<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

require_once APPPATH . 'third_party/fpdf/fpdf.php';

class Pdf_fpdf extends FPDF {
    
    public function __construct() {
        parent::__construct();
    }
    
    /**
     * Générer un billet de voyage avec reçu - Format découpable
     * Moitié supérieure: Exemplaire CLIENT (Billet 2/3 + Reçu 1/3)
     * Moitié inférieure: Exemplaire AGENCE (Billet 2/3 + Reçu 1/3)
     */
    public function createTicket($billet, $reservation, $voyage) {
        $this->AddPage('P', 'A4');
        
        // Dimensions A4: 210 x 297 mm
        // Moitié page = 148.5 mm de hauteur
        // 2/3 largeur = 140 mm pour billet, 1/3 = 70 mm pour reçu
        
        $page_width = 210;
        $half_height = 145; // Hauteur de chaque moitié (avec marge)
        $billet_width = 135; // 2/3 de la largeur utile
        $recu_width = 65;    // 1/3 de la largeur utile
        $margin_left = 5;
        $margin_top = 5;
        
        // =====================================================
        // PARTIE SUPÉRIEURE - EXEMPLAIRE CLIENT
        // =====================================================
        $y_start_client = $margin_top;
        
        // Dessiner le billet (partie gauche - 2/3)
        $this->dessinerBillet($margin_left, $y_start_client, $billet_width, $half_height - 10, $billet, $reservation, $voyage, 'CLIENT');
        
        // Dessiner le reçu (partie droite - 1/3)
        $this->dessinerRecu($margin_left + $billet_width + 2, $y_start_client, $recu_width, $half_height - 10, $billet, $reservation, $voyage, 'CLIENT');
        
        // =====================================================
        // LIGNE DE DÉCOUPE
        // =====================================================
        $y_coupe = $margin_top + $half_height - 3;
        $this->SetDrawColor(150, 150, 150);
        $this->SetLineWidth(0.1);
        
        // Ligne pointillée
        $this->SetFont('Courier', '', 7);
        $this->SetTextColor(150, 150, 150);
        
        for ($x = $margin_left; $x < $page_width - $margin_left; $x += 8) {
            $this->Line($x, $y_coupe, $x + 4, $y_coupe);
        }
        
        // Texte de découpe avec ciseaux
        $this->SetXY($margin_left, $y_coupe - 3);
        $this->Cell($page_width - 2 * $margin_left, 6, '--- DECOUPER ICI / CUT HERE ---', 0, 1, 'C');
        
        $this->SetDrawColor(0, 0, 0);
        $this->SetTextColor(0, 0, 0);
        
        // =====================================================
        // PARTIE INFÉRIEURE - EXEMPLAIRE AGENCE
        // =====================================================
        $y_start_agence = $y_coupe + 5;
        
        // Dessiner le billet (partie gauche - 2/3)
        $this->dessinerBillet($margin_left, $y_start_agence, $billet_width, $half_height - 10, $billet, $reservation, $voyage, 'AGENCE');
        
        // Dessiner le reçu (partie droite - 1/3)
        $this->dessinerRecu($margin_left + $billet_width + 2, $y_start_agence, $recu_width, $half_height - 10, $billet, $reservation, $voyage, 'AGENCE');
    }
    
