<?php
session_start();
require_once __DIR__ . '/../config/db.php';

// Set content type first
header('Content-Type: application/json');

// Check if user is logged in and has staff/admin role
if (!isset($_SESSION['user_id'])) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'User not authenticated. Please log in first.']);
    exit;
}

if (!in_array((string)($_SESSION['user_role'] ?? ''), ['admin', 'staff'], true)) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'You do not have permission to manage services.']);
    exit;
}

$response = ['success' => false, 'message' => 'Unknown error'];

try {
    // Verify database connection
    if (!isset($connection) || $connection->ping() === false) {
        throw new Exception('Database connection failed');
    }
    
    // Create services table if it doesn't exist
    $connection->query("CREATE TABLE IF NOT EXISTS services (
        id INT AUTO_INCREMENT PRIMARY KEY,
        title VARCHAR(255) NOT NULL,
        image VARCHAR(500),
        link VARCHAR(500) DEFAULT '#',
        description TEXT NOT NULL,
        area_sqft INT,
        price DECIMAL(10, 2),
        duration VARCHAR(100),
        status VARCHAR(50) DEFAULT 'ACTIVE',
        sort_order INT NOT NULL DEFAULT 0,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    // Create service_products table
    $connection->query("CREATE TABLE IF NOT EXISTS service_products (
        id INT AUTO_INCREMENT PRIMARY KEY,
        service_id INT NOT NULL,
        product_name VARCHAR(255) NOT NULL,
        cost DECIMAL(10, 2),
        quantity VARCHAR(100),
        spot_x DECIMAL(5,2) NULL,
        spot_y DECIMAL(5,2) NULL,
        sort_order INT DEFAULT 0,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (service_id) REFERENCES services(id) ON DELETE CASCADE,
        INDEX idx_service_id (service_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    $connection->query("ALTER TABLE service_products ADD COLUMN IF NOT EXISTS spot_x DECIMAL(5,2) NULL");
    $connection->query("ALTER TABLE service_products ADD COLUMN IF NOT EXISTS spot_y DECIMAL(5,2) NULL");

    // Create service_tools table
    $connection->query("CREATE TABLE IF NOT EXISTS service_tools (
        id INT AUTO_INCREMENT PRIMARY KEY,
        service_id INT NOT NULL,
        tool_name VARCHAR(255) NOT NULL,
        tool_description TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (service_id) REFERENCES services(id) ON DELETE CASCADE,
        INDEX idx_service_id (service_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    // Get POST data
    $action = isset($_POST['action']) ? $_POST['action'] : '';

    if ($action === 'add_service') {
        $title = isset($_POST['title']) ? trim($_POST['title']) : '';
        $description = isset($_POST['description']) ? trim($_POST['description']) : '';
        $area = isset($_POST['area']) ? intval($_POST['area']) : 0;
        $basePrice = isset($_POST['basePrice']) ? floatval($_POST['basePrice']) : 0;
        $duration = isset($_POST['duration']) ? trim($_POST['duration']) : '';
        $status = isset($_POST['status']) ? trim($_POST['status']) : 'ACTIVE';
        
        // Decode products and tools JSON
        $productsJson = isset($_POST['products']) ? $_POST['products'] : '[]';
        $toolsJson = isset($_POST['tools']) ? $_POST['tools'] : '[]';
        
        $products = json_decode($productsJson, true);
        $tools = json_decode($toolsJson, true);
        
        // Validate JSON decoding
        if ($products === null && $productsJson !== '[]') {
            throw new Exception('Invalid products JSON format');
        }
        if ($tools === null && $toolsJson !== '[]') {
            throw new Exception('Invalid tools JSON format');
        }
        
        if (empty($products)) $products = [];
        if (empty($tools)) $tools = [];

        if (!$title || !$description || !$basePrice) {
            throw new Exception('Missing required fields: title, description, or price');
        }

        // Handle image upload
        $imagePath = '';
        if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
            $uploadDir = __DIR__ . '/../assets/img/service/';
            if (!is_dir($uploadDir)) {
                if (!mkdir($uploadDir, 0755, true)) {
                    throw new Exception('Failed to create upload directory');
                }
            }

            $fileName = 'service_' . time() . '_' . basename($_FILES['image']['name']);
            $filePath = $uploadDir . $fileName;

            if (move_uploaded_file($_FILES['image']['tmp_name'], $filePath)) {
                $imagePath = 'assets/img/service/' . $fileName;
            } else {
                throw new Exception('Failed to upload image file');
            }
        }

        // Insert service
        $stmt = $connection->prepare("
            INSERT INTO services (title, image, description, area_sqft, price, duration, status, is_active)
            VALUES (?, ?, ?, ?, ?, ?, ?, 1)
        ");

        if (!$stmt) {
            throw new Exception($connection->error);
        }

        $stmt->bind_param('sssidss', $title, $imagePath, $description, $area, $basePrice, $duration, $status);

        if (!$stmt->execute()) {
            throw new Exception($stmt->error);
        }

        $serviceId = $connection->insert_id;
        $stmt->close();

        // Insert products
        if (!empty($products)) {
            $productStmt = $connection->prepare("
                INSERT INTO service_products (service_id, product_name, cost, quantity, sort_order, spot_x, spot_y)
                VALUES (?, ?, ?, ?, ?, NULLIF(?, ''), NULLIF(?, ''))
            ");

            if (!$productStmt) {
                throw new Exception($connection->error);
            }

            foreach ($products as $index => $product) {
                $productName = isset($product['name']) ? trim($product['name']) : '';
                $productCost = isset($product['cost']) ? floatval($product['cost']) : 0;
                $productQty = isset($product['qty']) ? trim($product['qty']) : '';
                $productX = isset($product['x']) && $product['x'] !== null ? (string)floatval($product['x']) : '';
                $productY = isset($product['y']) && $product['y'] !== null ? (string)floatval($product['y']) : '';
                $sortOrder = (int)$index;

                $productStmt->bind_param('isdsiss', $serviceId, $productName, $productCost, $productQty, $sortOrder, $productX, $productY);

                if (!$productStmt->execute()) {
                    throw new Exception($productStmt->error);
                }
            }

            $productStmt->close();
        }

        // Insert tools
        if (!empty($tools)) {
            $toolStmt = $connection->prepare("
                INSERT INTO service_tools (service_id, tool_name, tool_description)
                VALUES (?, ?, ?)
            ");

            if (!$toolStmt) {
                throw new Exception($connection->error);
            }

            foreach ($tools as $tool) {
                $toolName = isset($tool['name']) ? trim($tool['name']) : '';
                $toolDesc = isset($tool['desc']) ? trim($tool['desc']) : '';

                $toolStmt->bind_param('iss', $serviceId, $toolName, $toolDesc);

                if (!$toolStmt->execute()) {
                    throw new Exception($toolStmt->error);
                }
            }

            $toolStmt->close();
        }

        $response = [
            'success' => true,
            'message' => 'Service added successfully',
            'serviceId' => $serviceId
        ];

    } else if ($action === 'update_service') {
        $serviceId = isset($_POST['service_id']) ? intval($_POST['service_id']) : 0;
        $title = isset($_POST['title']) ? trim($_POST['title']) : '';
        $image = isset($_POST['image']) ? trim($_POST['image']) : '';
        $description = isset($_POST['description']) ? trim($_POST['description']) : '';
        $link = isset($_POST['link']) ? trim($_POST['link']) : '#';
        $area = isset($_POST['area']) ? intval($_POST['area']) : 0;
        $basePrice = isset($_POST['basePrice']) ? floatval($_POST['basePrice']) : 0;
        $duration = isset($_POST['duration']) ? trim($_POST['duration']) : '';
        $status = isset($_POST['status']) ? trim($_POST['status']) : 'ACTIVE';
        $products = isset($_POST['products']) ? json_decode($_POST['products'], true) : [];
        $tools = isset($_POST['tools']) ? json_decode($_POST['tools'], true) : [];

        if (!$serviceId || !$title || !$description) {
            throw new Exception('Missing required fields');
        }

        // Update service - check if image is provided
        if (!empty($image)) {
            $stmt = $connection->prepare("
                UPDATE services 
                SET title = ?, image = ?, description = ?, link = ?, area_sqft = ?, price = ?, duration = ?, status = ?
                WHERE id = ?
            ");
            $stmt->bind_param('sssssidsi', $title, $image, $description, $link, $area, $basePrice, $duration, $status, $serviceId);
        } else {
            $stmt = $connection->prepare("
                UPDATE services 
                SET title = ?, description = ?, link = ?, area_sqft = ?, price = ?, duration = ?, status = ?
                WHERE id = ?
            ");
            $stmt->bind_param('sssidsi', $title, $description, $link, $area, $basePrice, $duration, $status, $serviceId);
        }

        if (!$stmt) {
            throw new Exception($connection->error);
        }

        if (!$stmt->execute()) {
            throw new Exception($stmt->error);
        }

        $stmt->close();

        // Delete and re-insert products if provided
        if (!empty($products) || isset($_POST['products'])) {
            $connection->query("DELETE FROM service_products WHERE service_id = " . intval($serviceId));

            if (!empty($products)) {
                $productStmt = $connection->prepare("
                    INSERT INTO service_products (service_id, product_name, cost, quantity, sort_order, spot_x, spot_y)
                    VALUES (?, ?, ?, ?, ?, NULLIF(?, ''), NULLIF(?, ''))
                ");

                if (!$productStmt) {
                    throw new Exception($connection->error);
                }

                foreach ($products as $index => $product) {
                    $productName = isset($product['name']) ? trim($product['name']) : '';
                    $productCost = isset($product['cost']) ? floatval($product['cost']) : 0;
                    $productQty = isset($product['qty']) ? trim($product['qty']) : '';
                    $productX = isset($product['x']) && $product['x'] !== null ? (string)floatval($product['x']) : '';
                    $productY = isset($product['y']) && $product['y'] !== null ? (string)floatval($product['y']) : '';
                    $sortOrder = (int)$index;

                    $productStmt->bind_param('isdsiss', $serviceId, $productName, $productCost, $productQty, $sortOrder, $productX, $productY);
                    if (!$productStmt->execute()) {
                        throw new Exception($productStmt->error);
                    }
                }

                $productStmt->close();
            }
        }

        // Delete and re-insert tools if provided
        if (!empty($tools) || isset($_POST['tools'])) {
            $connection->query("DELETE FROM service_tools WHERE service_id = " . intval($serviceId));

            if (!empty($tools)) {
                $toolStmt = $connection->prepare("
                    INSERT INTO service_tools (service_id, tool_name, tool_description)
                    VALUES (?, ?, ?)
                ");

                if (!$toolStmt) {
                    throw new Exception($connection->error);
                }

                foreach ($tools as $tool) {
                    $toolName = isset($tool['name']) ? trim($tool['name']) : '';
                    $toolDesc = isset($tool['desc']) ? trim($tool['desc']) : '';

                    $toolStmt->bind_param('iss', $serviceId, $toolName, $toolDesc);
                    if (!$toolStmt->execute()) {
                        throw new Exception($toolStmt->error);
                    }
                }

                $toolStmt->close();
            }
        }

        $response = [
            'success' => true,
            'message' => 'Service updated successfully'
        ];

    } else if ($action === 'delete_service') {
        $serviceId = isset($_POST['service_id']) ? intval($_POST['service_id']) : 0;

        if (!$serviceId) {
            throw new Exception('Service ID is required');
        }

        // Delete associated records
        $connection->query("DELETE FROM service_products WHERE service_id = " . $serviceId);
        $connection->query("DELETE FROM service_tools WHERE service_id = " . $serviceId);

        // Delete service
        $stmt = $connection->prepare("DELETE FROM services WHERE id = ?");
        $stmt->bind_param('i', $serviceId);

        if (!$stmt->execute()) {
            throw new Exception($stmt->error);
        }

        $stmt->close();

        $response = [
            'success' => true,
            'message' => 'Service deleted successfully'
        ];
    }

} catch (Exception $e) {
    http_response_code(400);
    $response['message'] = 'Error: ' . $e->getMessage();
    $response['error_details'] = [
        'type' => get_class($e),
        'file' => basename($e->getFile()),
        'line' => $e->getLine()
    ];
}

echo json_encode($response);
exit;
