<?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;
}

$customer_id = $_SESSION['user_id'];

try {
    // Get favorite properties (only if property still exists - use INNER JOIN instead of LEFT JOIN)
    $stmt = $conn->prepare("
        SELECT p.id, p.title, p.city, p.price, p.bedrooms, p.bathrooms, p.image_url, f.created_at
        FROM favorites f
        INNER JOIN properties p ON f.property_id = p.id
        WHERE f.customer_id = ?
        ORDER BY f.created_at DESC
        LIMIT 10
    ");
    $stmt->bind_param('i', $customer_id);
    $stmt->execute();
    $result = $stmt->get_result();

    $favorites = [];
    while ($row = $result->fetch_assoc()) {
        // Ensure all required fields are present and properly typed
        $favorites[] = [
            'id' => intval($row['id']),
            'title' => $row['title'] ?? 'Property',
            'city' => $row['city'] ?? 'Location',
            'price' => intval($row['price'] ?? 0),
            'bedrooms' => intval($row['bedrooms'] ?? 0),
            'bathrooms' => intval($row['bathrooms'] ?? 0),
            'image_url' => $row['image_url'] ?? ''
        ];
    }
    $stmt->close();

    echo json_encode(['success' => true, 'favorites' => $favorites]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>
