<?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);
$city_name = $data['city_name'] ?? '';

if (empty($city_name)) {
    echo json_encode(['success' => false, 'message' => 'City name cannot be empty.']);
    exit;
}

try {
    $pdo = db();
    $stmt = $pdo->prepare("INSERT INTO favorite_locations (user_id, city_name) VALUES (?, ?)");
    $stmt->execute([$_SESSION['user_id'], $city_name]);
    echo json_encode(['success' => true, 'message' => 'Location saved successfully.', 'location_id' => $pdo->lastInsertId()]);
} catch (PDOException $e) {
    // Check for duplicate entry
    if ($e->errorInfo[1] == 1062) {
        echo json_encode(['success' => false, 'message' => 'Location already saved.']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
    }
}
