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

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

switch ($action) {
    case 'create':
        $data = json_decode(file_get_contents('php://input'), true);
        try {
            $sql = "INSERT INTO Feuilles (FeuilleID, DateFeuille, FeuilleManuelle, IdDepart, Site, UserID, Date_Modif) 
                    VALUES (?, ?, ?, ?, ?, ?, ?)";
            $db->query($sql, [
                $data['FeuilleID'],
                $data['DateFeuille'],
                $data['FeuilleManuelle'],
                $data['IdDepart'],
                $data['Site'],
                $data['UserID'],
                $data['Date_Modif']
            ]);
            echo json_encode(['success' => true, 'message' => 'Feuille créée']);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        break;
        
    case 'getTotals':
        $departID = $_GET['departID'] ?? '';
        $siteName = $_GET['site'] ?? '';
        try {
            $sql = "SELECT COUNT(*) as nbre, SUM(RedevancePassager) as redevance, SUM(PrixTotal) as total, SUM(Prix) as tickets_prix 
                    FROM Tickets WHERE DepartID = ? AND Site = ?";
            $result = $db->select($sql, [$departID, $siteName]);
            echo json_encode(['success' => true, 'data' => $result[0]]);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        break;
        
    default:
        echo json_encode(['success' => false, 'message' => 'Action non reconnue']);
}
