<?php

namespace App\Services;

use Dompdf\Dompdf;
use Dompdf\Options;

class PdfGeneratorService
{
    private Dompdf $dompdf;
    private array $company;
    private array $invoice;
    private array $lines;
    private array $client;
    private NumberToWordsService $wordsService;

    public function __construct()
    {
        $options = new Options();
        $options->set('isHtml5ParserEnabled', true);
        $options->set('isPhpEnabled', false);
        $options->set('isRemoteEnabled', true);
        $options->set('defaultFont', 'DejaVu Sans');
        $options->set('fontDir', FCPATH . 'assets/fonts/');
        $options->set('fontCache', WRITEPATH . 'cache/fonts/');
        $options->set('chroot', FCPATH);

        $this->dompdf = new Dompdf($options);
        $this->wordsService = new NumberToWordsService();
    }

    public function generateInvoice(array $company, array $invoice, array $lines, array $client): string
    {
        $this->company = $company;
        $this->invoice = $invoice;
        $this->lines = $lines;
        $this->client = $client;

        $html = $this->buildInvoiceHtml();

        $this->dompdf->loadHtml($html);
        $this->dompdf->setPaper('A4', 'portrait');
        $this->dompdf->render();

        $filename = 'FACTURE_' . str_replace('/', '_', $invoice['invoice_number']) . '.pdf';
        $filepath = WRITEPATH . 'uploads/' . $filename;

        file_put_contents($filepath, $this->dompdf->output());

        return $filepath;
    }

