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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Not logged in']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);
$customer_id = $_SESSION['user_id'];
$property_id = intval($input['property_id'] ?? 0);
$action = trim($input['action'] ?? '');

if ($property_id <= 0 || !in_array($action, ['add', 'remove'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid parameters']);
    exit;
}

try {
    // Ensure favorites table exists
    $createTable = "CREATE TABLE IF NOT EXISTS favorites (
        id INT AUTO_INCREMENT PRIMARY KEY,
        customer_id INT NOT NULL,
        property_id INT NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        UNIQUE KEY unique_fav (customer_id, property_id)
    )";
    $conn->query($createTable);

    if ($action === 'add') {
        // Add to favorites
        $stmt = $conn->prepare("INSERT INTO favorites (customer_id, property_id) VALUES (?, ?)");
        $stmt->bind_param('ii', $customer_id, $property_id);
        $result = $stmt->execute();
        $stmt->close();

        if ($result) {
            echo json_encode(['success' => true, 'message' => 'Added to favorites']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to add']);
        }
    } else {
        // Remove from favorites
        $stmt = $conn->prepare("DELETE FROM favorites WHERE customer_id = ? AND property_id = ?");
        $stmt->bind_param('ii', $customer_id, $property_id);
        $result = $stmt->execute();
        $stmt->close();

        if ($result) {
            echo json_encode(['success' => true, 'message' => 'Removed from favorites']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to remove']);
        }
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>
