<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");

/**
 * ENDPOINT D'AUTHENTIFICATION LUCASAPP
 *
 * Reçoit : client_id, password, fcm_token (optionnel)
 * Retourne : token, infos client si authentification OK
 */

// --- 1. CHARGEMENT BASE DE DONNÉES ---
$json_file = '../database.json';
if (!file_exists($json_file)) {
    http_response_code(500);
    die(json_encode(["status" => "error", "message" => "Base de données introuvable"]));
}
$db = json_decode(file_get_contents($json_file), true);

// --- 2. RÉCEPTION DONNÉES ---
$input = json_decode(file_get_contents('php://input'), true);
$client_id = $input['client_id'] ?? '';
$password = $input['password'] ?? '';
$fcm_token = $input['fcm_token'] ?? null;

if (empty($client_id) || empty($password)) {
    http_response_code(400);
    die(json_encode(["status" => "error", "message" => "Identifiant et mot de passe requis"]));
}

// --- 3. RECHERCHE CLIENT ---
$client_index = -1;
$current_client = null;

if (isset($db['clients'])) {
    foreach ($db['clients'] as $index => $c) {
        if (strcasecmp($c['name'], $client_id) == 0) {
            $client_index = $index;
            $current_client = $c;
            break;
        }
    }
}

if ($client_index === -1) {
    http_response_code(403);
    die(json_encode(["status" => "error", "message" => "Identifiant inconnu"]));
}

// --- 4. VÉRIFICATION MOT DE PASSE ---
$password_hash = $current_client['password_hash'] ?? null;

if ($password_hash === null) {
    http_response_code(403);
    die(json_encode(["status" => "error", "message" => "Compte non configuré. Contactez l'administrateur."]));
}

if (!password_verify($password, $password_hash)) {
    http_response_code(403);
    die(json_encode(["status" => "error", "message" => "Mot de passe incorrect"]));
}

// --- 5. ENREGISTREMENT FCM TOKEN (si fourni) ---
if ($fcm_token !== null) {
    if (!isset($current_client['fcm_tokens'])) {
        $current_client['fcm_tokens'] = [];
    }

    // Ajouter le token s'il n'existe pas déjà
    if (!in_array($fcm_token, $current_client['fcm_tokens'])) {
        $current_client['fcm_tokens'][] = $fcm_token;
        $db['clients'][$client_index]['fcm_tokens'] = $current_client['fcm_tokens'];
        file_put_contents($json_file, json_encode($db, JSON_PRETTY_PRINT));
    }
}

// --- 6. RÉPONSE SUCCÈS ---
echo json_encode([
    "status" => "success",
    "message" => "Authentification réussie",
    "data" => [
        "token" => $current_client['token'],
        "client_name" => $current_client['name'],
        "senior_name" => $current_client['senior_name'] ?? '',
        "senior_nickname" => $current_client['senior_nickname'] ?? '',
        "senior_photo" => $current_client['senior_photo'] ?? '',
        "latitude" => $current_client['latitude'] ?? '',
        "longitude" => $current_client['longitude'] ?? '',
        "emergency_number" => $current_client['emergency_number'] ?? '15',
        "contacts" => $current_client['contacts'] ?? [],
        "site_status" => $current_client['site_status'] ?? 'provisioned'
    ]
]);
?>
