<?php
session_start();
header('Content-Type: application/json');
require_once __DIR__ . '/../config/db.php';

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode([
        'success' => false,
        'message' => 'User not authenticated'
    ]);
    exit;
}

$userId = (int) $_SESSION['user_id'];
$action = $_GET['action'] ?? '';

function ensureServiceFavoritesTable(mysqli $connection): bool
{
    $sql = "CREATE TABLE IF NOT EXISTS service_favorites (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT NOT NULL,
        service_id INT NOT NULL,
        service_title VARCHAR(255) NOT NULL,
        service_image VARCHAR(500) NOT NULL,
        service_description TEXT,
        added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        UNIQUE KEY unique_user_service (user_id, service_id),
        INDEX idx_user_id (user_id),
        INDEX idx_service_id (service_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";

    return (bool) $connection->query($sql);
}

if (!ensureServiceFavoritesTable($connection)) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Failed to initialize favorites table'
    ]);
    exit;
}

try {
    if ($action === 'add') {
        $payload = json_decode(file_get_contents('php://input'), true);
        $serviceId = (int) ($payload['service_id'] ?? 0);
        $serviceTitle = trim((string) ($payload['service_title'] ?? ''));
        $serviceImage = trim((string) ($payload['service_image'] ?? ''));
        $serviceDescription = trim((string) ($payload['service_description'] ?? ''));

        if ($serviceId <= 0 || $serviceTitle === '' || $serviceImage === '') {
            throw new RuntimeException('Missing required service fields');
        }

        $stmt = $connection->prepare("
            INSERT INTO service_favorites (user_id, service_id, service_title, service_image, service_description)
            VALUES (?, ?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE
                service_title = VALUES(service_title),
                service_image = VALUES(service_image),
                service_description = VALUES(service_description)
        ");

        if (!$stmt) {
            throw new RuntimeException('Prepare failed');
        }

        $stmt->bind_param('iisss', $userId, $serviceId, $serviceTitle, $serviceImage, $serviceDescription);
        $stmt->execute();
        $stmt->close();

        echo json_encode([
            'success' => true,
            'message' => 'Service added to favorites',
            'service_id' => $serviceId
        ]);
        exit;
    }

    if ($action === 'remove') {
        $payload = json_decode(file_get_contents('php://input'), true);
        $serviceId = (int) ($payload['service_id'] ?? 0);
        if ($serviceId <= 0) {
            throw new RuntimeException('Invalid service_id');
        }

        $stmt = $connection->prepare("DELETE FROM service_favorites WHERE user_id = ? AND service_id = ?");
        if (!$stmt) {
            throw new RuntimeException('Prepare failed');
        }

        $stmt->bind_param('ii', $userId, $serviceId);
        $stmt->execute();
        $stmt->close();

        echo json_encode([
            'success' => true,
            'message' => 'Service removed from favorites',
            'service_id' => $serviceId
        ]);
        exit;
    }

    if ($action === 'get_all') {
        $stmt = $connection->prepare("
            SELECT service_id, service_title, service_image, service_description, added_at
            FROM service_favorites
            WHERE user_id = ?
            ORDER BY added_at DESC
        ");

        if (!$stmt) {
            throw new RuntimeException('Prepare failed');
        }

        $stmt->bind_param('i', $userId);
        $stmt->execute();
        $result = $stmt->get_result();

        $favorites = [];
        while ($result && $row = $result->fetch_assoc()) {
            $favorites[] = $row;
        }
        $stmt->close();

        echo json_encode([
            'success' => true,
            'count' => count($favorites),
            'favorites' => $favorites
        ]);
        exit;
    }

    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => 'Invalid action'
    ]);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Server error: ' . $e->getMessage()
    ]);
}
