<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../../../config/database.php';

// Vérifier l'authentification (désactivé en local pour le proxy et les tests)
$host = $_SERVER['HTTP_HOST'] ?? '';
$isLocal = in_array($host, ['localhost', '127.0.0.1']);

// Toujours désactiver l'authentification en local pour éviter les problèmes de session
if ($isLocal || php_sapi_name() === 'cli') {
    // En local ou en CLI, aucune authentification requise
} else {
    session_start();
    if (!isset($_SESSION['user_code'])) {
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'message' => 'Non autorisé']);
        exit;
    }
}

$db = Database::getInstance();
$action = $_GET['action'] ?? '';

switch ($action) {
    case 'list':
        try {
            $siteId = $_GET['siteId'] ?? 'PA01';
            $date = $_GET['date'] ?? '';
            $startDate = $_GET['startDate'] ?? '';
            $endDate = $_GET['endDate'] ?? '';
            $agent = $_GET['agent'] ?? '';
            
            $sql = "SELECT t.*, u.NomPrenom 
                    FROM Tickets_Parking t
                    LEFT JOIN Utilisateurs u ON t.code_utilisateur = u.code_utilisateur
                    WHERE t.SiteID = ?";
            $params = [$siteId];
            
            if (!empty($startDate) && !empty($endDate)) {
                $sql .= " AND DATE(t.date_heure) BETWEEN ? AND ?";
                $params[] = $startDate;
                $params[] = $endDate;
            } else if (!empty($date)) {
                $sql .= " AND DATE(t.date_heure) = ?";
                $params[] = $date;
            }
            
            if (!empty($agent)) {
                $sql .= " AND t.code_utilisateur = ?";
                $params[] = $agent;
            }
            
            $sql .= " ORDER BY t.date_heure DESC";
            
            $result = $db->select($sql, $params);
            echo json_encode(['success' => true, 'data' => $result]);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        break;
        
        case 'stats':
        try {
            $siteId = $_GET['siteId'] ?? 'PA01';
            $date = $_GET['date'] ?? '';
            $startDate = $_GET['startDate'] ?? '';
            $endDate = $_GET['endDate'] ?? '';
            $agent = $_GET['agent'] ?? '';
            
            $sql = "SELECT 
                        COUNT(*) as total_tickets,
                        SUM(prix) as total_amount,
                        COUNT(CASE WHEN designation = 'Tickets manuels' THEN 1 END) as manual_tickets,
                        COUNT(DISTINCT code_utilisateur) as agent_count
                    FROM Tickets_Parking 
                    WHERE SiteID = ?";
            $params = [$siteId];
            
            if (!empty($startDate) && !empty($endDate)) {
                $sql .= " AND DATE(date_heure) BETWEEN ? AND ?";
                $params[] = $startDate;
                $params[] = $endDate;
            } else if (!empty($date)) {
                $sql .= " AND DATE(date_heure) = ?";
                $params[] = $date;
            }
            
            if (!empty($agent)) {
                $sql .= " AND code_utilisateur = ?";
                $params[] = $agent;
            }
            
            $result = $db->select($sql, $params);
            $stats = $result[0] ?? [
                'total_tickets' => 0,
                'total_amount' => 0,
                'manual_tickets' => 0,
                'agent_count' => 0
            ];
            
            echo json_encode(['success' => true, 'data' => $stats]);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        break;
        
    case 'agents':
        try {
            $siteId = $_GET['siteId'] ?? 'PA01';
            
            $sql = "SELECT DISTINCT t.code_utilisateur as agent, u.NomPrenom 
                    FROM Tickets_Parking t
                    LEFT JOIN Utilisateurs u ON t.code_utilisateur = u.code_utilisateur
                    WHERE t.SiteID = ? 
                    ORDER BY u.NomPrenom, t.code_utilisateur";
            $result = $db->select($sql, [$siteId]);
            
            echo json_encode(['success' => true, 'data' => $result]);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        break;
        
    case 'etat_ventes':
        try {
            $siteId = $_GET['siteId'] ?? 'PA01';
            $startDate = $_GET['startDate'] ?? '';
            $endDate = $_GET['endDate'] ?? '';
            
            $sql = "SELECT DATE(date_heure) as date_vente, prix as pu_ttc, COUNT(*) as nbre_tickets
                    FROM Tickets_Parking 
                    WHERE SiteID = ?";
            $params = [$siteId];
            
            if (!empty($startDate) && !empty($endDate)) {
                $sql .= " AND DATE(date_heure) BETWEEN ? AND ?";
                $params[] = $startDate;
                $params[] = $endDate;
            }
            
            $sql .= " GROUP BY DATE(date_heure), prix ORDER BY DATE(date_vente) ASC, prix ASC";
            
            $result = $db->select($sql, $params);
            
            // Calculer les colonnes supplémentaires
            $finalData = [];
            foreach ($result as $row) {
                $nbre = (int)$row['nbre_tickets'];
                $pu_ttc = (float)$row['pu_ttc'];
                
                // Calcul basé sur l'exemple de l'utilisateur :
                // Mt HT = (PU TTC / 1.19) * Nbre
                $mt_ht = round(($pu_ttc / 1.19) * $nbre, 2);
                $tva = round($mt_ht * 0.19, 2);
                $ttc = $mt_ht + $tva; // Doit être égal à pu_ttc * nbre
                $pu_ht = round($pu_ttc / 1.19, 2);
                
                $finalData[] = [
                    'date' => $row['date_vente'],
                    'nbre' => $nbre,
                    'pu_ttc' => $pu_ttc,
                    'pu_ht' => $pu_ht,
                    'mt_ht' => $mt_ht,
                    'tva' => $tva,
                    'ttc' => $ttc
                ];
            }
            
            echo json_encode(['success' => true, 'data' => $finalData]);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        break;
        
    case 'chart_data':
        try {
            // Cette action n'est plus utilisée
            echo json_encode(['success' => false, 'message' => 'Action non disponible']);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        break;
        
    default:
        echo json_encode(['success' => false, 'message' => 'Action non reconnue']);
}