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

try {
    // Récupérer les données
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);
    
    if (empty($data)) {
        $data = $_GET;
    }
    
    // Validation
    $errors = validateInput($data, ['session_token', 'user_code', 'site_id']);
    if (!empty($errors)) {
        jsonResponse(false, implode(', ', $errors), [], 400);
    }
    
    $session_token = $data['session_token'];
    $user_code = $data['user_code'];
    $site_id = $data['site_id'];
    $date = $data['date'] ?? date('Y-m-d');
    
    $db = Database::getInstance();
    
    // Vérifier la session
    $check_sql = "SELECT s.* FROM Sessions s
                 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]);
    if ($check_stmt->get_result()->num_rows === 0) {
        $check_stmt->close();
        jsonResponse(false, 'Session invalide ou expirée', [], 403);
    }
    $check_stmt->close();
    
    // Récupérer le rapport journalier
    $report_sql = "SELECT * FROM DailyReports 
                  WHERE code_utilisateur = ? 
                  AND SiteID = ?
                  AND date_rapport = ?
                  ORDER BY date_synchronisation DESC LIMIT 1";
    
    $report_stmt = $db->executeQuery($report_sql, [$user_code, $site_id, $date]);
    $report_result = $report_stmt->get_result();
    
    if ($report_result->num_rows > 0) {
        $report = $report_result->fetch_assoc();
        $report_stmt->close();
        
        // Récupérer les détails des tickets
        $tickets_sql = "SELECT numero_ticket, date_heure, prix 
                       FROM Tickets_Parking 
                       WHERE code_utilisateur = ? 
                       AND SiteID = ?
                       AND DATE(date_heure) = ?
                       ORDER BY date_heure";
        
        $tickets_stmt = $db->executeQuery($tickets_sql, [$user_code, $site_id, $date]);
        $tickets_result = $tickets_stmt->get_result();
        
        $tickets = [];
        while ($ticket = $tickets_result->fetch_assoc()) {
            $tickets[] = [
                'numero' => $ticket['numero_ticket'],
                'date_heure' => $ticket['date_heure'],
                'prix' => (float)$ticket['prix']
            ];
        }
        $tickets_stmt->close();
        
        // Récupérer les statistiques
        $stats_sql = "SELECT 
                      COUNT(*) as total_tickets,
                      SUM(prix) as total_amount,
                      MIN(date_heure) as first_ticket_time,
                      MAX(date_heure) as last_ticket_time,
                      AVG(prix) as average_price
                      FROM Tickets_Parking 
                      WHERE code_utilisateur = ? 
                      AND SiteID = ?
                      AND DATE(date_heure) = ?";
        
        $stats_stmt = $db->executeQuery($stats_sql, [$user_code, $site_id, $date]);
        $stats = $stats_stmt->get_result()->fetch_assoc();
        $stats_stmt->close();
        
        $response_data = [
            'report' => [
                'date' => $report['date_rapport'],
                'nombre_tickets' => (int)$report['nombre_tickets'],
                'montant_total' => (float)$report['montant_total'],
                'statut' => $report['statut'],
                'date_synchronisation' => $report['date_synchronisation']
            ],
            'statistics' => [
                'total_tickets' => (int)$stats['total_tickets'],
                'total_amount' => (float)$stats['total_amount'],
                'average_price' => (float)$stats['average_price'],
                'first_ticket' => $stats['first_ticket_time'],
                'last_ticket' => $stats['last_ticket_time'],
                'working_hours' => $stats['first_ticket_time'] && $stats['last_ticket_time'] 
                    ? round((strtotime($stats['last_ticket_time']) - strtotime($stats['first_ticket_time'])) / 3600, 2) 
                    : 0
            ],
            'tickets' => $tickets,
            'summary' => [
                'date' => $date,
                'user_code' => $user_code,
                'site_id' => $site_id,
                'generated_at' => date('Y-m-d H:i:s')
            ]
        ];
        
        jsonResponse(true, 'Rapport journalier récupéré', $response_data, 200);
        
    } else {
        $report_stmt->close();
        
        // Aucun rapport trouvé, retourner des statistiques vides
        $response_data = [
            'report' => null,
            'statistics' => [
                'total_tickets' => 0,
                'total_amount' => 0,
                'average_price' => 0,
                'first_ticket' => null,
                'last_ticket' => null,
                'working_hours' => 0
            ],
            'tickets' => [],
            'summary' => [
                'date' => $date,
                'user_code' => $user_code,
                'site_id' => $site_id,
                'generated_at' => date('Y-m-d H:i:s'),
                'message' => 'Aucun rapport trouvé pour cette date'
            ]
        ];
        
        jsonResponse(true, 'Aucun rapport trouvé pour cette date', $response_data, 200);
    }
    
} catch (Exception $e) {
    jsonResponse(false, 'Erreur de génération du rapport: ' . $e->getMessage(), [], 500);
}
?>