<?php
namespace Api\Controllers;

use Api\Core\Database;
use Api\Models\User;

class ApiController {
    
    public function handleRequest() {
        header('Content-Type: application/json');
        
        $uri = $_SERVER['REQUEST_URI'];
        // Remove query string
        if (($pos = strpos($uri, '?')) !== false) {
            $uri = substr($uri, 0, $pos);
        }
        
        $method = $_SERVER['REQUEST_METHOD'];
        
        if (strpos($uri, '/login') !== false) {
            $this->login();
        } elseif (strpos($uri, '/bus-list') !== false) {
            $this->getBusList();
        } elseif (strpos($uri, '/create-depart') !== false) {
            $this->createDepart();
        } elseif (strpos($uri, '/open-departs') !== false) {
            $this->getOpenDeparts();
        } elseif (strpos($uri, '/trajets') !== false) {
            $this->getTrajets();
        } elseif (strpos($uri, '/create-ticket') !== false) {
            $this->createTicket();
        } elseif (strpos($uri, '/ventes') !== false) {
            $this->getVentes();
        } elseif (strpos($uri, '/feuilles-route') !== false) {
            $this->getFeuillesRoute();
        } elseif (strpos($uri, '/consignes') !== false) {
            $this->getConsignes();
        } elseif (strpos($uri, '/close-depart') !== false) {
            $this->closeDepart();
        } else {
            http_response_code(404);
            echo json_encode(['error' => 'Endpoint non trouvé in standalone API', 'uri' => $uri]);
        }
    }
    
    private function login() {
        $input = json_decode(file_get_contents('php://input'), true);
        $username = $input['username'] ?? '';
        $password = $input['password'] ?? '';
        
        $userModel = new User();
        $user = $userModel->authenticate($username, $password);
        
        if ($user) {
            echo json_encode([
                'success' => true,
                'user' => [
                    'id' => $user['code_utilisateur'],
                    'nom' => $user['NomPrenom'] ?? ($user['Nom'] . ' ' . $user['Prenom']),
                    'role' => $user['role'],
                    'site' => $user['SiteID']
                ]
            ]);
        } else {
            http_response_code(401);
            echo json_encode(['success' => false, 'message' => 'Identifiants incorrects']);
        }
    }

    private function getVentes() {
        $db = Database::getInstance();
        $stmt = $db->query("SELECT * FROM Tickets ORDER BY DateAchat DESC LIMIT 50");
        echo json_encode(['success' => true, 'data' => $stmt->fetchAll()]);
    }

    private function getFeuillesRoute() {
        $db = Database::getInstance();
        $stmt = $db->query("SELECT * FROM Feuilles ORDER BY DateFeuille DESC LIMIT 50");
        echo json_encode(['success' => true, 'data' => $stmt->fetchAll()]);
    }

    private function getConsignes() {
        $db = Database::getInstance();
        $stmt = $db->query("SELECT * FROM ConsignesBagages ORDER BY DateDepot DESC LIMIT 50");
        echo json_encode(['success' => true, 'data' => $stmt->fetchAll()]);
    }