    private function buildInvoiceHtml(): string
    {
        $c = $this->company;
        $i = $this->invoice;
        $cl = $this->client;

        $logoHtml = '';
        if (!empty($c['logo']) && file_exists(FCPATH . 'uploads/logos/' . $c['logo'])) {
            $logoPath = FCPATH . 'uploads/logos/' . $c['logo'];
            $logoData = base64_encode(file_get_contents($logoPath));
            $logoHtml = '<img src="data:image/png;base64,' . $logoData . '" style="max-height:80px;" />';
        }

        $linesHtml = '';
        foreach ($this->lines as $line) {
            $linesHtml .= sprintf(
                '<tr><td style="padding:6px;border-bottom:1px solid #ddd;">%s</td>' .
                '<td style="padding:6px;border-bottom:1px solid #ddd;text-align:right;">%s</td></tr>',
                htmlspecialchars($line['designation']),
                number_format($line['amount'], 2, ',', ' ')
            );
        }

        $amountWords = $this->wordsService->toWords((float) $i['net_payable']);

        return '<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
@page { margin: 15mm; }
body { font-family: DejaVu Sans, Arial, sans-serif; font-size: 11px; color: #333; }
.header { border-bottom: 3px solid #1a5276; padding-bottom: 15px; margin-bottom: 20px; }
.header-left { float: left; width: 55%; }
.header-right { float: right; width: 40%; text-align: right; }
.company-name { font-size: 18px; font-weight: bold; color: #1a5276; }
.company-info { font-size: 10px; line-height: 1.4; }
.invoice-title { font-size: 22px; font-weight: bold; color: #1a5276; margin-bottom: 5px; }
.invoice-number { font-size: 14px; color: #666; }
.clear { clear: both; }
.section { margin-bottom: 15px; }
.section-title { font-weight: bold; color: #1a5276; border-bottom: 1px solid #1a5276; padding-bottom: 3px; margin-bottom: 8px; }
.info-table { width: 100%; }
.info-table td { padding: 3px 0; font-size: 10px; }
.info-label { font-weight: bold; width: 35%; }
.lines-table { width: 100%; border-collapse: collapse; margin-top: 15px; }
.lines-table th { background: #1a5276; color: white; padding: 8px; text-align: left; font-size: 10px; }
.lines-table td { padding: 6px; border-bottom: 1px solid #ddd; font-size: 10px; }
.totals-table { width: 45%; float: right; margin-top: 15px; border-collapse: collapse; }
.totals-table td { padding: 6px; font-size: 11px; }
.totals-table .label { text-align: left; }
.totals-table .amount { text-align: right; font-weight: bold; }
.totals-table .total-row { background: #f0f0f0; font-size: 13px; }
.totals-table .net-row { background: #1a5276; color: white; font-size: 14px; }
.footer { margin-top: 30px; border-top: 2px solid #1a5276; padding-top: 10px; font-size: 9px; text-align: center; color: #666; }
.amount-words { margin-top: 20px; padding: 10px; background: #f9f9f9; border: 1px solid #ddd; font-size: 10px; font-style: italic; }
.signature-area { margin-top: 40px; }
.signature-left { float: left; width: 45%; }
.signature-right { float: right; width: 45%; text-align: center; }
.stamp-placeholder { border: 1px dashed #999; height: 80px; width: 150px; margin: 0 auto; }
</style>
</head>
<body>
<div class="header">
    <div class="header-left">
        <div class="company-name">' . htmlspecialchars($c['name']) . '</div>
        <div class="company-info">
            ' . htmlspecialchars($c['full_name'] ?? '') . '<br>
            ' . htmlspecialchars($c['address'] ?? '') . '<br>
            Tel: ' . htmlspecialchars($c['phone'] ?? '') . ' - Fax: ' . htmlspecialchars($c['fax'] ?? '') . '<br>
            GSM: ' . htmlspecialchars($c['gsm'] ?? '') . '<br>
            Email: ' . htmlspecialchars($c['email'] ?? '') . '<br>
            MF: ' . htmlspecialchars($c['tax_id'] ?? '') . '
        </div>
    </div>
    <div class="header-right">
        ' . $logoHtml . '
        <div class="invoice-title">FACTURE</div>
        <div class="invoice-number">N° ' . htmlspecialchars($i['invoice_number']) . '</div>
        <div style="margin-top:5px;font-size:11px;">Date: ' . date('d/m/Y', strtotime($i['date'])) . '</div>
    </div>
    <div class="clear"></div>
</div>

<div class="section">
    <table class="info-table">
        <tr><td class="info-label">Code client:</td><td>' . htmlspecialchars($cl['code'] ?? '') . '</td>
            <td class="info-label">Raison sociale:</td><td>' . htmlspecialchars($cl['company_name']) . '</td></tr>
        <tr><td class="info-label">Adresse:</td><td>' . htmlspecialchars($cl['address'] ?? '') . '</td>
            <td class="info-label">Ville:</td><td>' . htmlspecialchars($cl['city'] ?? '') . '</td></tr>
        <tr><td class="info-label">M.Fiscale:</td><td>' . htmlspecialchars($cl['tax_id'] ?? '') . '</td>
            <td class="info-label">ICE:</td><td>' . htmlspecialchars($cl['ice'] ?? '') . '</td></tr>
    </table>
</div>

<div class="section">
    <table class="info-table">
        <tr><td class="info-label">Code en douane:</td><td>' . htmlspecialchars($i['customs_code'] ?? '') . '</td>
            <td class="info-label">Reper.N°:</td><td>' . htmlspecialchars($i['reper_number'] ?? '') . '</td></tr>
        <tr><td class="info-label">Designation:</td><td colspan="3"><strong>' . htmlspecialchars($i['designation_global'] ?? '') . '</strong></td></tr>
        <tr><td class="info-label">Poids Brut:</td><td>' . number_format($i['gross_weight'] ?? 0, 0, ',', ' ') . ' ' . htmlspecialchars($i['weight_unit'] ?? 'KGS') . '</td>
            <td class="info-label">Nbre.Colis:</td><td>' . ($i['package_count'] ?? '') . '</td></tr>
        <tr><td class="info-label">Valeur devise:</td><td>' . number_format($i['currency_value'] ?? 0, 2, ',', ' ') . ' ' . htmlspecialchars($i['currency_unit'] ?? 'EUR') . '</td>
            <td class="info-label">Expéditeur:</td><td>' . htmlspecialchars($i['shipper'] ?? '') . '</td></tr>
    </table>
</div>

<table class="lines-table">
    <thead>
        <tr><th style="width:70%">FRAIS</th><th style="width:30%;text-align:right">MONTANT</th></tr>
    </thead>
    <tbody>
        ' . $linesHtml . '
    </tbody>
</table>

<table class="totals-table">
    <tr><td class="label">Débours:</td><td class="amount">' . number_format($i['subtotal'] ?? 0, 2, ',', ' ') . '</td></tr>
    <tr><td class="label">Taxables:</td><td class="amount">' . number_format($i['vat_base'] ?? 0, 2, ',', ' ') . '</td></tr>
    <tr><td class="label">TVA (' . ($i['vat_rate'] * 100) . '%):</td><td class="amount">' . number_format($i['vat_amount'] ?? 0, 2, ',', ' ') . '</td></tr>
    <tr><td class="label">Droit de timbres:</td><td class="amount">' . number_format($i['stamp_duty'] ?? 0, 2, ',', ' ') . '</td></tr>
    <tr class="total-row"><td class="label">Total Facture:</td><td class="amount">' . number_format($i['total_ttc'] ?? 0, 2, ',', ' ') . '</td></tr>
    <tr><td class="label">Avance:</td><td class="amount">' . number_format($i['advance_amount'] ?? 0, 2, ',', ' ') . '</td></tr>
    <tr class="net-row"><td class="label">Net à payer:</td><td class="amount">' . number_format($i['net_payable'] ?? 0, 2, ',', ' ') . '</td></tr>
</table>
<div class="clear"></div>

<div class="amount-words">
    <strong>ARRETEE LA PRESENTE A LA SOMME DE:</strong> ' . $amountWords . '
</div>

<div class="signature-area">
    <div class="signature-left">
        <div style="font-size:10px;margin-bottom:5px;"><strong>Signature et Cachet</strong></div>
        <div class="stamp-placeholder"></div>
    </div>
    <div class="signature-right">
        <div style="font-size:10px;margin-bottom:5px;"><strong>Le Client</strong></div>
        <div class="stamp-placeholder"></div>
    </div>
    <div class="clear"></div>
</div>

<div class="footer">
    ' . htmlspecialchars($c['full_name'] ?? $c['name']) . ' - ' . htmlspecialchars($c['address'] ?? '') . ' - MF: ' . htmlspecialchars($c['tax_id'] ?? '') . '<br>
    Tel: ' . htmlspecialchars($c['phone'] ?? '') . ' - Email: ' . htmlspecialchars($c['email'] ?? '') . '<br>
    Cette facture est payable à ' . ($c['payment_terms'] ?? 30) . ' jours. Pénalités de retard: 3 fois le taux d'intérêt légal.
</div>
</body>
</html>';
    }
}
