<?php
// Rapports et statistiques pour le projet VB.NET
// POST /apiggr/reports  Body: {"action": "...", "params": {...}}

header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/../../config/database.php';

$body = json_decode(file_get_contents('php://input'), true) ?? [];
$action = $body['action'] ?? '';

try {
    $db = Database::getInstance()->getConnection();

    switch ($action) {

        case 'statistiques_tickets':
            $where = "WHERE 1=1";
            $params = [];
            if (!empty($body['site'])) {
                $where .= " AND Site = :site";
                $params[':site'] = $body['site'];
            }
            if (!empty($body['user'])) {
                $where .= " AND UserID = :user";
                $params[':user'] = $body['user'];
            }
            if (!empty($body['dateDeb']) && !empty($body['dateFin'])) {
                $where .= " AND DateAchat BETWEEN :dateDeb AND :dateFin";
                $params[':dateDeb'] = $body['dateDeb'];
                $params[':dateFin'] = $body['dateFin'];
            }
            $sql = "SELECT TicketID, Prix, RedevancePassager, PrixTotal, MtRembVoyageur, DateAchat, UserID, Site FROM Tickets {$where}";
            $stmt = $db->prepare($sql);
            $stmt->execute($params);
            echo json_encode(['success' => true, 'data' => $stmt->fetchAll()]);
            break;

        case 'etat_vente_operateur':
            $sql = "SELECT Operateur, SUM(MtTickets) AS mtTickets, SUM(Redevance) AS redevance, 
                    SUM(Commission) AS commission, SUM(DST) AS dst, SUM(NbrePlaces) AS nbrePlaces 
                    FROM Penalites WHERE Site = :site AND DatePenalite BETWEEN :dateDeb AND :dateFin 
                    GROUP BY Operateur";
            $stmt = $db->prepare($sql);
            $stmt->execute([
                ':site' => $body['site'] ?? '',
                ':dateDeb' => $body['dateDeb'] ?? '',
                ':dateFin' => $body['dateFin'] ?? ''
            ]);
            echo json_encode(['success' => true, 'data' => $stmt->fetchAll()]);
            break;

        case 'consignes_montant':
            $sql = "SELECT SUM(MontantTicket) AS MontantConsignes FROM ConsignesBagages 
                    WHERE Site = :site AND DateDepot BETWEEN :dateDeb AND :dateFin";
            $stmt = $db->prepare($sql);
            $stmt->execute([
                ':site' => $body['site'] ?? '',
                ':dateDeb' => $body['dateDeb'] ?? '',
                ':dateFin' => $body['dateFin'] ?? ''
            ]);
            echo json_encode(['success' => true, 'data' => $stmt->fetch()]);
            break;

        case 'parking_montant':
            $sql = "SELECT SUM(TP.prix) AS MontantParking FROM Tickets_Parking TP 
                    INNER JOIN Sites S ON TP.SiteID = S.SiteID 
                    WHERE TP.date_heurs BETWEEN :dateDeb AND :dateFin AND S.Nom_Site = :site";
            $stmt = $db->prepare($sql);
            $stmt->execute([
                ':dateDeb' => $body['dateDeb'] ?? '',
                ':dateFin' => $body['dateFin'] ?? '',
                ':site' => $body['site'] ?? ''
            ]);
            echo json_encode(['success' => true, 'data' => $stmt->fetch()]);
            break;

        case 'autres_recettes_montant':
            $sql = "SELECT SUM(Montant) AS MontantAutres FROM AutresRecettes 
                    WHERE Site = :site AND DateRecettes BETWEEN :dateDeb AND :dateFin";
            $stmt = $db->prepare($sql);
            $stmt->execute([
                ':site' => $body['site'] ?? '',
                ':dateDeb' => $body['dateDeb'] ?? '',
                ':dateFin' => $body['dateFin'] ?? ''
            ]);
            echo json_encode(['success' => true, 'data' => $stmt->fetch()]);
            break;

        case 'journal_details':
            $sql = "SELECT DISTINCT Num_Journal, Date_Du, Date_Au, Operateur, Bus, Nbre_Tickets, 
                    Total_Montant, Total_Redevance FROM Journalisation 
                    WHERE Site = :site AND Date_Du >= :dateDeb AND Date_Au <= :dateFin";
            $stmt = $db->prepare($sql);
            $stmt->execute([
                ':site' => $body['site'] ?? '',
                ':dateDeb' => $body['dateDeb'] ?? '',
                ':dateFin' => $body['dateFin'] ?? ''
            ]);
            echo json_encode(['success' => true, 'data' => $stmt->fetchAll()]);
            break;

        default:
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Action de rapport inconnue: ' . $action]);
    }

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Erreur SQL: ' . $e->getMessage()]);
}