    /**
     * Dessiner la partie BILLET (2/3 gauche)
     */
    private function dessinerBillet($x, $y, $w, $h, $billet, $reservation, $voyage, $exemplaire) {
        // Cadre extérieur
        $this->SetDrawColor(0, 0, 0);
        $this->SetLineWidth(0.3);
        $this->Rect($x, $y, $w, $h);
        
        $padding = 3;
        $inner_x = $x + $padding;
        $inner_y = $y + $padding;
        $inner_w = $w - 2 * $padding;
        
        $this->SetXY($inner_x, $inner_y);
        
        // ===== EN-TÊTE =====
        $this->SetFont('Courier', 'B', 14);
        $this->Cell($inner_w, 6, 'YAMEELA', 0, 2, 'C');
        $this->SetFont('Courier', '', 7);
        $this->Cell($inner_w, 4, 'Transport Maritime Inter-Iles - Union des Comores', 0, 2, 'C');
        
        // Ligne
        $this->SetX($inner_x);
        $this->Cell($inner_w, 0, '', 'T', 2);
        $this->Ln(2);
        
        // ===== TITRE BILLET =====
        $this->SetX($inner_x);
        $this->SetFont('Courier', 'B', 11);
        $this->SetFillColor(41, 128, 185);
        $this->SetTextColor(255, 255, 255);
        $this->Cell($inner_w, 7, 'BILLET DE VOYAGE - ' . $exemplaire, 1, 2, 'C', true);
        $this->SetTextColor(0, 0, 0);
        $this->Ln(2);
        
        // ===== N° BILLET =====
        $this->SetX($inner_x);
        $this->SetFont('Courier', 'B', 9);
        $this->Cell(35, 5, 'No Billet:', 0, 0);
        $this->SetTextColor(180, 0, 0);
        $this->SetFont('Courier', 'B', 10);
        $this->Cell($inner_w - 35, 5, $billet->numero_billet, 0, 2);
        $this->SetTextColor(0, 0, 0);
        $this->Ln(1);
        
        // ===== INFORMATIONS VOYAGE =====
        $this->SetX($inner_x);
        $this->SetFont('Courier', 'B', 8);
        $this->SetFillColor(240, 240, 240);
        $this->Cell($inner_w, 5, 'VOYAGE', 0, 2, 'L', true);
        
        $this->SetFont('Courier', '', 8);
        $col1 = 32;
        $col2 = $inner_w - $col1;
        
        $this->SetX($inner_x);
        $this->Cell($col1, 4, 'N. Voyage:', 0, 0);
        $this->SetFont('Courier', 'B', 8);
        $this->Cell($col2, 4, $voyage->numero_voyage, 0, 2);
        
        $this->SetX($inner_x);
        $this->SetFont('Courier', '', 8);
        $this->Cell($col1, 4, 'Ferry:', 0, 0);
        $this->SetFont('Courier', 'B', 8);
        $this->Cell($col2, 4, $voyage->ferry_nom, 0, 2);
        
        $this->SetX($inner_x);
        $this->SetFont('Courier', '', 8);
        $this->Cell($col1, 4, 'Date:', 0, 0);
        $this->SetFont('Courier', 'B', 8);
        $this->Cell($col2, 4, date('d/m/Y', strtotime($voyage->date_voyage)), 0, 2);
        
        $this->SetX($inner_x);
        $this->SetFont('Courier', '', 8);
        $this->Cell($col1, 4, 'Heure:', 0, 0);
        $this->Cell($col2, 4, substr($voyage->heure_depart, 0, 5), 0, 2);
        
        $this->SetX($inner_x);
        $this->SetFont('Courier', '', 8);
        $this->Cell($col1, 4, 'Trajet:', 0, 0);
        $this->SetFont('Courier', 'B', 8);
        $this->Cell($col2, 4, $voyage->port_depart . ' -> ' . $voyage->port_arrivee, 0, 2);
        
        $this->Ln(1);
        
        // ===== PASSAGER =====
        $this->SetX($inner_x);
        $this->SetFont('Courier', 'B', 8);
        $this->Cell($inner_w, 5, 'PASSAGER', 0, 2, 'L', true);
        
        $this->SetX($inner_x);
        $this->SetFont('Courier', '', 8);
        $this->Cell($col1, 4, 'Nom:', 0, 0);
        $this->SetFont('Courier', 'B', 8);
        $this->Cell($col2, 4, strtoupper($reservation->nom) . ' ' . strtoupper($reservation->prenom), 0, 2);
        
        // ===== VÉHICULE SI PRÉSENT =====
        if (isset($reservation->vehicules) && !empty($reservation->vehicules)) {
            $vehicule = $reservation->vehicules[0];
            $this->Ln(1);
            $this->SetX($inner_x);
            $this->SetFont('Courier', 'B', 8);
            $this->Cell($inner_w, 5, 'VEHICULE', 0, 2, 'L', true);
            
            $this->SetX($inner_x);
            $this->SetFont('Courier', '', 8);
            $this->Cell($col1, 4, 'Type:', 0, 0);
            $this->SetFont('Courier', 'B', 8);
            $this->Cell($col2, 4, strtoupper(str_replace('_', ' ', $vehicule->type_vehicule)), 0, 2);
            
            if (!empty($vehicule->immatriculation)) {
                $this->SetX($inner_x);
                $this->SetFont('Courier', '', 8);
                $this->Cell($col1, 4, 'Immat:', 0, 0);
                $this->SetFont('Courier', 'B', 8);
                $this->Cell($col2, 4, $vehicule->immatriculation, 0, 2);
            }
        }
        
        $this->Ln(2);
        
        // ===== CODE-BARRES =====
        $barcode_x = $inner_x + ($inner_w - 70) / 2;
        $barcode_y = $this->GetY();
        $this->Code39($barcode_x, $barcode_y, $reservation->code_reservation, 0.5, 12);
        
        $this->SetY($barcode_y + 14);
        $this->SetX($inner_x);
        $this->SetFont('Courier', 'B', 9);
        $this->Cell($inner_w, 4, $reservation->code_reservation, 0, 2, 'C');
        
        $this->Ln(2);
        
        // ===== INFORMATIONS IMPORTANTES =====
        $this->SetX($inner_x);
        $this->SetFont('Courier', 'B', 7);
        $this->SetFillColor(240, 240, 240);
        $this->Cell($inner_w, 4, 'INFORMATIONS IMPORTANTES', 0, 2, 'L', true);
        
        $this->SetX($inner_x);
        $this->SetFont('Courier', '', 6);
        $this->MultiCell($inner_w, 3, 
            "- Presentez-vous a l'embarquement 1 heure avant le depart\n" .
            "- Munissez-vous de votre piece d'identite originale\n" .
            "- Ce billet est nominatif et non remboursable\n" .
            "- Conservez ce billet jusqu'a la fin du voyage", 0, 'L');
        
        // ===== PIED =====
        $this->Ln(1);
        $this->SetFont('Courier', '', 5);
        $this->SetX($inner_x);
        $this->Cell($inner_w, 3, 'Emission: ' . date('d/m/Y H:i', strtotime($billet->date_emission)), 0, 2, 'L');
        
        if (!empty($billet->caissier_nom)) {
            $this->SetX($inner_x);
            $this->Cell($inner_w, 3, 'Agent: ' . $billet->caissier_nom, 0, 2, 'L');
        }
    }
    
