<?php
require_once __DIR__ . '/../models/TypeVehicule.php';
require_once __DIR__ . '/../models/Tarif.php';
require_once __DIR__ . '/../models/BonVers.php';

class VersementController {
    private $db;

    public function __construct($db) {
        $this->db = $db;
    }

    public function getTypeVehicules() {
        $typeVehicule = new TypeVehicule($this->db);
        $stmt = $typeVehicule->getAll();
        $types = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode([
            'success' => true,
            'data' => $types
        ]);
    }

    public function getOperateurs() {
        $type = $_GET['type'] ?? null;
        
        // On récupère les opérateurs qui ont des bus actifs
        $query = "SELECT DISTINCT o.id, o.name 
                  FROM operators o 
                  INNER JOIN buses b ON o.id = b.id_operateur 
                  WHERE b.actif = 1";
        
        $params = [];
        if ($type && $type !== 'all' && $type !== 'actif') {
            $query .= " AND b.type = ?";
            $params[] = $type;
        }
        
        $query .= " ORDER BY o.name ASC";
                  
        $stmt = $this->db->prepare($query);
        $stmt->execute($params);
        $operateurs = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        echo json_encode([
            'success' => true,
            'data' => $operateurs
        ]);
    }

    public function getBuses() {
        $id_operateur = $_GET['id_operateur'] ?? null;
        $type = $_GET['type'] ?? null;
        
        if (!$id_operateur || !$type) {
            echo json_encode(['success' => false, 'message' => 'Parameters missing']);
            return;
        }

        // On filtre aussi par actif = 1 pour être cohérent avec les opérateurs
        $query = "SELECT id, matricule, id_operateur FROM buses WHERE id_operateur = ? AND type = ? AND actif = 1";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(1, $id_operateur);
        $stmt->bindParam(2, $type);
        $stmt->execute();
        $buses = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        echo json_encode([
            'success' => true,
            'data' => $buses
        ]);
    }

    public function getTarif() {
        $type = $_GET['type'] ?? null;
        if (!$type) {
            echo json_encode(['success' => false, 'message' => 'Type is required']);
            return;
        }
        $tarif = new Tarif($this->db);
        $stmt = $tarif->getByType($type);
        $tarifData = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($tarifData) {
            // Convert numeric strings to actual numbers for Android
            $tarifData['Num'] = (int)$tarifData['Num'];
            $tarifData['prix_ht'] = (float)$tarifData['prix_ht'];
            $tarifData['tva'] = (float)$tarifData['tva'];
            $tarifData['mt_tva'] = (float)$tarifData['mt_tva'];
            $tarifData['prix_ttc'] = (float)$tarifData['prix_ttc'];
            $tarifData['timbre'] = (float)$tarifData['timbre'];
            $tarifData['ttc'] = (float)$tarifData['ttc'];
        }

        echo json_encode([
            'success' => true,
            'data' => $tarifData
        ]);
    }

    public function getNextNumVers() {
        // Security: Ensure we only get the numeric part and increment it safely
        $stmt = $this->db->query("SELECT COALESCE(MAX(Id), 0) FROM bons_vers");
        $maxId = $stmt->fetchColumn();
        $nextId = intval($maxId) + 1;
        
        $yearSuffix = date('y');
        $num_vers = "BVR" . str_pad($nextId, 6, '0', STR_PAD_LEFT) . "-" . $yearSuffix;
        
        echo json_encode([
            'success' => true,
            'next_num' => $num_vers
        ]);
    }

    public function checkPeriode() {
        $matricule = $_GET['matricule'] ?? null;
        $periode = $_GET['periode'] ?? null;
        
        if (!$matricule || !$periode) {
            echo json_encode(['success' => false, 'message' => 'Parameters missing']);
            return;
        }

        // Vérifier si un enregistrement existe déjà pour ce matricule et cette période
        $query = "SELECT COUNT(*) FROM bons_vers WHERE matricule = ? AND periode_p = ?";
        $stmt = $this->db->prepare($query);
        $stmt->execute([$matricule, $periode]);
        $exists = $stmt->fetchColumn() > 0;
        
        echo json_encode(['success' => true, 'exists' => $exists]);
    }

    public function createBonVers() {
        $input = file_get_contents("php://input");
        $data = json_decode($input);
        
        if (!$data || !isset($data->matricules) || !is_array($data->matricules)) {
            echo json_encode(['success' => false, 'message' => 'Invalid data or missing matricules']);
            return;
        }
        
        $results = [];
        $successCount = 0;
        $yearSuffix = date('y'); // 26 pour 2026

        // Security: Use a transaction for bulk insert
        $this->db->beginTransaction();

        try {
            foreach ($data->matricules as $matriculeInfo) {
                // Security: Use prepared query to get MAX(Id) safely
                $stmt = $this->db->query("SELECT MAX(Id) FROM bons_vers");
                $nextId = ($stmt->fetchColumn() ?: 0) + 1;
                $num_vers = "BVR" . str_pad($nextId, 6, '0', STR_PAD_LEFT) . "-" . $yearSuffix;

                $query = "INSERT INTO bons_vers 
                          (num_vers, date_vers, periode_p, operateur, type_vehicule, mt_ttc, obs, creer_par, date_creer, matricule) 
                          VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                
                $stmt = $this->db->prepare($query);
                $date_creer = date('Y-m-d H:i:s');
                
                $success = $stmt->execute([
                    $num_vers,
                    $data->date_vers ?? $date_creer,
                    $data->periode_p,
                    $data->operateur,
                    $data->type_vehicule,
                    $matriculeInfo->ttc,
                    $data->obs,
                    $data->creer_par,
                    $date_creer,
                    $matriculeInfo->matricule
                ]);

                if ($success) {
                    $successCount++;
                    $results[] = ["matricule" => $matriculeInfo->matricule, "num_vers" => $num_vers];
                }
            }
            
            $this->db->commit();
            
            echo json_encode([
                'success' => $successCount > 0,
                'count' => $successCount,
                'details' => $results
            ]);
        } catch (Exception $e) {
            $this->db->rollBack();
            echo json_encode([
                'success' => false,
                'message' => 'Database error during insertion: ' . $e->getMessage()
            ]);
        }
    }

    public function printBonVers() {
        $data = json_decode(file_get_contents("php://input"));
        echo json_encode(['success' => true]);
    }

    public function getRapportVersement() {
        $periode = $_GET['periode'] ?? null;
        $operateur = $_GET['operateur'] ?? null;

        if (!$periode) {
            echo json_encode([
                'success' => false,
                'message' => 'Paramètre periode requis'
            ]);
            return;
        }

        // Construction de la requête pour agréger les totaux par matricule
        // Utilisation explicite du nom de la table 'bons_vers'
        $query = "SELECT matricule, SUM(mt_ttc) as total_ttc 
                  FROM bons_vers 
                  WHERE periode_p = :periode";
        
        $params = [':periode' => $periode];

        // Si un opérateur spécifique est demandé (et n'est pas "TOUT" ou vide)
        if ($operateur && $operateur !== 'TOUS LES OPERATEURS' && $operateur !== 'TOUT' && $operateur !== '') {
            $query .= " AND operateur = :operateur";
            $params[':operateur'] = $operateur;
        }

        $query .= " GROUP BY matricule 
                    ORDER BY matricule ASC";

        try {
            $stmt = $this->db->prepare($query);
            $stmt->execute($params);
            $data = $stmt->fetchAll(PDO::FETCH_ASSOC);

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