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

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

class Batches extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library('auth_lib');
        $this->load->model('Batch_model');
        $this->load->helper(['url', 'form', 'download']);
        $this->auth_lib->require_login();
    }

    /**
     * Liste des batchs
     */
    public function index()
    {
        $this->auth_lib->require_permission('batch_view');

        $filters = [
            'status' => $this->input->get('status'),
            'year'   => $this->input->get('year') ?: date('Y'),
        ];

        $data = [
            'title'          => 'Batchs Hebdomadaires',
            'batches'        => $this->Batch_model->get_list($filters, 50),
            'unbatched_count'=> $this->Batch_model->count_unbatched(),
            'filters'        => $filters,
        ];

        $this->load->view('templates/header', $data);
        $this->load->view('batches/index', $data);
        $this->load->view('templates/footer');
    }

    /**
     * Créer un batch — sélection des dépenses
     */
    public function create()
    {
        $this->auth_lib->require_permission('batch_create');

        $unbatched = $this->Batch_model->get_unbatched_expenses();

        $data = [
            'title'     => 'Créer un Batch',
            'unbatched' => $unbatched,
            'next_id'   => $this->Batch_model->next_batch_id(),
        ];

        if ($this->input->method() === 'post') {
            $selected = $this->input->post('expense_ids');

            if (empty($selected)) {
                $this->session->set_flashdata('error', 'Veuillez sélectionner au moins une dépense.');
                redirect('batches/create');
            }

            $new_id = $this->Batch_model->create_batch($selected, $this->auth_lib->user_id());

            if ($new_id) {
                $batch = $this->Batch_model->get($new_id);
                $this->auth_lib->log_action(
                    $this->auth_lib->user_id(), 'batch_created', 'batches', $new_id,
                    $batch->batch_id . ' | ' . $batch->expense_count . ' dépenses | ' . number_format($batch->total_amount) . ' KMF'
                );
                $this->session->set_flashdata('success',
                    'Batch ' . $batch->batch_id . ' créé avec ' . $batch->expense_count . ' dépense(s).');
                redirect('batches/view/' . $new_id);
            } else {
                $this->session->set_flashdata('error', 'Erreur lors de la création du batch.');
                redirect('batches/create');
            }
        }

        $this->load->view('templates/header', $data);
        $this->load->view('batches/create', $data);
        $this->load->view('templates/footer');
    }

    /**
     * Voir un batch
     */
    public function view($id)
    {
        $this->auth_lib->require_permission('batch_view');

        $batch = $this->Batch_model->get($id);
        if ( ! $batch) show_404();

        $expenses = $this->Batch_model->get_batch_expenses($id);

        $by_location = [];
        foreach ($expenses as $e) {
            $loc = $e->location_name;
            if ( ! isset($by_location[$loc])) $by_location[$loc] = ['count' => 0, 'total' => 0];
            $by_location[$loc]['count']++;
            $by_location[$loc]['total'] += (float) $e->amount;
        }

        $data = [
            'title'       => 'Batch ' . $batch->batch_id,
            'batch'       => $batch,
            'expenses'    => $expenses,
            'by_location' => $by_location,
        ];

        $this->load->view('templates/header', $data);
        $this->load->view('batches/view', $data);
        $this->load->view('templates/footer');
    }

    /**
     * Finaliser un batch et générer le ZIP
     */
    public function finalize($id)
    {
        $this->auth_lib->require_permission('batch_finalize');

        $batch = $this->Batch_model->get($id);
        if ( ! $batch || $batch->status !== 'draft') {
            $this->session->set_flashdata('error', 'Batch introuvable ou déjà finalisé.');
            redirect('batches');
        }

        $expenses = $this->Batch_model->get_batch_expenses($id);
        $zip_path = $this->_generate_batch_zip($batch, $expenses);

        if ($zip_path) {
            $this->Batch_model->finalize($id, $zip_path);

            // Enregistrer dans le compte partenaire
            $this->load->model('Statement_model');
            foreach ($expenses as $e) {
                $this->Statement_model->record_expense(
                    $e->id, $e->expense_id, $e->supplier . ' - ' . $e->description,
                    $e->amount, $this->auth_lib->user_id()
                );
            }

            $this->auth_lib->log_action(
                $this->auth_lib->user_id(), 'batch_finalized', 'batches', $id,
                $batch->batch_id . ' | ' . count($expenses) . ' dépenses imputées au compte partenaire'
            );

            $this->session->set_flashdata('success',
                'Batch ' . $batch->batch_id . ' finalisé. ZIP généré et dépenses imputées au compte partenaire.');
        } else {
            $this->session->set_flashdata('error', 'Erreur lors de la génération du ZIP.');
        }

        redirect('batches/view/' . $id);
    }

    /**
     * Télécharger le ZIP
     */
    public function download($id)
    {
        $this->auth_lib->require_permission('batch_view');

        $batch = $this->Batch_model->get($id);
        if ( ! $batch || empty($batch->zip_path) || ! file_exists('./' . $batch->zip_path)) {
            $this->session->set_flashdata('error', 'Fichier ZIP introuvable.');
            redirect('batches/view/' . $id);
        }

        force_download('./' . $batch->zip_path, NULL);
    }

    public function mark_sent($id)
    {
        $this->auth_lib->require_permission('batch_finalize');
        $this->Batch_model->mark_sent($id);
        $this->auth_lib->log_action($this->auth_lib->user_id(), 'batch_sent', 'batches', $id);
        $this->session->set_flashdata('success', 'Batch marqué comme envoyé.');
        redirect('batches/view/' . $id);
    }

    public function mark_acknowledged($id)
    {
        $this->auth_lib->require_permission('batch_finalize');
        $this->Batch_model->mark_acknowledged($id);
        $this->auth_lib->log_action($this->auth_lib->user_id(), 'batch_acknowledged', 'batches', $id);
        $this->session->set_flashdata('success', 'Accusé de réception enregistré.');
        redirect('batches/view/' . $id);
    }

    // ===============================================================
    // GÉNÉRATION PDF (FPDF) / ZIP
    // ===============================================================

    private function _generate_batch_zip($batch, $expenses)
    {
        $batch_dir = './uploads/batches/' . $batch->batch_id . '/';
        if ( ! is_dir($batch_dir)) mkdir($batch_dir, 0777, TRUE);

        // 1. Summary PDF
        $summary_path = $batch_dir . 'Batch-Summary.pdf';
        $this->_generate_summary_pdf($batch, $expenses, $summary_path);

        // 2. Expense Sheets
        $expense_files = [];
        foreach ($expenses as $e) {
            $filepath = $batch_dir . $e->expense_id . '.pdf';
            $this->_generate_expense_sheet($e, $filepath);
            $expense_files[] = $filepath;
        }

        // 3. ZIP
        $zip_filename = $batch->batch_id . '.zip';
        $zip_path = 'uploads/batches/' . $zip_filename;

        $zip = new ZipArchive();
        if ($zip->open('./' . $zip_path, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) {
            $zip->addFile($summary_path, 'Batch-Summary.pdf');
            foreach ($expense_files as $file) {
                $zip->addFile($file, basename($file));
            }
            foreach ($expenses as $e) {
                if ( ! empty($e->invoice_path) && file_exists('./' . $e->invoice_path)) {
                    $ext = pathinfo($e->invoice_path, PATHINFO_EXTENSION);
                    $zip->addFile('./' . $e->invoice_path, 'Invoices/' . $e->expense_id . '-invoice.' . $ext);
                }
            }
            $zip->close();
            return $zip_path;
        }

        return false;
    }

    /**
     * Batch Summary PDF (paysage)
     */
    private function _generate_summary_pdf($batch, $expenses, $output_path)
    {
        $pdf = new FPDF('L', 'mm', 'A4'); // Paysage
        $pdf->SetAutoPageBreak(true, 15);
        $pdf->AddPage();

        // Titre
        $pdf->SetFont('Arial', 'B', 16);
        $pdf->SetTextColor(27, 42, 74);
        $pdf->Cell(0, 10, 'BATCH SUMMARY', 0, 1, 'C');

        $pdf->SetFont('Arial', 'B', 12);
        $pdf->SetTextColor(13, 110, 253);
        $pdf->Cell(0, 8, $batch->batch_id, 0, 1, 'C');

        // Infos
        $pdf->SetFont('Arial', '', 9);
        $pdf->SetTextColor(0, 0, 0);
        $pdf->Ln(2);

        $pdf->Cell(30, 5, 'Periode:', 0, 0);
        $pdf->SetFont('Arial', 'B', 9);
        $pdf->Cell(70, 5, date('d/m/Y', strtotime($batch->period_start)) . ' - ' . date('d/m/Y', strtotime($batch->period_end)), 0, 0);

        $pdf->SetFont('Arial', '', 9);
        $pdf->Cell(30, 5, 'Cree par:', 0, 0);
        $pdf->SetFont('Arial', 'B', 9);
        $pdf->Cell(0, 5, iconv('UTF-8', 'windows-1252//TRANSLIT', $batch->created_by_name), 0, 1);

        $pdf->SetFont('Arial', '', 9);
        $pdf->Cell(30, 5, 'Depenses:', 0, 0);
        $pdf->SetFont('Arial', 'B', 9);
        $pdf->Cell(70, 5, $batch->expense_count, 0, 0);

        $pdf->SetFont('Arial', '', 9);
        $pdf->Cell(30, 5, 'Total:', 0, 0);
        $pdf->SetFont('Arial', 'B', 11);
        $pdf->Cell(0, 5, number_format($batch->total_amount, 0, ',', ' ') . ' KMF', 0, 1);

        $pdf->Ln(5);

        // En-tête tableau
        $pdf->SetFont('Arial', 'B', 8);
        $pdf->SetFillColor(27, 42, 74);
        $pdf->SetTextColor(255, 255, 255);

        $cols = [10, 35, 22, 30, 50, 60, 35, 35];
        $headers = ['#', 'Expense ID', 'Date', 'Lieu', 'Fournisseur', 'Description', 'Categorie', 'Montant (KMF)'];

        for ($i = 0; $i < count($headers); $i++) {
            $align = ($i == count($headers) - 1) ? 'R' : 'L';
            $pdf->Cell($cols[$i], 7, $headers[$i], 1, 0, $align, true);
        }
        $pdf->Ln();

        // Lignes
        $pdf->SetTextColor(0, 0, 0);
        $pdf->SetFont('Arial', '', 8);
        $n = 0;
        $fill = false;
        foreach ($expenses as $e) {
            $n++;
            if ($fill) $pdf->SetFillColor(245, 247, 250);
            else $pdf->SetFillColor(255, 255, 255);

            $pdf->Cell($cols[0], 6, $n, 'LR', 0, 'L', true);
            $pdf->Cell($cols[1], 6, $e->expense_id, 'LR', 0, 'L', true);
            $pdf->Cell($cols[2], 6, date('d/m/Y', strtotime($e->expense_date)), 'LR', 0, 'L', true);
            $pdf->Cell($cols[3], 6, iconv('UTF-8', 'windows-1252//TRANSLIT', $e->location_name), 'LR', 0, 'L', true);
            $pdf->Cell($cols[4], 6, iconv('UTF-8', 'windows-1252//TRANSLIT', mb_substr($e->supplier, 0, 30)), 'LR', 0, 'L', true);
            $pdf->Cell($cols[5], 6, iconv('UTF-8', 'windows-1252//TRANSLIT', mb_substr($e->description, 0, 40)), 'LR', 0, 'L', true);
            $pdf->Cell($cols[6], 6, iconv('UTF-8', 'windows-1252//TRANSLIT', $e->category_label), 'LR', 0, 'L', true);
            $pdf->Cell($cols[7], 6, number_format($e->amount, 0, ',', ' '), 'LR', 0, 'R', true);
            $pdf->Ln();
            $fill = !$fill;
        }

        // Total
        $pdf->SetFont('Arial', 'B', 9);
        $pdf->SetFillColor(227, 242, 253);
        $total_w = array_sum(array_slice($cols, 0, 7));
        $pdf->Cell($total_w, 8, 'TOTAL BATCH', 1, 0, 'R', true);
        $pdf->Cell($cols[7], 8, number_format($batch->total_amount, 0, ',', ' ') . ' KMF', 1, 1, 'R', true);

        // Footer
        $pdf->Ln(10);
        $pdf->SetFont('Arial', '', 7);
        $pdf->SetTextColor(128, 128, 128);
        $pdf->Cell(0, 4, 'Wassim Service - Operations Ferry - Ligne Moroni / Mutsamudu', 0, 1, 'L');
        $pdf->Cell(0, 4, 'Document genere le ' . date('d/m/Y a H:i'), 0, 1, 'L');

        $pdf->Output('F', $output_path);
    }

    /**
     * Expense Sheet PDF (portrait, 2 pages)
     */
    /*private function _generate_expense_sheet($expense, $output_path)
    {
        $pdf = new FPDF('P', 'mm', 'A4');
        $pdf->SetAutoPageBreak(true, 15);

        // === PAGE 1 : Expense Sheet ===
        $pdf->AddPage();

        // Titre
        $pdf->SetFont('Arial', 'B', 16);
        $pdf->SetTextColor(27, 42, 74);
        $pdf->Cell(0, 10, 'EXPENSE SHEET', 0, 1, 'C');

        $pdf->SetFont('Arial', '', 8);
        $pdf->SetTextColor(128, 128, 128);
        $pdf->Cell(0, 5, 'Wassim Service - Operations Ferry - Ligne Moroni / Mutsamudu', 0, 1, 'C');

        $pdf->Ln(5);
        $pdf->SetDrawColor(13, 110, 253);
        $pdf->SetLineWidth(0.5);
        $pdf->Line(15, $pdf->GetY(), 195, $pdf->GetY());
        $pdf->Ln(5);

        // Tableau info
        $pdf->SetTextColor(0, 0, 0);
        $label_w = 45;
        $value_w = 140;

        $rows = [
            ['Expense ID', $expense->expense_id],
            ['Date', date('d M Y', strtotime($expense->expense_date))],
            ['Localisation', $expense->location_name],
            ['Fournisseur', $expense->supplier],
            ['Categorie', $expense->category_label],
            ['Description', $expense->description],
            ['N. Facture', $expense->invoice_number ?: '—'],
            ['Devise', $expense->currency],
        ];

        foreach ($rows as $i => $row) {
            $pdf->SetFont('Arial', 'B', 10);
            $pdf->SetFillColor(241, 243, 245);
            $pdf->Cell($label_w, 8, iconv('UTF-8', 'windows-1252//TRANSLIT', $row[0]), 1, 0, 'L', true);
            $pdf->SetFont('Arial', '', 10);
            $pdf->Cell($value_w, 8, iconv('UTF-8', 'windows-1252//TRANSLIT', mb_substr($row[1], 0, 80)), 1, 1, 'L');
        }

        // Montant
        $pdf->Ln(5);
        $pdf->SetFillColor(227, 242, 253);
        $pdf->SetFont('Arial', '', 10);
        $pdf->Cell($label_w, 12, 'Montant', 1, 0, 'C', true);
        $pdf->SetFont('Arial', 'B', 16);
        $pdf->Cell($value_w, 12, number_format($expense->amount, 0, ',', ' ') . ' KMF', 1, 1, 'C', true);

        // Signatures
        $pdf->Ln(15);
        $pdf->SetFont('Arial', 'B', 9);
        $pdf->Cell(90, 6, 'Demande par', 0, 0, 'C');
        $pdf->Cell(90, 6, 'Approuve par', 0, 1, 'C');

        $pdf->SetFont('Arial', '', 9);
        $pdf->Cell(90, 6, iconv('UTF-8', 'windows-1252//TRANSLIT', $expense->created_by_name), 0, 0, 'C');
        $pdf->Cell(90, 6, iconv('UTF-8', 'windows-1252//TRANSLIT', $expense->validated_by_name ?: '________________'), 0, 1, 'C');

        $pdf->SetFont('Arial', '', 7);
        $created_date = $expense->created_at ? date('d/m/Y', strtotime($expense->created_at)) : '';
        $validated_date = $expense->validated_at ? date('d/m/Y', strtotime($expense->validated_at)) : '';
        $pdf->Cell(90, 5, $created_date, 0, 0, 'C');
        $pdf->Cell(90, 5, $validated_date, 0, 1, 'C');

        // Footer
        $pdf->Ln(10);
        $pdf->SetFont('Arial', '', 7);
        $pdf->SetTextColor(128, 128, 128);
        $pdf->Cell(0, 4, 'Document genere le ' . date('d/m/Y a H:i'), 0, 1, 'L');

        // === PAGE 2 : Justificatif ===
        $pdf->AddPage();

        $pdf->SetFont('Arial', 'B', 14);
        $pdf->SetTextColor(27, 42, 74);
        $pdf->Cell(0, 10, 'JUSTIFICATIF - ' . $expense->expense_id, 0, 1, 'C');

        $pdf->SetFont('Arial', '', 9);
        $pdf->SetTextColor(0, 0, 0);
        $pdf->Cell(0, 6, iconv('UTF-8', 'windows-1252//TRANSLIT', $expense->supplier) . ' - ' . date('d/m/Y', strtotime($expense->expense_date)), 0, 1, 'C');

        $pdf->Ln(5);

        if ( ! empty($expense->invoice_path) && file_exists('./' . $expense->invoice_path)) {
            $ext = strtolower(pathinfo($expense->invoice_path, PATHINFO_EXTENSION));
            if (in_array($ext, ['jpg', 'jpeg', 'png'])) {
                // Intégrer l'image
                $img_path = './' . $expense->invoice_path;
                list($img_w, $img_h) = getimagesize($img_path);
                $max_w = 170;
                $max_h = 220;
                $ratio = min($max_w / $img_w, $max_h / $img_h);
                $new_w = $img_w * $ratio;
                $new_h = $img_h * $ratio;
                $x = (210 - $new_w) / 2;
                $pdf->Image($img_path, $x, $pdf->GetY(), $new_w, $new_h);
            } else {
                $pdf->Ln(30);
                $pdf->SetFont('Arial', 'I', 11);
                $pdf->SetTextColor(128, 128, 128);
                $pdf->Cell(0, 10, 'Le justificatif est un fichier PDF joint dans le dossier Invoices/', 0, 1, 'C');
            }
        } else {
            $pdf->Ln(60);
            $pdf->SetFont('Arial', 'I', 14);
            $pdf->SetTextColor(180, 180, 180);
            $pdf->Cell(0, 10, 'Aucun justificatif joint', 0, 1, 'C');
        }

        $pdf->Output('F', $output_path);
    }*/
    

    /**
     * Expense Sheet PDF (portrait, style Yameela)
     */
    private function _generate_expense_sheet($expense, $output_path)
    {
        $pdf = new FPDF('P', 'mm', 'A4');
        $pdf->SetAutoPageBreak(true, 15);
        $pdf->AddPage();

        $lm = 15; // left margin
        $pw = 180; // page width usable

        // ===== HEADER =====
        $pdf->SetFont('Arial', 'B', 18);
        $pdf->SetTextColor(139, 0, 0); // dark red
        $pdf->Cell(0, 10, 'EXPENSE SHEET N.: ' . $expense->expense_id, 0, 1, 'C');
        $pdf->SetFont('Arial', '', 9);
        $pdf->SetTextColor(100, 100, 100);
        $pdf->Cell(0, 5, 'Wassim Service - Ferry Operations - Moroni / Mutsamudu', 0, 1, 'C');
        $pdf->Ln(8);

        // ===== INFO BLOCK =====
        $pdf->SetTextColor(0, 0, 0);
        $pdf->SetFont('Arial', 'B', 9);
        $col1 = 50;
        $col2 = $pw - $col1;

        $pdf->SetFillColor(255, 255, 255);
        $pdf->SetDrawColor(0, 0, 0);

        $info_rows = [
            ['Date of Expenditure:', date('d/m/Y', strtotime($expense->expense_date))],
            ['Operation Date:', $expense->operation_date ? date('d/m/Y', strtotime($expense->operation_date)) : '—'],
            ['Department:', 'Ferry Operations'],
            ['Location:', iconv('UTF-8', 'windows-1252//TRANSLIT', $expense->location_name)],
            ['Name of applicant:', iconv('UTF-8', 'windows-1252//TRANSLIT', $expense->created_by_name)],
        ];

        foreach ($info_rows as $row) {
            $pdf->SetFont('Arial', 'B', 9);
            $pdf->Cell($col1, 7, $row[0], 1, 0, 'L');
            $pdf->SetFont('Arial', '', 9);
            $pdf->Cell($col2, 7, $row[1], 1, 1, 'R');
        }

        $pdf->Ln(6);

        // ===== DETAIL OF EXPENDITURE =====
        $pdf->SetFont('Arial', 'BU', 10);
        $pdf->Cell(5, 6, '', 0, 0);
        $pdf->Cell(0, 6, 'Detail of the expenditure:', 0, 1, 'L');
        $pdf->Ln(2);

        // Header tableau
        $pdf->SetFont('Arial', 'B', 8);
        $pdf->SetFillColor(27, 42, 74);
        $pdf->SetTextColor(255, 255, 255);

        $dc = [70, 30, 30, 50]; // colonnes
        $pdf->Cell($dc[0], 8, 'SERVICE DESCRIPTION', 1, 0, 'C', true);
        $pdf->Cell($dc[1], 8, 'OPERATION DATE', 1, 0, 'C', true);
        $pdf->Cell($dc[2], 8, 'CATEGORY', 1, 0, 'C', true);
        $pdf->Cell($dc[3], 8, 'TOTAL (EXCL. VAT)', 1, 1, 'C', true);

        // Ligne donnée
        $pdf->SetTextColor(0, 0, 0);
        $pdf->SetFont('Arial', '', 8);
        $desc = iconv('UTF-8', 'windows-1252//TRANSLIT', $expense->description);
        $pdf->Cell($dc[0], 7, mb_substr($desc, 0, 45), 1, 0, 'L');
        $pdf->Cell($dc[1], 7, $expense->operation_date ? date('d/m/Y', strtotime($expense->operation_date)) : date('d/m/Y', strtotime($expense->expense_date)), 1, 0, 'C');
        $pdf->Cell($dc[2], 7, iconv('UTF-8', 'windows-1252//TRANSLIT', mb_substr($expense->category_label, 0, 20)), 1, 0, 'C');
        $pdf->Cell($dc[3], 7, number_format($expense->amount, 0, ',', ' ') . ' KMF', 1, 1, 'R');

        // Totaux
        $pdf->SetFont('Arial', 'B', 8);
        $sub_w = $dc[0] + $dc[1] + $dc[2];
        $pdf->Cell($sub_w, 7, 'TOTAL (Excl. VAT)', 1, 0, 'R');
        $pdf->Cell($dc[3], 7, number_format($expense->amount, 0, ',', ' ') . ' KMF', 1, 1, 'R');

        $pdf->Cell($sub_w, 7, 'VAT 0%', 1, 0, 'R');
        $pdf->Cell($dc[3], 7, '0 KMF', 1, 1, 'R');

        $pdf->SetFont('Arial', 'B', 9);
        $pdf->Cell($sub_w, 8, 'TOTAL (Incl. VAT)', 1, 0, 'R');
        $pdf->SetFont('Arial', 'B', 10);
        $pdf->Cell($dc[3], 8, number_format($expense->amount, 0, ',', ' ') . ' KMF', 1, 1, 'R');

        // Montant en lettres
        $pdf->Ln(3);
        $pdf->SetFont('Arial', 'B', 9);
        $pdf->SetTextColor(139, 0, 0);
        $pdf->Cell(30, 6, 'Amount in words: ', 0, 0, 'L');
        $pdf->SetFont('Arial', 'I', 9);
        $pdf->Cell(0, 6, $this->_number_to_words($expense->amount) . ' Francs Comoriens.', 0, 1, 'L');
        $pdf->SetTextColor(0, 0, 0);

        $pdf->Ln(4);

        // ===== INFORMATION FOURNISSEUR =====
        $pdf->SetFont('Arial', 'BU', 10);
        $pdf->Cell(5, 6, '', 0, 0);
        $pdf->Cell(0, 6, 'Information from the supplier or service provider:', 0, 1, 'L');
        $pdf->Ln(2);

        $supplier_rows = [
            ['Name :', iconv('UTF-8', 'windows-1252//TRANSLIT', $expense->supplier)],
            ['Date and NUM invoice:', date('d/m/Y', strtotime($expense->expense_date)) . ($expense->invoice_number ? ' - ' . $expense->invoice_number : '')],
            ['Payment method:', 'Cash'],
            ['Cashbox:', iconv('UTF-8', 'windows-1252//TRANSLIT', $expense->cashbox_name ?: '—')],
        ];

        $pdf->SetFont('Arial', '', 9);
        foreach ($supplier_rows as $row) {
            $pdf->SetFont('Arial', 'B', 9);
            $pdf->Cell(50, 7, $row[0], 1, 0, 'L');
            $pdf->SetFont('Arial', '', 9);
            $pdf->Cell($pw - 50, 7, $row[1], 1, 1, 'L');
        }

        $pdf->Ln(5);


        // ===== VALIDATIONS & SIGNATURES =====
        $pdf->SetFont('Arial', 'BU', 10);
        $pdf->Cell(5, 6, '', 0, 0);
        $pdf->Cell(0, 6, 'Validations & Signatures:', 0, 1, 'L');
        $pdf->Ln(4);

        // Accountant (créateur)
        $pdf->SetFont('Arial', 'I', 9);
        $pdf->SetTextColor(0, 100, 0);
        $pdf->Cell($pw, 5, 'Digitally signed by ' . iconv('UTF-8', 'windows-1252//TRANSLIT', $expense->created_by_name), 0, 1, 'L');
        $pdf->SetFont('Arial', '', 8);
        $pdf->SetTextColor(80, 80, 80);
        $pdf->Cell($pw, 4, 'Accountant - ' . date('d/m/Y H:i', strtotime($expense->created_at)), 0, 1, 'L');

        $pdf->Ln(4);

        // Operations Manager (validateur)
        if ($expense->validated_by_name) {
            $pdf->SetFont('Arial', 'I', 9);
            $pdf->SetTextColor(0, 100, 0);
            $pdf->Cell($pw, 5, 'Digitally signed by ' . iconv('UTF-8', 'windows-1252//TRANSLIT', $expense->validated_by_name), 0, 1, 'L');
            $pdf->SetFont('Arial', '', 8);
            $pdf->SetTextColor(80, 80, 80);
            $pdf->Cell($pw, 4, 'Operations Manager - ' . date('d/m/Y H:i', strtotime($expense->validated_at)), 0, 1, 'L');
        } else {
            $pdf->SetFont('Arial', 'I', 9);
            $pdf->SetTextColor(150, 150, 150);
            $pdf->Cell($pw, 5, 'Operations Manager: Pending approval', 0, 1, 'L');
        }

        $pdf->SetTextColor(0, 0, 0);
        $pdf->Ln(6);

        // ===== FERRY SUPERVISOR (petite case en bas à droite) =====
        $box_w = 70;
        $box_h = 22;
        $box_x = $lm + $pw - $box_w;
        $box_y = $pdf->GetY();

        $pdf->SetFont('Arial', 'B', 8);
        $pdf->SetXY($box_x, $box_y - 5);
        $pdf->Cell($box_w, 5, 'Ferry Supervisor', 0, 1, 'L');

        $pdf->Rect($box_x, $box_y, $box_w, $box_h);

        $pdf->SetFont('Arial', '', 7);
        $pdf->SetXY($box_x + 2, $box_y + 2);
        $pdf->Cell(20, 4, 'Signature:', 0, 0);
        $pdf->Cell($box_w - 24, 4, '', 'B', 1);

        $pdf->SetXY($box_x + 2, $box_y + 12);
        $pdf->Cell(20, 4, 'Date:', 0, 0);
        $pdf->Cell($box_w - 24, 4, '', 'B', 1);

        $pdf->SetY($box_y + $box_h + 3);

        
        // Footer
        $pdf->SetY(-20);
        $pdf->SetFont('Arial', '', 7);
        $pdf->SetTextColor(128, 128, 128);
        $pdf->Cell(0, 4, 'Wassim Service - Ferry Operations - Document generated on ' . date('d/m/Y H:i'), 0, 1, 'C');

        // === PAGE 2 : Justificatif ===
        $pdf->AddPage();

        $pdf->SetFont('Arial', 'B', 14);
        $pdf->SetTextColor(139, 0, 0);
        $pdf->Cell(0, 10, 'SUPPORTING DOCUMENT - ' . $expense->expense_id, 0, 1, 'C');

        $pdf->SetFont('Arial', '', 9);
        $pdf->SetTextColor(0, 0, 0);
        $pdf->Cell(0, 6, iconv('UTF-8', 'windows-1252//TRANSLIT', $expense->supplier) . ' - ' . date('d/m/Y', strtotime($expense->expense_date)), 0, 1, 'C');
        $pdf->Ln(5);

        if ( ! empty($expense->invoice_path) && file_exists('./' . $expense->invoice_path)) {
            $ext = strtolower(pathinfo($expense->invoice_path, PATHINFO_EXTENSION));
            $img_path = null;

            if (in_array($ext, ['jpg', 'jpeg', 'png'])) {
                $img_path = './' . $expense->invoice_path;
            } elseif ($ext === 'pdf') {
                // Convertir le PDF en image via Ghostscript
                $img_path = $this->_pdf_to_image('./' . $expense->invoice_path);
            }

            if ($img_path && file_exists($img_path)) {
                list($img_w, $img_h) = getimagesize($img_path);
                if ($img_w && $img_h) {
                    $max_w = 170;
                    $max_h = 220;
                    $ratio = min($max_w / $img_w, $max_h / $img_h);
                    $new_w = $img_w * $ratio;
                    $new_h = $img_h * $ratio;
                    $x = (210 - $new_w) / 2;
                    $pdf->Image($img_path, $x, $pdf->GetY(), $new_w, $new_h);
                } else {
                    $pdf->SetFont('Arial', 'I', 10);
                    $pdf->SetTextColor(150, 150, 150);
                    $pdf->Cell(0, 10, 'Unable to process the attached document.', 0, 1, 'C');
                }
            } else {
                $pdf->SetFont('Arial', 'I', 10);
                $pdf->SetTextColor(150, 150, 150);
                $pdf->Cell(0, 10, 'Unable to convert the attached PDF. Original file included in Invoices/ folder.', 0, 1, 'C');
            }
        } else {
            $pdf->Ln(60);
            $pdf->SetFont('Arial', 'I', 14);
            $pdf->SetTextColor(200, 200, 200);
            $pdf->Cell(0, 10, 'No supporting document attached', 0, 1, 'C');
        }

        $pdf->Output('F', $output_path);
    }

    /**
     * Convertir un nombre en lettres (français simplifié)
     */
    private function _number_to_words($number)
    {
        $number = (int) $number;
        if ($number == 0) return 'Zero';

        $units = ['', 'Un', 'Deux', 'Trois', 'Quatre', 'Cinq', 'Six', 'Sept', 'Huit', 'Neuf',
                   'Dix', 'Onze', 'Douze', 'Treize', 'Quatorze', 'Quinze', 'Seize',
                   'Dix-Sept', 'Dix-Huit', 'Dix-Neuf'];
        $tens = ['', '', 'Vingt', 'Trente', 'Quarante', 'Cinquante', 'Soixante', 
                 'Soixante', 'Quatre-Vingt', 'Quatre-Vingt'];

        $result = '';

        if ($number >= 1000000) {
            $millions = (int)($number / 1000000);
            $result .= ($millions == 1 ? 'Un' : $this->_number_to_words($millions)) . ' Million' . ($millions > 1 ? 's' : '') . ' ';
            $number %= 1000000;
        }

        if ($number >= 1000) {
            $thousands = (int)($number / 1000);
            if ($thousands == 1) {
                $result .= 'Mille ';
            } else {
                $result .= $this->_number_to_words($thousands) . ' Mille ';
            }
            $number %= 1000;
        }

        if ($number >= 100) {
            $hundreds = (int)($number / 100);
            if ($hundreds == 1) {
                $result .= 'Cent ';
            } else {
                $result .= $units[$hundreds] . ' Cents ';
            }
            $number %= 100;
        }

        if ($number >= 20) {
            $t = (int)($number / 10);
            $u = $number % 10;

            if ($t == 7 || $t == 9) {
                $result .= $tens[$t] . '-' . $units[10 + $u] . ' ';
            } else {
                $result .= $tens[$t];
                if ($u > 0) {
                    $result .= ($u == 1 && $t != 8 ? '-et-' : '-') . $units[$u];
                } elseif ($t == 8) {
                    $result .= 's';
                }
                $result .= ' ';
            }
        } elseif ($number > 0) {
            $result .= $units[$number] . ' ';
        }

        return trim($result);
    }



    /**
     * Convertir la première page d'un PDF en image JPG via Ghostscript
     */
    private function _pdf_to_image($pdf_path)
    {
        $output_path = $pdf_path . '.jpg';

        // Chercher Ghostscript sur Windows
        $gs_paths = [
            'gswin64c',  // Si dans le PATH
            'gswin32c',
            'C:\\Program Files\\gs\\gs10.05.0\\bin\\gswin64c.exe',
            'C:\\Program Files\\gs\\gs10.04.0\\bin\\gswin64c.exe',
            'C:\\Program Files\\gs\\gs10.03.0\\bin\\gswin64c.exe',
            'C:\\Program Files\\gs\\gs10.02.0\\bin\\gswin64c.exe',
            'C:\\Program Files (x86)\\gs\\gs10.05.0\\bin\\gswin32c.exe',
        ];

        $gs_cmd = null;
        foreach ($gs_paths as $path) {
            if (strpos($path, '\\') !== false) {
                // Chemin complet, vérifier s'il existe
                if (file_exists($path)) {
                    $gs_cmd = '"' . $path . '"';
                    break;
                }
            } else {
                // Nom simple, tester via where (Windows)
                exec('where ' . $path . ' 2>NUL', $out, $ret);
                if ($ret === 0) {
                    $gs_cmd = $path;
                    break;
                }
            }
        }

        // Fallback Linux
        if ( ! $gs_cmd) {
            exec('which gs 2>/dev/null', $out, $ret);
            if ($ret === 0) $gs_cmd = 'gs';
        }

        if ( ! $gs_cmd) {
            log_message('error', 'Ghostscript not found for PDF to image conversion');
            return null;
        }

        $cmd = $gs_cmd . ' -dNOPAUSE -dBATCH -sDEVICE=jpeg -dJPEGQ=90 -r200'
             . ' -dFirstPage=1 -dLastPage=1'
             . ' -sOutputFile="' . realpath(dirname($output_path)) . DIRECTORY_SEPARATOR . basename($output_path) . '"'
             . ' "' . realpath($pdf_path) . '"'
             . ' 2>&1';

        exec($cmd, $output, $return_code);

        if ($return_code === 0 && file_exists($output_path)) {
            return $output_path;
        }

        log_message('error', 'Ghostscript conversion failed: ' . implode("\n", $output));
        return null;
    }
}
