<?php
/**
 * TaxCalendarPDF - Generador de PDF para Calendario Tributario
 * Basado en mPDF (extraido de dw2pdf plugin)
 *
 * Genera documentos PDF de alta calidad a partir del contenido HTML
 * de las pestañas del calendario tributario.
 */

namespace dokuwiki\plugin\beztaxcalendar\lib;

use Mpdf\Mpdf;
use Mpdf\MpdfException;

class TaxCalendarPDF {

    /** @var Mpdf */
    protected $mpdf;

    /** @var string Titulo del documento */
    protected $title;

    /** @var string Subtitulo */
    protected $subtitle;

    /** @var string Directorio temporal para limpieza */
    protected $tmpDir;

    /**
     * Constructor
     *
     * @param string $title Titulo del PDF
     * @param string $subtitle Subtitulo opcional
     * @param string $orientation portrait o landscape
     */
    public function __construct($title = '', $subtitle = '', $orientation = 'landscape') {
        global $conf;

        // Intentar aumentar memoria para mPDF
        $currentLimit = ini_get('memory_limit');
        $currentBytes = $this->parseMemoryLimit($currentLimit);
        $requiredBytes = 128 * 1024 * 1024; // 128MB
        if ($currentBytes > 0 && $currentBytes < $requiredBytes) {
            @ini_set('memory_limit', '128M');
        }

        // Cargar autoload de mpdf
        $autoloadPath = __DIR__ . '/mpdf_autoload.php';
        if (!file_exists($autoloadPath)) {
            throw new \Exception('No se encontro la libreria mPDF en: ' . $autoloadPath);
        }
        require_once $autoloadPath;

        $this->title = $title;
        $this->subtitle = $subtitle;

        $this->tmpDir = $conf['tmpdir'] . '/taxcalpdf/' . uniqid('pdf_', true) . '/';
        io_mkdir_p($this->tmpDir);

        $format = 'Letter';
        if ($orientation === 'landscape') {
            $format .= '-L';
        }

        try {
            $this->mpdf = new Mpdf([
                'mode' => 'c',
                'format' => $format,
                'default_font_size' => 9,
                'default_font' => 'helvetica',
                'margin_left' => 10,
                'margin_right' => 10,
                'margin_top' => 35,
                'margin_bottom' => 20,
                'margin_header' => 8,
                'margin_footer' => 8,
                'tempDir' => $this->tmpDir,
                'autoScriptToLang' => false,
                'autoLangToFont' => false,
                'useSubstitutions' => false,
            ]);

            $this->mpdf->SetTitle($title);
            $this->mpdf->SetAuthor('SIE Asesorias - Calendario Tributario DIAN');
            $this->mpdf->SetCreator('BEZ Tax Calendar Plugin');

            $this->mpdf->ignore_invalid_utf8 = true;
            $this->mpdf->SetDirectionality('ltr');

            // Deshabilitar features costosos en memoria
            $this->mpdf->useKerning = false;
            $this->mpdf->useAdobeCJK = false;

        } catch (MpdfException $e) {
            throw new \Exception('Error al inicializar mPDF: ' . $e->getMessage());
        }
    }

    /**
     * Convierte string de memory_limit a bytes
     */
    protected function parseMemoryLimit($val) {
        $val = trim($val);
        if ($val === '-1') return -1;
        $last = strtolower($val[strlen($val) - 1]);
        $val = (int)$val;
        switch ($last) {
            case 'g': $val *= 1024;
            case 'm': $val *= 1024;
            case 'k': $val *= 1024;
        }
        return $val;
    }

    /**
     * Genera el PDF con el contenido HTML proporcionado
     *
     * @param string $htmlContent Contenido HTML de la pestaña
     * @param string $tabType Tipo de pestaña (view, obligations, client)
     * @return string Contenido binario del PDF
     */
    public function generate($htmlContent, $tabType = 'view') {

        // Header con logo y titulo
        $headerHtml = $this->buildHeader();
        $this->mpdf->SetHTMLHeader($headerHtml);

        // Footer con paginacion y fecha
        $footerHtml = $this->buildFooter();
        $this->mpdf->SetHTMLFooter($footerHtml);

        // Estilos CSS para el PDF
        $css = $this->buildStyles($tabType);
        $this->mpdf->WriteHTML($css, \Mpdf\HTMLParserMode::HEADER_CSS);

        // Contenido principal
        $html = '<div class="pdf-content">';
        $html .= $htmlContent;
        $html .= '</div>';

        $this->mpdf->WriteHTML($html, \Mpdf\HTMLParserMode::HTML_BODY);

        return $this->mpdf->Output('', 'S');
    }

