<?php
/**
 * ComptaFlow - Service de generation PDF
 * Utilise Dompdf pour generer des factures PDF
 */

namespace ComptaFlowPro\Services;

use Dompdf\Dompdf;
use Dompdf\Options;

defined('ABSPATH') || exit;

class PDFGenerator {

    /**
     * Dossier de stockage des PDFs
     */
    private static function getStorageDir(): string {
        $upload_dir = wp_upload_dir();
        $base_dir = $upload_dir['basedir'] . '/comptaflow';

        $dirs = ['invoices'];
        foreach ($dirs as $dir) {
            $path = $base_dir . '/' . $dir;
            if (!file_exists($path)) {
                wp_mkdir_p($path);
                file_put_contents($base_dir . '/.htaccess', "Options -Indexes\n");
            }
        }

        return $base_dir;
    }

    /**
     * Generer le PDF d'une facture
     */
    public static function generateInvoice(int $invoice_id, bool $force = false): string|false {
        $invoice = InvoiceService::getById($invoice_id, true);

        if (!$invoice) {
            return false;
        }

        $filename = sanitize_file_name($invoice['invoice_number']) . '.pdf';
        $filepath = self::getStorageDir() . '/invoices/' . $filename;

        if (file_exists($filepath) && !$force) {
            return $filepath;
        }

        $client = ClientService::getById($invoice['client_id']);
        $company = self::getCompanyInfo();
        $lines = $invoice['lines'] ?? InvoiceService::getLines($invoice_id);

        $html = self::renderTemplate('invoice', [
            'invoice' => $invoice,
            'client' => $client,
            'company' => $company,
            'lines' => $lines,
        ]);

        return self::generatePDF($html, $filepath);
    }

    /**
     * Generer le PDF a partir du HTML
     */
    private static function generatePDF(string $html, string $filepath): string|false {
        try {
            $options = new Options();
            $options->set('isRemoteEnabled', true);
            $options->set('isHtml5ParserEnabled', true);
            $options->set('defaultFont', 'DejaVu Sans');
            $options->set('tempDir', sys_get_temp_dir());

            $dompdf = new Dompdf($options);
            $dompdf->loadHtml($html);
            $dompdf->setPaper('A4', 'portrait');
            $dompdf->render();

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

            return $filepath;

        } catch (\Exception $e) {
            error_log('ComptaFlow PDF Error: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Telecharger un PDF
     */
    public static function download(string $type, int $id): void {
        if (!current_user_can('manage_options')) {
            wp_die('Permissions insuffisantes.');
        }

        if (!isset($_GET['_wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['_wpnonce'])), 'download_pdf_' . $type . '_' . $id)) {
            wp_die('Lien expire. Veuillez reessayer.');
        }

        $filepath = false;
        if ($type === 'invoice') {
            $filepath = self::generateInvoice($id);
        }

        if (!$filepath || !file_exists($filepath)) {
            wp_die('Impossible de generer le PDF.');
        }

        $filename = basename($filepath);

        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Content-Length: ' . filesize($filepath));
        header('Cache-Control: private, max-age=0, must-revalidate');
        header('Pragma: public');

        readfile($filepath);
        exit;
    }

    /**
     * Afficher un PDF dans le navigateur
     */
    public static function view(string $type, int $id): void {
        if (!current_user_can('manage_options')) {
            wp_die('Permissions insuffisantes.');
        }

        if (!isset($_GET['_wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['_wpnonce'])), 'view_pdf_' . $type . '_' . $id)) {
            wp_die('Lien expire. Veuillez reessayer.');
        }

        $filepath = false;
        if ($type === 'invoice') {
            $filepath = self::generateInvoice($id);
        }

        if (!$filepath || !file_exists($filepath)) {
            wp_die('Impossible de generer le PDF.');
        }

        header('Content-Type: application/pdf');
        header('Content-Disposition: inline; filename="' . basename($filepath) . '"');
        header('Content-Length: ' . filesize($filepath));

        readfile($filepath);
        exit;
    }

    /**
     * Obtenir l'URL de telechargement d'un PDF
     */
    public static function getDownloadUrl(string $type, int $id): string {
        return admin_url('admin-post.php?' . http_build_query([
            'action' => 'comptaflow_download_pdf',
            'type' => $type,
            'id' => $id,
            '_wpnonce' => wp_create_nonce('download_pdf_' . $type . '_' . $id),
        ]));
    }

    /**
     * Obtenir l'URL de visualisation d'un PDF
     */
    public static function getViewUrl(string $type, int $id): string {
        return admin_url('admin-post.php?' . http_build_query([
            'action' => 'comptaflow_view_pdf',
            'type' => $type,
            'id' => $id,
            '_wpnonce' => wp_create_nonce('view_pdf_' . $type . '_' . $id),
        ]));
    }

    /**
     * Recuperer les informations de l'entreprise
     */
    public static function getCompanyInfo(): array {
        $settings = get_option('comptaflow_company_settings', []);

        $logo_base64 = '';
        if (!empty($settings['company_logo_id'])) {
            $logo_path = get_attached_file($settings['company_logo_id']);
            if ($logo_path && file_exists($logo_path)) {
                $logo_data = file_get_contents($logo_path);
                $logo_mime = mime_content_type($logo_path);
                $logo_base64 = 'data:' . $logo_mime . ';base64,' . base64_encode($logo_data);
            }
        }

        return [
            'name' => $settings['company_name'] ?? '',
            'address' => $settings['address'] ?? '',
            'postal_code' => $settings['postal_code'] ?? '',
            'city' => $settings['city'] ?? '',
            'email' => $settings['company_email'] ?? '',
            'phone' => $settings['company_phone'] ?? '',
            'website' => $settings['company_website'] ?? '',
            'siret' => $settings['siret'] ?? '',
            'vat_number' => $settings['vat_number'] ?? '',
            'vat_regime' => $settings['vat_regime'] ?? 'FRANCHISE',
            'naf_code' => $settings['naf_code'] ?? '',
            'status' => $settings['status'] ?? '',
            'capital_social' => $settings['capital_social'] ?? '',
            'rcs_city' => $settings['rcs_city'] ?? '',
            'iban' => $settings['iban'] ?? '',
            'bic' => $settings['bic'] ?? '',
            'logo' => $logo_base64,
            'payment_terms' => $settings['default_payment_terms'] ?? '',
            'late_payment_penalties' => $settings['late_payment_penalties'] ?? '',
            'recovery_indemnity' => $settings['recovery_indemnity'] ?? '',
            'no_discount' => $settings['no_discount'] ?? '',
        ];
    }

    /**
     * Rendre un template PDF
     */
    private static function renderTemplate(string $template, array $data): string {
        $template_path = COMPTAFLOW_PLUGIN_DIR . 'src/Templates/PDF/' . $template . '.php';

        if (!file_exists($template_path)) {
            return '<html><body><h1>Template non trouve</h1></body></html>';
        }

        extract($data);

        ob_start();
        include $template_path;
        return ob_get_clean();
    }

    /**
     * Formater un montant
     */
    public static function formatAmount(float $amount): string {
        return number_format($amount, 2, ',', ' ') . ' €';
    }

    /**
     * Formater une date
     */
    public static function formatDate(string $date): string {
        return date_i18n('d/m/Y', strtotime($date));
    }
}
