<?php
/**
 * unregister_token.php — Désinscription token FCM
 *
 * Retire le token FCM de la liste des tokens du client.
 * Appelé quand l'utilisateur se déconnecte ou change de client.
 *
 * POST /unregister_token.php
 * Content-Type: application/json
 * {"client_id": "Demo_01", "fcm_token": "fheHxy..."}
 */
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    die(json_encode(["success" => false, "message" => "Méthode non autorisée"]));
}

$input = json_decode(file_get_contents("php://input"), true);
$client_id = $input['client_id'] ?? '';
$fcm_token = $input['fcm_token'] ?? '';
$password  = $input['password'] ?? '';

if (empty($client_id) || empty($fcm_token) || empty($password)) {
    http_response_code(400);
    die(json_encode(["success" => false, "message" => "client_id, fcm_token et password requis"]));
}

$DB_FILE = "database.json";
$db = json_decode(file_get_contents($DB_FILE), true);
if (!$db || !isset($db['clients'])) {
    http_response_code(500);
    die(json_encode(["success" => false, "message" => "Base de données introuvable"]));
}

$found_key = null;
foreach ($db['clients'] as $key => $c) {
    if (strcasecmp($c['name'] ?? '', $client_id) === 0) {
        $found_key = $key;
        break;
    }
}

if ($found_key === null) {
    http_response_code(404);
    die(json_encode(["success" => false, "message" => "Client inconnu"]));
}

// Vérification mot de passe (bcrypt)
$password_hash = $db['clients'][$found_key]['password_hash'] ?? null;
if ($password_hash === null) {
    http_response_code(403);
    die(json_encode(["success" => false, "message" => "Compte non configuré"]));
}
if (!password_verify($password, $password_hash)) {
    http_response_code(401);
    die(json_encode(["success" => false, "message" => "Mot de passe incorrect"]));
}

if (isset($db['clients'][$found_key]['fcm_tokens'])) {
    $tokens = $db['clients'][$found_key]['fcm_tokens'];
    $new_tokens = array_values(array_filter($tokens, function($t) use ($fcm_token) {
        return $t !== $fcm_token;
    }));
    $db['clients'][$found_key]['fcm_tokens'] = $new_tokens;
    file_put_contents($DB_FILE, json_encode($db, JSON_PRETTY_PRINT));
    echo json_encode(["success" => true, "message" => "Token retiré"]);
} else {
    echo json_encode(["success" => true, "message" => "Aucun token à retirer"]);
}
?>
