<?php
require_once 'db.php'; 
$data = json_decode(file_get_contents("php://input"));

if (!isset($data->user_id) || !isset($data->label) || !isset($data->address) || !isset($data->latitude) || !isset($data->longitude)) {
    http_response_code(400); echo json_encode(["error" => "Data tidak lengkap."]); exit();
}

try {
    // Reset status default alamat lain (agar yg baru jadi default)
    $stmt0 = $conn->prepare("UPDATE user_addresses SET is_default = 0 WHERE user_id = :uid");
    $stmt0->bindParam(':uid', $data->user_id);
    $stmt0->execute();

    // Tambah alamat baru
    $sql = "INSERT INTO user_addresses (user_id, label, address, latitude, longitude, is_default)
            VALUES (:user_id, :label, :address, :lat, :lng, 1)";
    $stmt = $conn->prepare($sql);
    $stmt->bindParam(':user_id', $data->user_id);
    $stmt->bindParam(':label', $data->label);
    $stmt->bindParam(':address', $data->address);
    $stmt->bindParam(':lat', $data->latitude);
    $stmt->bindParam(':lng', $data->longitude);
    $stmt->execute();

    http_response_code(201);
    echo json_encode(["status" => "success", "message" => "Alamat berhasil disimpan!"]);
} catch (PDOException $e) {
    http_response_code(500); echo json_encode(["error" => $e->getMessage()]);
}
?>