<?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 Tickets (TicketID, DepartID, DateOuverture, ArretDepart, ArretArriver, LigneID, OperateurID, 
                    DateAchat, Prix, RedevancePassager, PrixTotal, BusID, PassConv, Site, UserID, Date_Imp, NbreImpression) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            $db->query($sql, [
                $data['TicketID'],
                $data['DepartID'],
                $data['DateOuverture'],
                $data['ArretDepart'],
                $data['ArretArriver'],
                $data['LigneID'],
                $data['OperateurID'],
                $data['DateAchat'],
                $data['Prix'],
                $data['RedevancePassager'],
                $data['PrixTotal'],
                $data['BusID'],
                $data['PassConv'],
                $data['Site'],
                $data['UserID'],
                $data['Date_Imp'],
                $data['NbreImpression']
            ]);
            echo json_encode(['success' => true, 'message' => 'Ticket créé']);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        break;
        
    case 'getByDepart':
        $departID = $_GET['departID'] ?? '';
        $siteName = $_GET['site'] ?? '';
        try {
            $sql = "SELECT * FROM Tickets WHERE DepartID = ? AND Site = ?";
            $result = $db->select($sql, [$departID, $siteName]);
            echo json_encode(['success' => true, 'data' => $result]);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        break;
        
    case 'getSumPrixTotal':
        $departID = $_GET['departID'] ?? '';
        $siteName = $_GET['site'] ?? '';
        try {
            $sql = "SELECT SUM(PrixTotal) as total FROM Tickets WHERE DepartID = ? AND Site = ?";
            $result = $db->select($sql, [$departID, $siteName]);
            echo json_encode(['success' => true, 'data' => $result[0]['total'] ?? 0]);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        break;
        
    case 'getTrajetPrix':
        $ligneID = $_GET['ligneID'] ?? '';
        $siteName = $_GET['site'] ?? '';
        $arretArrivee = $_GET['arretArrivee'] ?? '';
        try {
            $sql = "SELECT Prix, Redevance, PrixTotal FROM Trajets WHERE LigneID = ? AND Site = ? AND ArretArriveeID = ?";
            $result = $db->select($sql, [$ligneID, $siteName, $arretArrivee]);
            if (count($result) > 0) {
                echo json_encode(['success' => true, 'data' => $result[0]]);
            } else {
                echo json_encode(['success' => false, 'message' => 'Trajet non trouvé']);
            }
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        break;
        
    case 'getByLigne':
        $ligneID = $_GET['ligneID'] ?? '';
        $siteName = $_GET['site'] ?? '';
        try {
            $sql = "SELECT ArretArriveeID, Prix, Redevance, PrixTotal FROM Trajets WHERE LigneID = ? AND Site = ? ORDER BY Prix";
            $result = $db->select($sql, [$ligneID, $siteName]);
            $trajets = [];
            foreach ($result as $row) {
                $trajets[] = [
                    'ArretArriveeID' => $row['ArretArriveeID'],
                    'Prix' => (float)($row['Prix'] ?? 0),
                    'Redevance' => (float)($row['Redevance'] ?? 0),
                    'PrixTotal' => (float)($row['PrixTotal'] ?? 0)
                ];
            }
            echo json_encode(['success' => true, 'data' => $trajets]);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        break;
        
    case 'lastId':
        $siteID = $_GET['siteID'] ?? '';
        try {
            $sql = "SELECT TicketID FROM Tickets WHERE TicketID LIKE ? ORDER BY TicketID DESC LIMIT 1";
            $result = $db->select($sql, [$siteID . '-TK-%']);
            if (count($result) > 0) {
                echo json_encode(['success' => true, 'data' => $result[0]['TicketID']]);
            } else {
                echo json_encode(['success' => true, 'data' => null]);
            }
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        break;
        
    case 'updateFeuilleID':
        $feuilleID = $_GET['feuilleID'] ?? '';
        $departID = $_GET['departID'] ?? '';
        $siteName = $_GET['site'] ?? '';
        try {
            $sql = "UPDATE Tickets SET FeuilleID = ? WHERE DepartID = ? AND Site = ?";
            $db->query($sql, [$feuilleID, $departID, $siteName]);
            echo json_encode(['success' => true, 'message' => 'Tickets mis à jour']);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        break;
        
    default:
        echo json_encode(['success' => false, 'message' => 'Action non reconnue']);
}
