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

try {
    $token = $_GET['token'] ?? '';
    $user_code = $_GET['user_code'] ?? '';
    
    if (empty($token) || empty($user_code)) {
        jsonResponse(false, 'Paramètres manquants');
    }
    
    $db = new Database();
    
    $sql = "SELECT s.*, u.is_session_open,
                   TIMESTAMPDIFF(MINUTE, NOW(), s.date_expiration) as minutes_left
            FROM Sessions s
            JOIN Utilisateurs u ON s.code_utilisateur = u.code_utilisateur
            WHERE s.jeton = ? 
            AND s.code_utilisateur = ?
            AND s.statut = 'ACTIVE'";
    
    $stmt = $db->executeQuery($sql, [$token, $user_code]);
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $session = $result->fetch_assoc();
        $stmt->close();
        
        $is_valid = ($session['minutes_left'] > 0 && $session['is_session_open'] == 'O');
        
        jsonResponse(true, 'Session vérifiée', [
            'is_valid' => $is_valid,
            'minutes_left' => (int)$session['minutes_left'],
            'expires_at' => $session['date_expiration'],
            'user_session_open' => $session['is_session_open']
        ]);
        
    } else {
        $stmt->close();
        jsonResponse(false, 'Session non trouvée ou expirée');
    }
    
    $db->close();
    
} catch (Exception $e) {
    jsonResponse(false, 'Erreur: ' . $e->getMessage());
}
?>