<?php
/**
 * API Dashboard - Statistiques et données du tableau de bord
 * Répertoire: Includes/Dashboard/
 * Sécurisée avec authentification
 */

include_once __DIR__ . '/../auth_check.php';

// Rate limiting par IP
checkRateLimit($_SERVER['REMOTE_ADDR'] ?? 'unknown');

// Connexion à la base de données
$pdo = getDbConnection();

// Vérifier l'authentification pour le dashboard
$auth = checkApiAuth($pdo);
if (!$auth['success']) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Authentification requise']);
    exit;
}

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? 'stats';

try {
    if ($method === 'GET') {
        if ($action === 'stats') {
            // Statistiques générales
            $stats = [];
            
            // Nombre de sites
            $stmt = $pdo->query("SELECT COUNT(*) as count FROM Sites");
            $stats['sites'] = $stmt->fetch()['count'];
            
            // Nombre d'utilisateurs
            $stmt = $pdo->query("SELECT COUNT(*) as count FROM Utilisateurs");
            $stats['users'] = $stmt->fetch()['count'];
            
            // Nombre de lignes
            $stmt = $pdo->query("SELECT COUNT(*) as count FROM Lignes");
            $stats['lignes'] = $stmt->fetch()['count'];
            
            // Nombre de bus
            $stmt = $pdo->query("SELECT COUNT(*) as count FROM BusGares");
            $stats['bus'] = $stmt->fetch()['count'];
            
            // Nombre d'arrêts
            $stmt = $pdo->query("SELECT COUNT(*) as count FROM Arrets");
            $stats['arrets'] = $stmt->fetch()['count'];
            
            // Today's stats
            $today = date('Y-m-d');
            
            // Nombre de départs aujourd'hui
            $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM Departs WHERE DateDepart = ?");
            $stmt->execute([$today]);
            $stats['departures_today'] = $stmt->fetch()['count'];
            
            // Nombre de tickets aujourd'hui
            $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM Tickets WHERE DATE(DateVente) = ?");
            $stmt->execute([$today]);
            $stats['tickets_today'] = $stmt->fetch()['count'];
            
            echo json_encode(['success' => true, 'data' => $stats]);
            exit;
        }
        
        if ($action === 'recent') {
            // Dernières activités
            $limit = $_GET['limit'] ?? 10;
            $stmt = $pdo->prepare("
                SELECT DateJournal, TimeJournal, OperateurID, Action, Details 
                FROM Journalisation 
                ORDER BY DateJournal DESC, TimeJournal DESC 
                LIMIT ?
            ");
            $stmt->execute([$limit]);
            echo json_encode(['success' => true, 'data' => $stmt->fetchAll()]);
            exit;
        }
        
        if ($action === 'sales') {
            // Ventes par jour (derniers 7 jours)
            $stmt = $pdo->query("
                SELECT DATE(DateVente) as date, COUNT(*) as count, SUM(MontantTotal) as total 
                FROM Tickets 
                WHERE DateVente >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
                GROUP BY DATE(DateVente)
                ORDER BY date
            ");
            echo json_encode(['success' => true, 'data' => $stmt->fetchAll()]);
            exit;
        }
        
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Action invalide']);
        exit;
    }
    
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Méthode non supportée']);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Erreur: ' . $e->getMessage()]);
}
?>