    /**
     * Construye el header HTML del PDF
     */
    protected function buildHeader() {
        $date = date('d/m/Y');
        return '
        <div style="border-bottom: 2px solid #2b73b7; padding-bottom: 5px; margin-bottom: 10px;">
            <table width="100%" style="border:none;">
                <tr>
                    <td style="border:none; width:70%; vertical-align:bottom;">
                        <span style="font-size: 14pt; font-weight: bold; color: #2b73b7;">' . htmlspecialchars($this->title) . '</span>
                        <br>
                        <span style="font-size: 9pt; color: #666;">' . htmlspecialchars($this->subtitle) . '</span>
                    </td>
                    <td style="border:none; width:30%; text-align: right; vertical-align:bottom;">
                        <span style="font-size: 8pt; color: #999;">Generado: ' . $date . '</span>
                    </td>
                </tr>
            </table>
        </div>';
    }

    /**
     * Construye el footer HTML del PDF
     */
    protected function buildFooter() {
        return '
        <div style="border-top: 1px solid #ddd; padding-top: 5px; font-size: 7pt; color: #999;">
            <table width="100%" style="border:none;">
                <tr>
                    <td style="border:none; text-align:left;">Calendario Tributario DIAN - SIE Asesorias</td>
                    <td style="border:none; text-align:right;">Pagina {PAGENO} de {nbpg}</td>
                </tr>
            </table>
        </div>';
    }

    /**
     * Construye los estilos CSS para el PDF
     *
     * @param string $tabType
     * @return string
     */
    protected function buildStyles($tabType) {
        $css = '
        <style>
            body { font-family: helvetica, sans-serif; font-size: 9pt; color: #333; }
            .pdf-content { padding: 0; }

            h2 { color: #2b73b7; font-size: 13pt; margin: 15px 0 10px; border-bottom: 1px solid #eee; padding-bottom: 5px; }
            h3 { color: #333; font-size: 11pt; margin: 12px 0 8px; background: #f5f5f5; padding: 6px 10px; border-radius: 3px; }
            h3 small { color: #888; font-weight: normal; font-size: 9pt; }
            h4 { color: #555; font-size: 10pt; margin: 10px 0 6px; border-bottom: 1px solid #eee; padding-bottom: 4px; }

            table { width: 100%; border-collapse: collapse; margin: 8px 0; }
            th, td { padding: 4px 6px; border: 1px solid #ccc; font-size: 8pt; }
            th { background: #e9ecef; font-weight: 600; text-align: center; }
            td { text-align: center; }
            td:first-child { text-align: left; }

            .obligation-section { margin-bottom: 15px; page-break-inside: avoid; }

            /* Status badges */
            .status-badge { padding: 2px 6px; border-radius: 8px; font-size: 7pt; }
            .status-active { background: #d4edda; color: #155724; }
            .status-draft { background: #fff3cd; color: #856404; }

            /* Client info */
            .client-info { background: #f0f7ff; padding: 10px; border-radius: 5px; margin-bottom: 12px; }
            .client-info h3 { margin: 0 0 3px; background: none; padding: 0; }
            .client-info p { margin: 0; font-size: 8pt; color: #666; }

            /* Sections */
            .taxcal-section { border: 1px solid #ddd; border-radius: 5px; padding: 10px; margin: 10px 0; page-break-inside: avoid; }

            /* Source highlights */
            .source-exception { background: #fff3cd; }
            .source-master { background: #ffffff; }

            /* Obligation checkboxes - render as text in PDF */
            .obligations-grid { margin: 8px 0; }
            .obligation-item { display: inline-block; padding: 3px 8px; margin: 2px; background: #f0f0f0; border-radius: 3px; font-size: 8pt; }
            .obligation-item.active { background: #d4edda; }
            .obligation-item.inactive { background: #f8f8f8; color: #999; }

            code { background: #f0f0f0; padding: 1px 4px; border-radius: 2px; font-size: 8pt; }
        </style>';

        return $css;
    }

    /**
     * Limpieza del directorio temporal
     */
    public function __destruct() {
        if (!empty($this->tmpDir) && is_dir($this->tmpDir)) {
            $this->removeDir($this->tmpDir);
        }
    }

    /**
     * Elimina un directorio recursivamente
     */
    protected function removeDir($dir) {
        if (!is_dir($dir)) return;
        $items = scandir($dir);
        foreach ($items as $item) {
            if ($item === '.' || $item === '..') continue;
            $path = $dir . $item;
            if (is_dir($path)) {
                $this->removeDir($path . '/');
            } else {
                @unlink($path);
            }
        }
        @rmdir($dir);
    }
}