    /**
     * Dessiner la partie REÇU (1/3 droite)
     */
    private function dessinerRecu($x, $y, $w, $h, $billet, $reservation, $voyage, $exemplaire) {
        // Cadre extérieur avec bordure double
        $this->SetDrawColor(0, 0, 0);
        $this->SetLineWidth(0.3);
        $this->Rect($x, $y, $w, $h);
        $this->SetLineWidth(0.1);
        $this->Rect($x + 1, $y + 1, $w - 2, $h - 2);
        
        $padding = 3;
        $inner_x = $x + $padding;
        $inner_y = $y + $padding;
        $inner_w = $w - 2 * $padding;
        
        $this->SetXY($inner_x, $inner_y);
        
        // ===== EN-TÊTE =====
        $this->SetFont('Courier', 'B', 10);
        $this->Cell($inner_w, 5, 'YAMEELA', 0, 2, 'C');
        $this->SetFont('Courier', '', 6);
        $this->Cell($inner_w, 3, 'Union des Comores', 0, 2, 'C');
        
        $this->Ln(1);
        
        // ===== TITRE REÇU =====
        $this->SetX($inner_x);
        $this->SetFont('Courier', 'B', 9);
        $this->SetFillColor(46, 204, 113);
        $this->SetTextColor(255, 255, 255);
        $this->Cell($inner_w, 6, 'RECU DE PAIEMENT', 1, 2, 'C', true);
        $this->SetTextColor(0, 0, 0);
        
        $this->Ln(1);
        
        // ===== MENTION EXEMPLAIRE =====
        $this->SetX($inner_x);
        $this->SetFont('Courier', 'B', 7);
        if ($exemplaire == 'CLIENT') {
            $this->SetFillColor(52, 152, 219);
        } else {
            $this->SetFillColor(155, 89, 182);
        }
        $this->SetTextColor(255, 255, 255);
        $this->Cell($inner_w, 5, 'EXEMPLAIRE ' . $exemplaire, 1, 2, 'C', true);
        $this->SetTextColor(0, 0, 0);
        
        $this->Ln(2);
        
        // ===== DÉTAILS =====
        $this->SetFont('Courier', '', 7);
        $col1 = 20;
        $col2 = $inner_w - $col1;
        
        $this->SetX($inner_x);
        $this->Cell($col1, 4, 'No:', 0, 0);
        $this->SetFont('Courier', 'B', 7);
        $this->Cell($col2, 4, $billet->numero_billet, 0, 2);
        
        $this->SetX($inner_x);
        $this->SetFont('Courier', '', 7);
        $this->Cell($col1, 4, 'Date:', 0, 0);
        $this->Cell($col2, 4, date('d/m/Y', strtotime($billet->date_paiement ?: $billet->date_emission)), 0, 2);
        
        $this->SetX($inner_x);
        $this->Cell($col1, 4, 'Heure:', 0, 0);
        $this->Cell($col2, 4, date('H:i', strtotime($billet->date_paiement ?: $billet->date_emission)), 0, 2);
        
        $this->Ln(1);
        $this->SetX($inner_x);
        $this->Cell($inner_w, 0, '', 'T', 2);
        $this->Ln(1);
        
        // ===== CLIENT =====
        $this->SetX($inner_x);
        $this->SetFont('Courier', 'B', 7);
        $this->Cell($inner_w, 4, 'CLIENT', 0, 2);
        
        $this->SetX($inner_x);
        $this->SetFont('Courier', '', 7);
        $nom_complet = strtoupper($reservation->nom) . ' ' . ucfirst($reservation->prenom);
        if (strlen($nom_complet) > 20) {
            $nom_complet = substr($nom_complet, 0, 18) . '..';
        }
        $this->Cell($inner_w, 4, $nom_complet, 0, 2);
        
        $this->Ln(1);
        $this->SetX($inner_x);
        $this->Cell($inner_w, 0, '', 'T', 2);
        $this->Ln(1);
        
        // ===== VOYAGE =====
        $this->SetX($inner_x);
        $this->SetFont('Courier', 'B', 7);
        $this->Cell($inner_w, 4, 'VOYAGE', 0, 2);
        
        $this->SetX($inner_x);
        $this->SetFont('Courier', '', 6);
        $this->Cell($inner_w, 3, $voyage->numero_voyage, 0, 2);
        
        $this->SetX($inner_x);
        $this->Cell($inner_w, 3, date('d/m/Y', strtotime($voyage->date_voyage)) . ' ' . substr($voyage->heure_depart, 0, 5), 0, 2);
        
        $this->SetX($inner_x);
        $this->SetFont('Courier', 'B', 6);
        $this->Cell($inner_w, 3, $voyage->port_depart . '->' . $voyage->port_arrivee, 0, 2);
        
        $this->Ln(2);
        $this->SetX($inner_x);
        $this->Cell($inner_w, 0, '', 'T', 2);
        $this->Ln(2);
        
        // ===== MONTANT =====
        $this->SetX($inner_x);
        $this->SetFont('Courier', 'B', 8);
        $this->SetFillColor(241, 196, 15);
        $this->Cell($inner_w, 5, 'MONTANT PAYE', 1, 2, 'C', true);
        
        $this->SetX($inner_x);
        $this->SetFont('Courier', 'B', 12);
        $this->SetTextColor(180, 0, 0);
        $this->Cell($inner_w, 8, number_format($billet->tarif_total, 0, ',', ' ') . ' FC', 1, 2, 'C');
        $this->SetTextColor(0, 0, 0);
        
        $this->Ln(2);
        
        // ===== STATUT =====
        $this->SetX($inner_x);
        $this->SetFont('Courier', 'B', 8);
        $this->SetFillColor(46, 204, 113);
        $this->SetTextColor(255, 255, 255);
        $this->Cell($inner_w, 5, 'PAYE', 1, 2, 'C', true);
        $this->SetTextColor(0, 0, 0);
        
        $this->Ln(2);
        
        // ===== CODE RÉSERVATION =====
        $this->SetX($inner_x);
        $this->SetFont('Courier', 'B', 8);
        $this->Cell($inner_w, 5, $reservation->code_reservation, 1, 2, 'C');
        
        $this->Ln(2);
        
        // ===== CAISSIER =====
        if (!empty($billet->caissier_nom)) {
            $this->SetX($inner_x);
            $this->SetFont('Courier', '', 5);
            $caissier = $billet->caissier_nom;
            if (strlen($caissier) > 18) {
                $caissier = substr($caissier, 0, 16) . '..';
            }
            $this->Cell($inner_w, 3, 'Caissier: ' . $caissier, 0, 2, 'L');
        }
        
        // ===== SIGNATURE (pour agence) =====
        if ($exemplaire == 'AGENCE') {
            $this->Ln(2);
            $this->SetX($inner_x);
            $this->SetFont('Courier', '', 6);
            $this->Cell($inner_w, 3, 'Signature client:', 0, 2, 'L');
            $this->SetX($inner_x);
            $this->Cell($inner_w, 8, '', 'B', 2);
        }
    }
    
