<?php
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
include_once __DIR__ . '/../auth_check.php';

try {
    $pdo = getDbConnection();
    $action = $_REQUEST['action'] ?? '';

    switch ($action) {
    case 'list':
        try {
            $stmt = $pdo->query("SELECT * FROM Tickets ORDER BY DateAchat DESC LIMIT 50");
            echo json_encode(['success' => true, 'data' => $stmt->fetchAll()]);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        break;
        
    case 'create':
        $data = json_decode(file_get_contents('php://input'), true);
        if (!$data) { $data = $_REQUEST; }
        try {
            $sql = "INSERT INTO Tickets (TicketID, DepartID, DateOuverture, ArretDepart, ArretArriver, LigneID, OperateurID, 
                    DateAchat, Prix, RedevancePassager, PrixTotal, BusID, PassConv, Site, UserID, Date_Imp, NbreImpression) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([
                $data['TicketID'] ?? '', $data['DepartID'] ?? '', $data['DateOuverture'] ?? '',
                $data['ArretDepart'] ?? '', $data['ArretArriver'] ?? '', $data['LigneID'] ?? '',
                $data['OperateurID'] ?? '', $data['DateAchat'] ?? '', $data['Prix'] ?? 0,
                $data['RedevancePassager'] ?? 0, $data['PrixTotal'] ?? 0, $data['BusID'] ?? '',
                $data['PassConv'] ?? '', $data['Site'] ?? '', $data['UserID'] ?? '',
                $data['Date_Imp'] ?? '', $data['NbreImpression'] ?? 0
            ]);
            echo json_encode(['success' => true, 'message' => 'Ticket créé']);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        break;
        
    case 'getByDepart':
        $departID = $_REQUEST['departID'] ?? '';
        $siteName = $_REQUEST['site'] ?? '';
        try {
            $stmt = $pdo->prepare("SELECT * FROM Tickets WHERE DepartID = ? AND Site = ?");
            $stmt->execute([$departID, $siteName]);
            echo json_encode(['success' => true, 'data' => $stmt->fetchAll()]);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        break;
        
    case 'getSumPrixTotal':
        $departID = $_REQUEST['departID'] ?? '';
        $siteName = $_REQUEST['site'] ?? '';
        try {
            $stmt = $pdo->prepare("SELECT SUM(PrixTotal) as total FROM Tickets WHERE DepartID = ? AND Site = ?");
            $stmt->execute([$departID, $siteName]);
            $result = $stmt->fetch();
            echo json_encode(['success' => true, 'data' => $result['total'] ?? 0]);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        break;
        
    case 'getTrajetPrix':
        $ligneID = $_REQUEST['ligneID'] ?? '';
        $siteName = $_REQUEST['site'] ?? '';
        $arretArrivee = $_REQUEST['arretArrivee'] ?? '';
        try {
            $stmt = $pdo->prepare("SELECT Prix, Redevance, PrixTotal FROM Trajets WHERE LigneID = ? AND Site = ? AND ArretArriveeID = ?");
            $stmt->execute([$ligneID, $siteName, $arretArrivee]);
            $result = $stmt->fetchAll();
            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 = $_REQUEST['ligneID'] ?? '';
        $siteName = $_REQUEST['site'] ?? '';
        try {
            $stmt = $pdo->prepare("SELECT ArretArriveeID, Prix, Redevance, PrixTotal FROM Trajets WHERE LigneID = ? AND Site = ? ORDER BY Prix");
            $stmt->execute([$ligneID, $siteName]);
            $result = $stmt->fetchAll();
            $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 = $_REQUEST['siteID'] ?? '';
        try {
            $stmt = $pdo->prepare("SELECT TicketID FROM Tickets WHERE TicketID LIKE ? ORDER BY TicketID DESC LIMIT 1");
            $stmt->execute([$siteID . '-TK-%']);
            $result = $stmt->fetch();
            if ($result) {
                echo json_encode(['success' => true, 'data' => $result['TicketID']]);
            } else {
                echo json_encode(['success' => true, 'data' => null]);
            }
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        break;
        
    case 'updateFeuilleID':
        $feuilleID = $_REQUEST['feuilleID'] ?? '';
        $departID = $_REQUEST['departID'] ?? '';
        $siteName = $_REQUEST['site'] ?? '';
        try {
            $stmt = $pdo->prepare("UPDATE Tickets SET FeuilleID = ? WHERE DepartID = ? AND Site = ?");
            $stmt->execute([$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:
            try {
                $stmt = $pdo->query("SELECT * FROM Tickets ORDER BY DateAchat DESC LIMIT 50");
                echo json_encode(['success' => true, 'data' => $stmt->fetchAll()]);
            } catch (Exception $e) {
                http_response_code(500);
                echo json_encode(['success' => false, 'message' => $e->getMessage()]);
            }
    }

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