<?php
require_once '../includes/User.php';
require_once '../includes/db_config.php';

header('Content-Type: application/json');

if (!User::isLoggedIn() || !User::isAdmin()) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit;
}

$pdo = getDBConnection();
$action = $_POST['action'] ?? $_GET['action'] ?? '';

try {
    switch ($action) {
        case 'get_services':
            $stmt = $pdo->query("SELECT * FROM services ORDER BY created_at DESC");
            $services = $stmt->fetchAll(PDO::FETCH_ASSOC);
            echo json_encode(['success' => true, 'services' => $services]);
            break;

        case 'get_service':
            $id = $_GET['id'] ?? 0;
            $stmt = $pdo->prepare("SELECT * FROM services WHERE id = ?");
            $stmt->execute([$id]);
            $service = $stmt->fetch(PDO::FETCH_ASSOC);
            echo json_encode(['success' => true, 'service' => $service]);
            break;

        case 'save_service':
            $id = $_POST['id'] ?? null;
            $name = $_POST['name'] ?? '';
            $description = $_POST['description'] ?? '';
            $price = $_POST['price'] ?? 0;
            $category = $_POST['category'] ?? '';
            $image = $_POST['image'] ?? '';

            if (empty($name) || empty($description) || empty($category)) {
                echo json_encode(['success' => false, 'message' => 'Please fill in all required fields']);
                break;
            }

            if ($id) {
                $stmt = $pdo->prepare("UPDATE services SET name = ?, description = ?, price = ?, category = ?, image = ? WHERE id = ?");
                $stmt->execute([$name, $description, $price, $category, $image, $id]);
                $message = 'Service updated successfully';
            } else {
                $stmt = $pdo->prepare("INSERT INTO services (name, description, price, category, image) VALUES (?, ?, ?, ?, ?)");
                $stmt->execute([$name, $description, $price, $category, $image]);
                $message = 'Service created successfully';
            }

            echo json_encode(['success' => true, 'message' => $message]);
            break;

        case 'delete_service':
            $id = $_POST['id'] ?? 0;
            $stmt = $pdo->prepare("DELETE FROM services WHERE id = ?");
            $stmt->execute([$id]);
            echo json_encode(['success' => true, 'message' => 'Service deleted successfully']);
            break;

        case 'get_options':
            $service_id = $_GET['service_id'] ?? '';
            
            if ($service_id) {
                $stmt = $pdo->prepare("
                    SELECT so.*, s.name as service_name 
                    FROM service_options so 
                    LEFT JOIN services s ON so.service_id = s.id 
                    WHERE so.service_id = ? 
                    ORDER BY so.option_type, so.option_name
                ");
                $stmt->execute([$service_id]);
            } else {
                $stmt = $pdo->query("
                    SELECT so.*, s.name as service_name 
                    FROM service_options so 
                    LEFT JOIN services s ON so.service_id = s.id 
                    ORDER BY so.service_id, so.option_type, so.option_name
                ");
            }
            
            $options = $stmt->fetchAll(PDO::FETCH_ASSOC);
            echo json_encode(['success' => true, 'options' => $options]);
            break;

        case 'get_option':
            $id = $_GET['id'] ?? 0;
            $stmt = $pdo->prepare("SELECT * FROM service_options WHERE id = ?");
            $stmt->execute([$id]);
            $option = $stmt->fetch(PDO::FETCH_ASSOC);
            echo json_encode(['success' => true, 'option' => $option]);
            break;

        case 'save_option':
            $id = $_POST['id'] ?? null;
            $service_id = $_POST['service_id'] ?? 0;
            $option_type = $_POST['option_type'] ?? '';
            $option_name = $_POST['option_name'] ?? '';
            $option_value = $_POST['option_value'] ?? '';
            $price_modifier = $_POST['price_modifier'] ?? 0;

            if (empty($service_id) || empty($option_type) || empty($option_name) || empty($option_value)) {
                echo json_encode(['success' => false, 'message' => 'Please fill in all required fields']);
                break;
            }

            if ($id) {
                $stmt = $pdo->prepare("
                    UPDATE service_options 
                    SET service_id = ?, option_type = ?, option_name = ?, option_value = ?, price_modifier = ? 
                    WHERE id = ?
                ");
                $stmt->execute([$service_id, $option_type, $option_name, $option_value, $price_modifier, $id]);
                $message = 'Option updated successfully';
            } else {
                $stmt = $pdo->prepare("
                    INSERT INTO service_options (service_id, option_type, option_name, option_value, price_modifier) 
                    VALUES (?, ?, ?, ?, ?)
                ");
                $stmt->execute([$service_id, $option_type, $option_name, $option_value, $price_modifier]);
                $message = 'Option created successfully';
            }

            echo json_encode(['success' => true, 'message' => $message]);
            break;

        case 'delete_option':
            $id = $_POST['id'] ?? 0;
            $stmt = $pdo->prepare("DELETE FROM service_options WHERE id = ?");
            $stmt->execute([$id]);
            echo json_encode(['success' => true, 'message' => 'Option deleted successfully']);
            break;

        default:
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
            break;
    }
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
