<?php
// gpsmateriel.php
// URL: https://api.transub.dz/apihse/gpsmateriel.php
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");

// --- CONFIGURATION ---
$db_host = "localhost";
$db_name = "transubd_HSE";
$db_user = "transubd_transub_user";
$db_pass = "Tr@nsub2@24";

// La clé secrète qui doit être envoyée par l'application Android
$API_KEY = "Tr@nsub_GPS_2026";
$sync_interval_minutes = 1;
// ---------------------

// Vérification de la méthode POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(["status" => "error", "message" => "Method not allowed. Use POST."]);
    exit();
}

// Récupération et vérification de la clé API
$headers = apache_request_headers();
$received_key = isset($headers['X-API-KEY']) ? $headers['X-API-KEY'] : '';

if (empty($received_key) && isset($_SERVER['HTTP_X_API_KEY'])) {
    $received_key = $_SERVER['HTTP_X_API_KEY'];
}

if ($received_key !== $API_KEY) {
    http_response_code(401);
    echo json_encode(["status" => "error", "message" => "Unauthorized. Invalid API Key."]);
    exit();
}

// Lecture des données JSON envoyées par l'application
$json_data = file_get_contents("php://input");
$data = json_decode($json_data, true);

if (!isset($data['site']) || !isset($data['latitude']) || !isset($data['longitude'])) {
    http_response_code(400);
    echo json_encode(["status" => "error", "message" => "Missing required fields (site, latitude, longitude)."]);
    exit();
}

$site = htmlspecialchars(strip_tags($data['site']));
$latitude = filter_var($data['latitude'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
$longitude = filter_var($data['longitude'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);

try {
    // Connexion à la base de données
    $dsn = "mysql:host=" . $db_host . ";dbname=" . $db_name . ";charset=utf8mb4";
    $pdo = new PDO($dsn, $db_user, $db_pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Vérifier si le site existe déjà (et récupérer tel_urgence et annonce)
    $stmt_check = $pdo->prepare("SELECT id, tel_urgence, annonce FROM localisation_materiel WHERE site = :site LIMIT 1");
    $stmt_check->bindParam(':site', $site);
    $stmt_check->execute();

    // Valeurs par défaut au cas où les champs sont vides en base
    $tel_urgence = "0770253926";
    $annonce = "En attente de connexion...";

    if ($stmt_check->rowCount() > 0) {
        $row = $stmt_check->fetch(PDO::FETCH_ASSOC);
        
        // Assigner les valeurs dynamiques de la base de données si elles existent
        if (!empty($row['tel_urgence'])) {
            $tel_urgence = $row['tel_urgence'];
        }
        if (!empty($row['annonce'])) {
            $annonce = $row['annonce'];
        }

        // Le site existe : UPDATE
        $stmt_update = $pdo->prepare("UPDATE localisation_materiel SET longitude = :longitude, latitude = :latitude, last_sync = NOW() WHERE site = :site");
        $stmt_update->bindParam(':longitude', $longitude);
        $stmt_update->bindParam(':latitude', $latitude);
        $stmt_update->bindParam(':site', $site);
        
        if ($stmt_update->execute()) {
            http_response_code(200);
            echo json_encode([
                "status" => "success", 
                "message" => "Location updated successfully.",
                "sync_interval_minutes" => $sync_interval_minutes,
                "tel_urgence" => $tel_urgence,
                "annonce" => $annonce
            ]);
        } else {
            http_response_code(500);
            echo json_encode(["status" => "error", "message" => "Failed to update location."]);
        }
    } else {
        // Le site n'existe pas : INSERT
        $stmt_insert = $pdo->prepare("INSERT INTO localisation_materiel (site, longitude, latitude, last_sync, tel_urgence, annonce) VALUES (:site, :longitude, :latitude, NOW(), :tel_urgence, :annonce)");
        $stmt_insert->bindParam(':site', $site);
        $stmt_insert->bindParam(':longitude', $longitude);
        $stmt_insert->bindParam(':latitude', $latitude);
        $stmt_insert->bindParam(':tel_urgence', $tel_urgence);
        $stmt_insert->bindParam(':annonce', $annonce);
        
        if ($stmt_insert->execute()) {
            http_response_code(201);
            echo json_encode([
                "status" => "success", 
                "message" => "Location inserted successfully.",
                "sync_interval_minutes" => $sync_interval_minutes,
                "tel_urgence" => $tel_urgence,
                "annonce" => $annonce
            ]);
        } else {
            http_response_code(500);
            echo json_encode(["status" => "error", "message" => "Failed to insert location."]);
        }
    }
} catch(PDOException $e) {
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => "Database connection error."]);
}
?>