    // Liste des bus disponibles pour créer un départ
    private function getBusList() {
        $db = Database::getInstance();
        $siteID = $_GET['siteID'] ?? '';
        
        if (empty($siteID)) {
            // Si aucun siteID n'est fourni, retourner tous les bus actifs
            $stmt = $db->query("SELECT BusID, Modele_Bus, Id_Ligne, Capacite_Bus, Ligne_Bus, Operateur_Bus 
                               FROM BusGares 
                               WHERE Etat = 'Actif' 
                               ORDER BY Modele_Bus");
        } else {
            // Filtrer par siteID
            $stmt = $db->prepare("SELECT BusID, Modele_Bus, Id_Ligne, Capacite_Bus, Ligne_Bus, Operateur_Bus 
                                 FROM BusGares 
                                 WHERE Etat = 'Actif' AND Site = ?
                                 ORDER BY Modele_Bus");
            $stmt->execute([$siteID]);
        }
        
        echo json_encode(['success' => true, 'data' => $stmt->fetchAll()]);
    }

    // Créer un nouveau départ
    private function createDepart() {
        $input = json_decode(file_get_contents('php://input'), true);
        $db = Database::getInstance();
        
        $busID = $input['busID'] ?? '';
        $placeDeclare = intval($input['placeDeclare'] ?? 0);
        $siteID = $input['siteID'] ?? 'GR00';
        $userID = $input['userID'] ?? 'Mobile';
        
        // Récupérer les infos du bus
        $stmt = $db->prepare("SELECT * FROM BusGares WHERE BusID = ?");
        $stmt->execute([$busID]);
        $bus = $stmt->fetch();
        
        if (!$bus) {
            echo json_encode(['success' => false, 'message' => 'Bus introuvable']);
            return;
        }
        
        // Vérifier que placeDeclare <= Capacite_Bus
        if ($placeDeclare > $bus['Capacite_Bus'] || $placeDeclare <= 0) {
            echo json_encode(['success' => false, 'message' => 'Places déclarées invalides']);
            return;
        }
        
        // Vérifier qu'il n'existe pas déjà un départ ouvert pour ce bus
        $stmt = $db->prepare("SELECT COUNT(*) as count FROM Departs WHERE BusID = ? AND Etat_Depart = 'O'");
        $stmt->execute([$busID]);
        $existingDepart = $stmt->fetch()['count'];
        
        if ($existingDepart > 0) {
            echo json_encode(['success' => false, 'message' => 'Ce bus a déjà un départ ouvert']);
            return;
        }
        
        // Générer le DepartID
        $stmt = $db->prepare("SELECT COUNT(*) as count FROM Departs WHERE DepartID LIKE ?");
        $stmt->execute([$siteID . '-DP-%']);
        $count = $stmt->fetch()['count'];
        $newDepartID = $siteID . '-DP-' . str_pad($count + 1, 7, '0', STR_PAD_LEFT);
        
        // Insérer le départ
        $stmt = $db->prepare("INSERT INTO Departs 
            (DepartID, DateDepart, DepartManuel, LigneID, BusID, OperateurID, PlaceDeclare, PlaceVendu, PlacesRestantes, Etat_Depart, Site, UserID, Date_Modif) 
            VALUES (?, ?, 'Non', ?, ?, ?, ?, 0, ?, 'O', ?, ?, ?)");
        
        $success = $stmt->execute([
            $newDepartID,
            date('Y-m-d H:i:s'),
            $bus['Id_Ligne'],
            $busID,
            $bus['Operateur_Bus'],
            $placeDeclare,
            $placeDeclare,
            $input['site'] ?? '',
            $userID,
            date('Y-m-d H:i:s')
        ]);
        
        echo json_encode(['success' => $success, 'departID' => $newDepartID]);
    }

    // Liste des départs ouverts
    private function getOpenDeparts() {
        $db = Database::getInstance();
        $stmt = $db->query("SELECT d.*, b.Modele_Bus, b.Ligne_Bus, b.Capacite_Bus 
                           FROM Departs d
                           LEFT JOIN BusGares b ON d.BusID = b.BusID
                           WHERE d.Etat_Depart = 'O'
                           ORDER BY d.DateDepart DESC");
        echo json_encode(['success' => true, 'data' => $stmt->fetchAll()]);
    }

    // Récupérer les trajets (arrêts) pour une ligne
    private function getTrajets() {
        $ligneID = $_GET['ligneID'] ?? '';
        $db = Database::getInstance();
        
        $stmt = $db->prepare("SELECT t.*, a.Nom_Arret 
                             FROM Trajets t
                             LEFT JOIN Arrets a ON t.ArretArriveeID = a.ArretID
                             WHERE t.LigneID = ?
                             ORDER BY t.Prix");
        $stmt->execute([$ligneID]);
        echo json_encode(['success' => true, 'data' => $stmt->fetchAll()]);
    }

    // Créer un ticket
    private function createTicket() {
        $input = json_decode(file_get_contents('php://input'), true);
        $db = Database::getInstance();
        
        $departID = $input['departID'] ?? '';
        $arretArrivee = $input['arretArrivee'] ?? '';
        $qty = intval($input['qty'] ?? 1);
        $prix = floatval($input['prix'] ?? 0);
        $redevance = floatval($input['redevance'] ?? 0);
        $prixTotal = floatval($input['prixTotal'] ?? 0);
        $userID = $input['userID'] ?? 'Mobile';
        $siteID = $input['siteID'] ?? 'GR00';
        
        // Récupérer le départ
        $stmt = $db->prepare("SELECT * FROM Departs WHERE DepartID = ?");
        $stmt->execute([$departID]);
        $depart = $stmt->fetch();
        
        if (!$depart) {
            echo json_encode(['success' => false, 'message' => 'Départ introuvable']);
            return;
        }
        
        // Vérifier les places restantes
        if ($depart['PlacesRestantes'] < $qty) {
            echo json_encode(['success' => false, 'message' => 'Pas assez de places restantes']);
            return;
        }
        
        // Récupérer ArretDepartID depuis la table Trajets
        $stmt = $db->prepare("SELECT ArretDepartID FROM Trajets WHERE LigneID = ? AND ArretArriveeID = ? LIMIT 1");
        $stmt->execute([$depart['LigneID'], $arretArrivee]);
        $trajet = $stmt->fetch();
        $arretDepart = $trajet['ArretDepartID'] ?? '';
        
        // Générer les tickets
        $stmt = $db->prepare("SELECT COUNT(*) as count FROM Tickets WHERE TicketID LIKE ?");
        $stmt->execute([$siteID . '-TK-%']);
        $count = $stmt->fetch()['count'];
        
        $success = true;
        for ($i = 0; $i < $qty; $i++) {
            $newTicketID = $siteID . '-TK-' . str_pad($count + $i + 1, 7, '0', STR_PAD_LEFT);
            
            $stmt = $db->prepare("INSERT INTO Tickets 
                (TicketID, DepartID, DateOuverture, ArretDepart, ArretArriver, LigneID, OperateurID, DateAchat, Prix, RedevancePassager, PrixTotal, BusID, PassConv, Site, UserID, Date_Imp, NbreImpression) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, 1)");
            
            $success = $success && $stmt->execute([
                $newTicketID,
                $departID,
                $depart['DateDepart'],
                $arretDepart,
                $arretArrivee,
                $depart['LigneID'],
                $depart['OperateurID'],
                date('Y-m-d H:i:s'),
                $prix,
                $redevance,
                $prixTotal,
                $depart['BusID'],
                $siteID,
                $userID,
                date('Y-m-d H:i:s')
            ]);
        }
        
        // Mettre à jour les places du départ
        if ($success) {
            $newPlaceVendu = $depart['PlaceVendu'] + $qty;
            $newPlacesRestantes = $depart['PlacesRestantes'] - $qty;
            
            $stmt = $db->prepare("UPDATE Departs SET PlaceVendu = ?, PlacesRestantes = ?, Date_Modif = ? WHERE DepartID = ?");
            $stmt->execute([$newPlaceVendu, $newPlacesRestantes, date('Y-m-d H:i:s'), $departID]);
        }
        
        echo json_encode(['success' => $success]);
    }

    // Fermer un départ et imprimer la feuille de route
    private function closeDepart() {
        $input = json_decode(file_get_contents('php://input'), true);
        $db = Database::getInstance();
        
        $departID = $input['departID'] ?? '';
        $siteID = $input['siteID'] ?? '';
        $userID = $input['userID'] ?? '';
        
        if (empty($departID) || empty($siteID)) {
            echo json_encode(['success' => false, 'message' => 'Données manquantes']);
            return;
        }

        // 1. Générer le nouveau FeuilleID
        // Chercher la dernière feuille manuelle NULL pour ce site
        $stmt = $db->prepare("SELECT MAX(FeuilleID) as maxID FROM Feuilles WHERE Site = ? AND FeuilleManuelle IS NULL");
        $stmt->execute([$siteID]);
        $lastFeuille = $stmt->fetch()['maxID'];
        
        if ($lastFeuille) {
            // Extraire le numéro (ex: GR05-FR-000007 -> 7)
            $parts = explode('-', $lastFeuille);
            $num = intval(end($parts));
            $newNum = $num + 1;
        } else {
            $newNum = 1;
        }
        
        $newFeuilleID = $siteID . '-FR-' . str_pad($newNum, 7, '0', STR_PAD_LEFT);
        
        // 2. Insérer dans la table Feuilles
        $stmt = $db->prepare("INSERT INTO Feuilles 
            (FeuilleID, DateFeuille, IdDepart, Site, UserID, Date_Modif) 
            VALUES (?, ?, ?, ?, ?, ?)");
            
        $dateNow = date('Y-m-d H:i:s');
        $success = $stmt->execute([
            $newFeuilleID,
            $dateNow,
            $departID,
            $siteID,
            $userID,
            $dateNow
        ]);
        
        if (!$success) {
            echo json_encode(['success' => false, 'message' => 'Erreur création feuille']);
            return;
        }
        
        // 3. Mettre à jour les Tickets
        $stmt = $db->prepare("UPDATE Tickets SET FeuilleID = ? WHERE DepartID = ?");
        $stmt->execute([$newFeuilleID, $departID]);
        
        // 4. Fermer le Départ
        $stmt = $db->prepare("UPDATE Departs SET Etat_Depart = 'F' WHERE DepartID = ?");
        $stmt->execute([$departID]);
        
        // 5. Impression Excel
        try {
            // Récupérer les infos pour l'impression
            // Nom Site
            $stmt = $db->prepare("SELECT Nom_Site FROM Sites WHERE SiteID = ?");
            $stmt->execute([$siteID]);
            $nomSite = $stmt->fetch()['Nom_Site'] ?? $siteID;
            
            // Infos Utilisateur
            $stmt = $db->prepare("SELECT NomPrenom FROM Utilisateurs WHERE code_utilisateur = ?");
            $stmt->execute([$userID]);
            $nomUser = $stmt->fetch()['NomPrenom'] ?? $userID;
            // URL de la feuille de route HTML
            // URL de base : https://api.transub.dz/apiggr
            $feuilleUrl = "https://api.transub.dz/apiggr/print_feuille.php?id=" . $newFeuilleID;
            
            echo json_encode([
                'success' => true, 
                'message' => 'Départ fermé avec succès', 
                'feuilleID' => $newFeuilleID,
                'pdf_url' => $feuilleUrl // On garde la clé pdf_url pour compatibilité Android, mais c'est une URL HTML
            ]);
            
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Erreur fermeture: ' . $e->getMessage()]);
        }
    }
}
