<?php
// /home/transubd/public_html/api.transub.dz/apiparkgare/system_log.php
require_once 'config/database.php';

try {
    // Récupérer les paramètres
    $session_token = $_GET['token'] ?? '';
    $user_code = $_GET['user_code'] ?? '';
    $type = $_GET['type'] ?? ''; // LOGIN, SYNC, ERROR, PRINT
    $limit = min($_GET['limit'] ?? 50, 100); // Limite à 100 max
    $start_date = $_GET['start_date'] ?? date('Y-m-d', strtotime('-7 days'));
    $end_date = $_GET['end_date'] ?? date('Y-m-d');
    
    if (empty($session_token) || empty($user_code)) {
        jsonResponse(false, 'Paramètres manquants', [], 400);
    }
    
    $db = Database::getInstance();
    
    // Vérifier la session et les permissions
    $check_sql = "SELECT u.role, u.SiteID FROM Sessions s
                 JOIN Utilisateurs u ON s.code_utilisateur = u.code_utilisateur
                 WHERE s.jeton = ? 
                 AND s.code_utilisateur = ?
                 AND s.statut = 'ACTIVE'
                 AND s.date_expiration > NOW()";
    
    $check_stmt = $db->executeQuery($check_sql, [$session_token, $user_code]);
    $check_result = $check_stmt->get_result();
    
    if ($check_result->num_rows === 0) {
        $check_stmt->close();
        jsonResponse(false, 'Session invalide ou expirée', [], 403);
    }
    
    $user = $check_result->fetch_assoc();
    $check_stmt->close();
    
    // Construire la requête
    $sql = "SELECT l.*, u.NomPrenom, s.Nom_Site 
           FROM SystemLogs l
           LEFT JOIN Utilisateurs u ON l.code_utilisateur = u.code_utilisateur
           LEFT JOIN Sites s ON l.SiteID = s.SiteID
           WHERE l.date_heure BETWEEN ? AND DATE_ADD(?, INTERVAL 1 DAY)";
    
    $params = [$start_date, $end_date];
    $types = "ss";
    
    // Filtrer par type si spécifié
    if (!empty($type)) {
        $sql .= " AND l.type = ?";
        $params[] = $type;
        $types .= "s";
    }
    
    // Filtrer par site si l'utilisateur n'est pas admin
    if ($user['role'] != 'Administrateur') {
        $sql .= " AND l.SiteID = ?";
        $params[] = $user['SiteID'];
        $types .= "s";
    }
    
    $sql .= " ORDER BY l.date_heure DESC LIMIT ?";
    $params[] = $limit;
    $types .= "i";
    
    // Exécuter la requête
    $stmt = $db->executeQuery($sql, $params, $types);
    $result = $stmt->get_result();
    
    $logs = [];
    $stats = [
        'LOGIN' => 0,
        'SYNC' => 0,
        'ERROR' => 0,
        'PRINT' => 0,
        'SUCCES' => 0,
        'ECHEC' => 0
    ];
    
    while ($row = $result->fetch_assoc()) {
        $log = [
            'id' => (int)$row['id_log'],
            'date_heure' => $row['date_heure'],
            'type' => $row['type'],
            'user_code' => $row['code_utilisateur'],
            'user_name' => $row['NomPrenom'],
            'site_id' => $row['SiteID'],
            'site_name' => $row['Nom_Site'],
            'description' => $row['description'],
            'statut' => $row['statut'],
            'formatted' => "[" . $row['date_heure'] . "] " . 
                          $row['type'] . " | " . 
                          ($row['NomPrenom'] ?? $row['code_utilisateur']) . 
                          " | " . $row['description'] . 
                          " | " . $row['statut']
        ];
        
        $logs[] = $log;
        
        // Mettre à jour les statistiques
        $stats[$row['type']]++;
        $stats[$row['statut']]++;
    }
    $stmt->close();
    
    // Récupérer les statistiques globales
    $global_sql = "SELECT 
                  COUNT(*) as total_logs,
                  COUNT(DISTINCT code_utilisateur) as unique_users,
                  COUNT(DISTINCT SiteID) as unique_sites,
                  MIN(date_heure) as first_log,
                  MAX(date_heure) as last_log
                  FROM SystemLogs 
                  WHERE date_heure BETWEEN ? AND DATE_ADD(?, INTERVAL 1 DAY)";
    
    $global_stmt = $db->executeQuery($global_sql, [$start_date, $end_date]);
    $global_stats = $global_stmt->get_result()->fetch_assoc();
    $global_stmt->close();
    
    $response_data = [
        'logs' => $logs,
        'pagination' => [
            'total' => count($logs),
            'limit' => (int)$limit,
            'has_more' => count($logs) >= $limit
        ],
        'filters' => [
            'type' => $type,
            'start_date' => $start_date,
            'end_date' => $end_date,
            'user_role' => $user['role'],
            'user_site' => $user['SiteID']
        ],
        'statistics' => [
            'by_type' => [
                'LOGIN' => $stats['LOGIN'],
                'SYNC' => $stats['SYNC'],
                'ERROR' => $stats['ERROR'],
                'PRINT' => $stats['PRINT']
            ],
            'by_status' => [
                'SUCCES' => $stats['SUCCES'],
                'ECHEC' => $stats['ECHEC']
            ],
            'global' => [
                'total_logs' => (int)$global_stats['total_logs'],
                'unique_users' => (int)$global_stats['unique_users'],
                'unique_sites' => (int)$global_stats['unique_sites'],
                'period' => [
                    'first_log' => $global_stats['first_log'],
                    'last_log' => $global_stats['last_log'],
                    'days_covered' => round((strtotime($global_stats['last_log']) - strtotime($global_stats['first_log'])) / (60 * 60 * 24), 2)
                ]
            ]
        ],
        'timestamp' => date('Y-m-d H:i:s')
    ];
    
    jsonResponse(true, 'Journaux système récupérés', $response_data, 200);
    
} catch (Exception $e) {
    jsonResponse(false, 'Erreur de récupération des journaux: ' . $e->getMessage(), [], 500);
}
?>