<?php
/**
 * OVP-Sponsorizare
 *
 * @package   OVPSPO_Sponsorizare
 * @author    Ovidiu Pantiru - OVP-Digital
 * @copyright 2024 Ovidiu Pantiru
 * @license   GPL-2.0+
 * @link      https://ovidiupantiru.ro
 */

if ( ! defined( 'ABSPATH' ) ) exit;

class OVPSPO_PDF {

    public static function generate( $data, $id ) {
        if ( ! self::load_tcpdf() ) {
            // Fallback: genereaza PDF minimal fara OVPSPO_TCPDF
            return self::generate_fallback( $data, $id );
        }

        $culoare  = OVPSPO_Settings::get( 'culoare_header', '#0F408A' );
        $org_nume = OVPSPO_Settings::get( 'org_nume', '' );
        $org_cif  = OVPSPO_Settings::get( 'org_cif', '' );
        $org_iban = OVPSPO_Settings::get( 'org_iban', '' );
        $an       = OVPSPO_Settings::get( 'an_fiscal', gmdate('Y') - 1 );
        $rgb      = self::hex2rgb( $culoare );

        $pdf = new OVPSPO_TCPDF( 'P', 'mm', 'A4', true, 'UTF-8', false );
        $pdf->SetCreator( 'Formular 230 Plugin' );
        $pdf->SetAuthor( $org_nume );
        $pdf->SetTitle( 'Formular 230 – ' . $data['nume'] . ' ' . $data['prenume'] );
        $pdf->SetMargins( 15, 15, 15 );
        $pdf->SetAutoPageBreak( true, 15 );
        $pdf->setPrintHeader( false );
        $pdf->setPrintFooter( false );
        $pdf->AddPage();

        // Header
        $pdf->SetFillColor( $rgb[0], $rgb[1], $rgb[2] );
        $pdf->Rect( 0, 0, 210, 26, 'F' );
        $pdf->SetTextColor( 255, 255, 255 );
        $pdf->SetFont( 'dejavusans', 'B', 12 );
        $pdf->SetXY( 15, 7 );
        $pdf->Cell( 0, 7, 'CERERE PRIVIND DESTINATIA SUMEI REPREZENTAND PANA LA 3,5%', 0, 1, 'C' );
        $pdf->SetFont( 'dejavusans', '', 9 );
        $pdf->SetXY( 15, 15 );
        $pdf->Cell( 0, 6, 'din impozitul anual pe veniturile din salarii – Anul fiscal: ' . $an, 0, 1, 'C' );
        $pdf->SetTextColor( 0, 0, 0 );

        $y = 32;
        $y = self::section( $pdf, $y, $rgb, 'I. DATE DE IDENTIFICARE A CONTRIBUABILULUI' );
        $y = self::row2( $pdf, $y, 'Nume:', $data['nume'], 'Prenume:', $data['prenume'] );
        $y = self::row2( $pdf, $y, 'CNP / NIF:', $data['cnp'], 'Initiala tatalui:', $data['initiala'] ? $data['initiala'] : '—' );
        $y = self::row2( $pdf, $y, 'Email:', $data['email'] ? $data['email'] : '—', 'Telefon:', $data['telefon'] ? $data['telefon'] : '—' );

        $y = self::section( $pdf, $y + 4, $rgb, 'II. ADRESA DE DOMICILIU' );
        $y = self::row2( $pdf, $y, 'Judet:', $data['judet'], 'Localitate:', $data['localitate'] );
        $strada_full = 'Str. ' . $data['strada'] . ' nr. ' . $data['nr'];
        if ( $data['bloc'] )  $strada_full .= ', bl. ' . $data['bloc'];
        if ( $data['scara'] ) $strada_full .= ', sc. ' . $data['scara'];
        if ( $data['etaj'] )  $strada_full .= ', et. ' . $data['etaj'];
        if ( $data['apart'] ) $strada_full .= ', ap. ' . $data['apart'];
        $y = self::row1( $pdf, $y, 'Adresa:', $strada_full );
        if ( $data['cod_postal'] ) {
            $y = self::row1( $pdf, $y, 'Cod postal:', $data['cod_postal'] );
        }

        $y = self::section( $pdf, $y + 4, $rgb, 'III. DATE ENTITATE BENEFICIARA' );
        $y = self::row1( $pdf, $y, 'Denumire:', $org_nume );
        $y = self::row2( $pdf, $y, 'CIF:', $org_cif, 'IBAN:', $org_iban );

        $y = self::section( $pdf, $y + 4, $rgb, 'IV. PERIOADA REDIRECTIONARII' );
        $pdf->SetXY( 15, $y + 2 );
        $pdf->SetFont( 'dejavusans', '', 9 );
        $pdf->SetDrawColor( 80, 80, 80 );
        $pdf->Rect( 15, $y + 2, 5, 5, 'D' );
        if ( $data['perioada'] == 1 ) {
            $pdf->SetFillColor( $rgb[0], $rgb[1], $rgb[2] );
            $pdf->Rect( 16, $y + 3, 3, 3, 'F' );
        }
        $pdf->SetXY( 22, $y + 2 ); $pdf->Cell( 40, 5, 'Un an' );
        $pdf->Rect( 65, $y + 2, 5, 5, 'D' );
        if ( $data['perioada'] == 2 ) {
            $pdf->SetFillColor( $rgb[0], $rgb[1], $rgb[2] );
            $pdf->Rect( 66, $y + 3, 3, 3, 'F' );
        }
        $pdf->SetXY( 72, $y + 2 ); $pdf->Cell( 40, 5, 'Doi ani' );
        $y += 12;

        $y = self::section( $pdf, $y + 4, $rgb, 'V. DECLARATIE SI SEMNATURA' );
        $pdf->SetXY( 15, $y + 2 );
        $pdf->SetFont( 'dejavusans', 'I', 8 );
        $pdf->SetTextColor( 60, 60, 60 );
        $pdf->MultiCell( 180, 4,
            'Sub sanctiunile aplicate faptei de fals in declaratii, declar ca datele inscrise in acest formular sunt corecte si complete. Sunt de acord ca datele de identificare si suma directionata sa fie comunicate entitatii beneficiare.',
            0, 'L' );
        $pdf->SetTextColor( 0, 0, 0 );
        $y = $pdf->GetY() + 5;

        if ( ! empty( $data['signature'] ) && strpos( $data['signature'], 'data:image' ) === 0 ) {
            $tmp = self::sig_to_file( $data['signature'] );
            if ( $tmp ) {
                $pdf->SetFont( 'dejavusans', 'B', 9 );
                $pdf->SetXY( 15, $y );
                $pdf->Cell( 80, 5, 'Semnatura contribuabil:' );
                $pdf->SetFont( 'dejavusans', '', 9 );
                $pdf->SetXY( 110, $y + 6 );
                $pdf->Cell( 70, 5, gmdate('d.m.Y'), 'B' );
                $pdf->Image( $tmp, 15, $y + 6, 80, 22, '', '', '', false, 150 );
                wp_delete_file( $tmp );
                $y += 32;
            }
        }

        $pdf->SetDrawColor( $rgb[0], $rgb[1], $rgb[2] );
        $pdf->SetLineWidth( 0.4 );
        $pdf->Line( 15, $y + 3, 195, $y + 3 );
        $pdf->SetFont( 'dejavusans', '', 7 );
        $pdf->SetTextColor( 120, 120, 120 );
        $pdf->SetXY( 15, $y + 5 );
        $pdf->Cell( 0, 4, $org_nume . ' | CIF: ' . $org_cif . ' | Generat: ' . gmdate('d.m.Y H:i'), 0, 0, 'C' );

        // Salvare cu nume care include organizatia
        $upload_dir = wp_upload_dir();
        $dir = $upload_dir['basedir'] . '/formular230/';
        if ( ! file_exists( $dir ) ) wp_mkdir_p( $dir );
        if ( ! file_exists( $dir . '.htaccess' ) ) {
            file_put_contents( $dir . '.htaccess', "Options -Indexes\nDeny from all" ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents
        }

        $slug_org  = self::slugify( $org_nume );
        $slug_nume = self::slugify( $data['nume'] . '_' . $data['prenume'] );
        $filename  = 'Formular_230_' . $slug_org . '_' . $slug_nume . '_' . $id . '.pdf';
        $filepath  = $dir . $filename;

        $pdf->Output( $filepath, 'F' );
        return file_exists( $filepath ) ? $filepath : '';
    }

    private static function section( $pdf, $y, $rgb, $title ) {
        $pdf->SetXY( 15, $y );
        $pdf->SetFillColor( $rgb[0], $rgb[1], $rgb[2] );
        $pdf->SetTextColor( 255, 255, 255 );
        $pdf->SetFont( 'dejavusans', 'B', 8 );
        $pdf->Cell( 180, 6, ' ' . $title, 0, 1, 'L', true );
        $pdf->SetTextColor( 0, 0, 0 );
        return $pdf->GetY() + 2;
    }

    private static function row1( $pdf, $y, $label, $value ) {
        $pdf->SetXY( 15, $y );
        $pdf->SetFont( 'dejavusans', 'B', 9 );
        $pdf->Cell( 35, 6, $label, 0, 0 );
        $pdf->SetFont( 'dejavusans', '', 9 );
        $pdf->Cell( 145, 6, $value, 'B', 1 );
        return $pdf->GetY() + 1;
    }

    private static function row2( $pdf, $y, $l1, $v1, $l2, $v2 ) {
        $pdf->SetXY( 15, $y );
        $pdf->SetFont( 'dejavusans', 'B', 9 );
        $pdf->Cell( 30, 6, $l1, 0, 0 );
        $pdf->SetFont( 'dejavusans', '', 9 );
        $pdf->Cell( 55, 6, $v1, 'B', 0 );
        $pdf->SetFont( 'dejavusans', 'B', 9 );
        $pdf->Cell( 30, 6, $l2, 0, 0 );
        $pdf->SetFont( 'dejavusans', '', 9 );
        $pdf->Cell( 55, 6, $v2, 'B', 1 );
        return $pdf->GetY() + 1;
    }

    private static function sig_to_file( $data_uri ) {
        $parts = explode( ',', $data_uri, 2 );
        if ( count($parts) < 2 ) return false;
        $img = base64_decode( $parts[1] );
        if ( ! $img ) return false;
        $tmp = wp_tempnam( 'ovpspo_' ) . '.png'; // phpcs:ignore WordPress.WP.AlternativeFunctions
        file_put_contents( $tmp, $img ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents
        return $tmp;
    }

    private static function slugify( $str ) {
        $str = iconv( 'UTF-8', 'ASCII//TRANSLIT', $str );
        $str = preg_replace( '/[^A-Za-z0-9_]/', '_', $str );
        return trim( $str, '_' );
    }

    /**
     * Fallback PDF minimal cand OVPSPO_TCPDF nu e disponibil.
     * Salveaza fisierul si returneaza path-ul.
     */
    private static function generate_fallback( $data, $id ) {
        $fallback_file = defined('OVPSPO_PATH') ? OVPSPO_PATH . 'includes/class-pdf-fallback.php' : '';
        if ( $fallback_file && file_exists($fallback_file) ) {
            require_once $fallback_file;
        }
        if ( ! class_exists('OVPSPO_PDF_Fallback') ) return '';

        $org_nume = OVPSPO_Settings::get( 'org_nume', '' );
        $an       = OVPSPO_Settings::get( 'an_fiscal', gmdate('Y') - 1 );

        $rows = array(
            'Organizație'       => $org_nume,
            'An fiscal'         => $an,
            'Nume contribuabil' => $data['prenume'] . ' ' . $data['nume'],
            'CNP'               => $data['cnp'] ?? '',
            'Județ'             => $data['judet'] ?? '',
            'Localitate'        => $data['localitate'] ?? '',
            'Stradă'            => ($data['strada'] ?? '') . ' ' . ($data['nr'] ?? ''),
            'Email'             => $data['email'] ?? '',
            'Telefon'           => $data['telefon'] ?? '',
            'Perioadă'          => isset($data['perioada']) && $data['perioada'] == 2 ? '2 ani' : '1 an',
        );

        $footer = 'ATENȚIE: Acest PDF este generat în modul de urgență. '
                . 'Instalați OVPSPO_TCPDF din setările pluginului pentru PDF-ul oficial ANAF.';

        $pdf_content = OVPSPO_PDF_Fallback::generate( 'Formular 230 – Declarație 3,5%', $rows, $footer );

        $upload_dir = wp_upload_dir();
        $dir = $upload_dir['basedir'] . '/formular230/';
        if ( ! file_exists($dir) ) wp_mkdir_p( $dir );

        $filename = 'f230_fallback_' . intval($id) . '_' . gmdate('YmdHis') . '.pdf';
        $path     = $dir . $filename;
        file_put_contents( $path, $pdf_content ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents

        return file_exists($path) ? $path : '';
    }

    private static function load_tcpdf() {
        if ( class_exists( 'OVPSPO_TCPDF' ) ) return true;

        $paths = array(
            // OVPSPO_TCPDF bundled in plugin (prioritate maxima)
            defined('OVPSPO_PATH') ? OVPSPO_PATH . 'lib/tcpdf/tcpdf.php' : '',
            defined('OVPSPO_PATH')    ? OVPSPO_PATH    . 'lib/tcpdf/tcpdf.php' : '',
            defined('OVPSPO_PATH')  ? OVPSPO_PATH  . 'lib/tcpdf/tcpdf.php' : '',
            // Instalat extern ca fallback
            defined('OVPSPO_TCPDF_PATH') ? OVPSPO_TCPDF_PATH : '',
            defined('OVPSPO_TCPDF_PATH')  ? OVPSPO_TCPDF_PATH  : '',
        );

        foreach ( $paths as $path ) {
            if ( $path && file_exists( $path ) ) {
                require_once $path;
                // Creeaza alias daca TCPDF e incarcat ca 'TCPDF' (bundled) in loc de 'OVPSPO_TCPDF'
                if ( class_exists( 'TCPDF' ) && ! class_exists( 'OVPSPO_TCPDF' ) ) {
                    class_alias( 'TCPDF', 'OVPSPO_TCPDF' ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals
                }
                if ( class_exists( 'OVPSPO_TCPDF' ) ) return true;
            }
        }
        return false;
    }

    /**
     * Verifica daca OVPSPO_TCPDF e disponibil, altfel intoarce false
     * pentru a folosi fallback-ul
     */
    private static function has_tcpdf() {
        return self::load_tcpdf();
    }

    private static function hex2rgb( $hex ) {
        $hex = ltrim( $hex, '#' );
        if ( strlen($hex) == 3 ) $hex = $hex[0].$hex[0].$hex[1].$hex[1].$hex[2].$hex[2];
        return array( hexdec(substr($hex,0,2)), hexdec(substr($hex,2,2)), hexdec(substr($hex,4,2)) );
    }
}