    /**
     * Générer un code-barres Code 39
     */
    private function Code39($x, $y, $code, $w = 1, $h = 15) {
        $encode = array(
            '0' => 'bwbWBwBwb', '1' => 'BwbWbwbwB', '2' => 'bwBWbwbwB',
            '3' => 'BwBWbwbwb', '4' => 'bwbWBwbwB', '5' => 'BwbWBwbwb',
            '6' => 'bwBWBwbwb', '7' => 'bwbWbwBwB', '8' => 'BwbWbwBwb',
            '9' => 'bwBWbwBwb', 'A' => 'BwbwbWbwB', 'B' => 'bwBwbWbwB',
            'C' => 'BwBwbWbwb', 'D' => 'bwbwBWbwB', 'E' => 'BwbwBWbwb',
            'F' => 'bwBwBWbwb', 'G' => 'bwbwbWBwB', 'H' => 'BwbwbWBwb',
            'I' => 'bwBwbWBwb', 'J' => 'bwbwBWBwb', 'K' => 'BwbwbwbWB',
            'L' => 'bwBwbwbWB', 'M' => 'BwBwbwbWb', 'N' => 'bwbwBwbWB',
            'O' => 'BwbwBwbWb', 'P' => 'bwBwBwbWb', 'Q' => 'bwbwbwBWB',
            'R' => 'BwbwbwBWb', 'S' => 'bwBwbwBWb', 'T' => 'bwbwBwBWb',
            'U' => 'BWbwbwbwB', 'V' => 'bWBwbwbwB', 'W' => 'BWBwbwbwb',
            'X' => 'bWbwBwbwB', 'Y' => 'BWbwBwbwb', 'Z' => 'bWBwBwbwb',
            '-' => 'bWbwbwBwB', '.' => 'BWbwbwBwb', ' ' => 'bWBwbwBwb',
            '*' => 'bWbwBwBwb', '$' => 'bWbWbWbwb', '/' => 'bWbWbwbWb',
            '+' => 'bWbwbWbWb', '%' => 'bwbWbWbWb'
        );
        
        $this->SetFillColor(0, 0, 0);
        
        $code = strtoupper($code);
        $data = '*' . $code . '*';
        
        $narrow = $w;
        $wide = $w * 2.5;
        $xpos = $x;
        
        for ($i = 0; $i < strlen($data); $i++) {
            $char = $data[$i];
            
            if (!isset($encode[$char])) {
                continue;
            }
            
            $pattern = $encode[$char];
            
            for ($j = 0; $j < strlen($pattern); $j++) {
                $c = $pattern[$j];
                
                if ($c == 'b') {
                    $this->Rect($xpos, $y, $narrow, $h, 'F');
                    $xpos += $narrow;
                } elseif ($c == 'B') {
                    $this->Rect($xpos, $y, $wide, $h, 'F');
                    $xpos += $wide;
                } elseif ($c == 'w') {
                    $xpos += $narrow;
                } elseif ($c == 'W') {
                    $xpos += $wide;
                }
            }
            
            $xpos += $narrow;
        }
    }
    
