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

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

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

$data = json_decode(file_get_contents('php://input'), true);
$location_id = $data['location_id'] ?? '';

if (empty($location_id)) {
    echo json_encode(['success' => false, 'message' => 'Location ID cannot be empty.']);
    exit;
}

try {
    $pdo = db();
    // Ensure the user owns this location before deleting
    $stmt = $pdo->prepare("DELETE FROM favorite_locations WHERE id = ? AND user_id = ?");
    $stmt->execute([$location_id, $_SESSION['user_id']]);

    if ($stmt->rowCount() > 0) {
        echo json_encode(['success' => true, 'message' => 'Location deleted successfully.']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Location not found or you do not have permission to delete it.']);
    }
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
