<?php
declare(strict_types=1);

/**
 * API: get_home_loc.php
 * GET/POST:
 *   - imei=...
 * Optional:
 *   - debug=1 (mostra dettagli errori in risposta)
 */

header('Content-Type: application/json; charset=utf-8');

function respond(int $statusCode, array $payload): void {
    http_response_code($statusCode);
    echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

$imei = $_GET['imei'] ?? $_POST['imei'] ?? null;
$imei = is_string($imei) ? trim($imei) : null;

$debug = $_GET['debug'] ?? $_POST['debug'] ?? null;
$debug = ($debug === '1' || $debug === 1 || $debug === true || $debug === 'true');

if (!$imei) {
    respond(400, [
        "ok" => false,
        "error" => "Missing parameter: imei"
    ]);
}

// --- DB CONFIG (MODIFICA QUI SE SERVE) ---
$dbHost = "127.0.0.1";  // prova anche "localhost" se root dà problemi
$dbPort = 3306;
$dbName = "ev";
$dbUser = "root";
$dbPass = "jV9ELLV7!6rNm8GjV9ELLV7!6rNm8G";

// DSN (password NON va nella DSN)
$dsn = "mysql:host={$dbHost};port={$dbPort};dbname={$dbName};charset=utf8mb4";

try {
    $pdo = new PDO($dsn, $dbUser, $dbPass, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);
} catch (Throwable $e) {
    $payload = [
        "ok" => false,
        "error" => "DB connection error"
    ];
    if ($debug) {
        $payload["details"] = $e->getMessage();
        $payload["code"] = $e->getCode();
        $payload["dsn"] = $dsn;
        $payload["user"] = $dbUser;
    }
    respond(500, $payload);
}

// 1) Trovo device tramite IMEI
$stmt = $pdo->prepare("SELECT id, IMEI FROM devices WHERE IMEI = :imei LIMIT 1");
$stmt->execute([":imei" => $imei]);
$device = $stmt->fetch();

if (!$device) {
    respond(404, [
        "ok" => false,
        "error" => "Device not found for IMEI",
        "imei" => $imei
    ]);
}

$deviceId = (int)$device["id"];

// 2) Prendo l'ultimo messaggio per quel device
$stmt = $pdo->prepare("
    SELECT id, text, insert_time
    FROM device_messages
    WHERE id_devices = :id_devices
    ORDER BY insert_time DESC, id DESC
    LIMIT 1
");
$stmt->execute([":id_devices" => $deviceId]);
$msg = $stmt->fetch();

if (!$msg || !is_string($msg["text"]) || trim($msg["text"]) === "") {
    respond(404, [
        "ok" => false,
        "error" => "No messages found for device",
        "device_id" => $deviceId,
        "imei" => $imei
    ]);
}

// 3) Parse JSON robusto
$raw = trim($msg["text"]);
$data = json_decode($raw, true);

if (json_last_error() !== JSON_ERROR_NONE) {
    // tenta a ripulire slash (JSON salvato escapato)
    $raw2 = stripslashes($raw);
    $data = json_decode($raw2, true);
}

if (!is_array($data)) {
    respond(500, [
        "ok" => false,
        "error" => "Invalid JSON in device_messages.text",
        "message_id" => (int)$msg["id"],
        "imei" => $imei
    ]);
}

// 4) Estrazione stati
$homeBeaconLoc = $data["Body"]["GeneralData"]["GeneralDataStatus"]["HomeBeaconLoc"] ?? null;
$homeWIFILoc   = $data["Body"]["GeneralData"]["GeneralDataStatus"]["HomeWIFILoc"] ?? null;

// 5) Estrazione GPS
$latitude  = $data["Body"]["GPSLocation"]["Latitude"] ?? null;
$longitude = $data["Body"]["GPSLocation"]["Longitude"] ?? null;
$altitude  = $data["Body"]["GPSLocation"]["Altitude"] ?? null;

// Normalizzo booleani
$homeBeaconLoc = is_bool($homeBeaconLoc) ? $homeBeaconLoc : null;
$homeWIFILoc   = is_bool($homeWIFILoc) ? $homeWIFILoc : null;

respond(200, [
    "ok" => true,
    "imei" => $imei,
    "device_id" => $deviceId,
    "message" => [
        "id" => (int)$msg["id"],
        "insert_time" => $msg["insert_time"],
    ],
    "HomeBeaconLoc" => $homeBeaconLoc,
    "HomeWIFILoc" => $homeWIFILoc,
    "Latitude" => $latitude,
    "Longitude" => $longitude,
    "Altitude" => $altitude
]);