    /**
     * Méthode pour créer un reçu de remboursement
     */
    public function createReceipt($data) {
        $this->AddPage();
        $this->SetFont('Courier', 'B', 16);
        
        $this->Cell(0, 10, 'YAMEELA', 0, 1, 'C');
        $this->SetFont('Courier', '', 12);
        $this->Cell(0, 10, 'Service de Transport Inter-Iles', 0, 1, 'C');
        $this->Ln(10);
        
        $this->SetFont('Courier', 'B', 14);
        $this->SetTextColor(200, 0, 0);
        $this->Cell(0, 10, 'RECU DE REMBOURSEMENT', 0, 1, 'C');
        $this->SetTextColor(0, 0, 0);
        $this->Ln(10);
        
        $this->SetFont('Courier', '', 12);
        $this->Cell(50, 8, 'No Billet:', 0, 0);
        $this->Cell(0, 8, $data['numero_billet'], 0, 1);
        
        $this->Cell(50, 8, 'Code Reservation:', 0, 0);
        $this->Cell(0, 8, $data['code_reservation'], 0, 1);
        
        $this->Cell(50, 8, 'Date/Heure:', 0, 0);
        $this->Cell(0, 8, date('d/m/Y H:i'), 0, 1);
        
        $this->Cell(50, 8, 'Passager:', 0, 0);
        $this->Cell(0, 8, $data['nom'] . ' ' . $data['prenom'], 0, 1);
        
        $this->Ln(10);
        
        $this->SetFont('Courier', 'B', 16);
        $this->SetTextColor(200, 0, 0);
        $this->Cell(0, 15, 'MONTANT REMBOURSE: ' . number_format($data['tarif_total']) . ' FC', 1, 1, 'C');
        $this->SetTextColor(0, 0, 0);
        
        $this->Ln(20);
        
        $this->SetFont('Courier', '', 10);
        $this->Cell(90, 30, 'Signature Client', 1, 0, 'C');
        $this->Cell(90, 30, 'Signature Caissier', 1, 1, 'C');
    }
    
    public function download($filename) {
        $this->Output('D', $filename);
    }
}