<?php
// C:\Application JAVA\ParkGare\apiparkgare\logout.php
require_once 'config/database.php';

try {
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);
    
    if (empty($data)) {
        $data = $_POST;
    }
    
    $errors = validateRequired($data, ['session_token', 'user_code']);
    if (!empty($errors)) {
        jsonResponse(false, implode(', ', $errors));
    }
    
    $session_token = $data['session_token'];
    $user_code = $data['user_code'];
    
    $db = new Database();
    $conn = $db->getConnection();
    
    // Mettre à jour l'utilisateur
    $update_user_sql = "UPDATE Utilisateurs 
                       SET is_session_open = 'N', 
                           session_id = NULL,
                           session_timestamp = NULL
                       WHERE code_utilisateur = ?";
    
    $update_user_stmt = $db->executeQuery($update_user_sql, [$user_code]);
    $update_user_stmt->close();
    
    // Fermer la session
    $update_session_sql = "UPDATE Sessions 
                          SET statut = 'RÉVOQUÉE'
                          WHERE jeton = ? 
                          AND code_utilisateur = ?";
    
    $update_session_stmt = $db->executeQuery($update_session_sql, [$session_token, $user_code]);
    $rows_affected = $update_session_stmt->affected_rows;
    $update_session_stmt->close();
    
    // Journaliser
    $log_sql = "INSERT INTO SystemLogs 
               (date_heure, type, code_utilisateur, description, statut)
               VALUES (NOW(), 'LOGIN', ?, 'Déconnexion réussie', 'SUCCES')";
    
    $log_stmt = $db->executeQuery($log_sql, [$user_code]);
    $log_stmt->close();
    
    jsonResponse(true, 'Déconnexion réussie', [
        'sessions_closed' => $rows_affected
    ]);
    
    $db->close();
    
} catch (Exception $e) {
    jsonResponse(false, 'Erreur de déconnexion: ' . $e->getMessage());
}
?>