<?php
header("Content-Type: application/json");

// CHEMINS ABSOLUS (Plus fiable)
$base_dir = __DIR__; // Le dossier où est ce fichier (/var/www/lucas)
$json_file = $base_dir . '/database.json';

if (!file_exists($json_file)) {
    http_response_code(500);
    die(json_encode(["status" => "error", "message" => "DB introuvable"]));
}
$db = json_decode(file_get_contents($json_file), true);

$client_input = $_REQUEST['client'] ?? ''; 
$token_input  = $_REQUEST['token'] ?? '';     
$user         = $_REQUEST['user'] ?? 'Inconnu';

$idx = -1;
if (isset($db['clients'])) {
    foreach ($db['clients'] as $i => $c) {
        if (strcasecmp($c['name'], $client_input) == 0 && $c['token'] === $token_input) {
            $idx = $i;
            break;
        }
    }
}

if ($idx === -1) {
    http_response_code(403);
    die(json_encode(["status" => "error", "message" => "Client ou Token incorrect"]));
}

// 1. RESET DB
$db['clients'][$idx]['alerte'] = false;
$db['clients'][$idx]['message'] = "✅ Intervention effectuée par $user. Système réarmé.";
$db['clients'][$idx]['last_update'] = date("d/m/Y H:i:s");
file_put_contents($json_file, json_encode($db, JSON_PRETTY_PRINT));

// 2. ARCHIVAGE ROBUSTE
$client_name = $db['clients'][$idx]['name'];
$source_dir = $base_dir . '/clients/' . $client_name . '/';
$archive_dir = $source_dir . 'archives/';

// Création dossier archives si besoin
if (!is_dir($archive_dir)) {
    if (!mkdir($archive_dir, 0777, true)) {
        die(json_encode(["status" => "error", "message" => "Impossible de créer le dossier archives (Permissions?)"]));
    }
}

// Déplacement des fichiers
$images = glob($source_dir . "*.jpg");
$moved = 0;

foreach($images as $img) {
    $filename = basename($img);
    if(rename($img, $archive_dir . $filename)) {
        $moved++;
    }
}

echo json_encode([
    "status" => "success", 
    "message" => "Reset OK. $moved images archivées."
]);
?>