<?php
/**
 * Erzeugt aus einem Angebots-Datensatz ein PDF im grün/weißen Stil
 * (angelehnt an die Word-Vorlage) mithilfe der mitgelieferten
 * Dompdf-Bibliothek.
 */

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

class AG_PDF {

    /**
     * Rendert das PDF und gibt es als Download-Stream aus (beendet danach).
     * Bei Problemen (fehlende PHP-Erweiterungen, Renderfehler) wird eine
     * verständliche Meldung angezeigt statt eines kritischen Fehlers.
     *
     * @param array  $offer    Bereinigter Angebots-Datensatz (AG_Offer::sanitize()).
     * @param string $filename Dateiname ohne Endung.
     */
    public static function stream( array $offer, $filename ) {
        $missing = self::missing_requirements();
        if ( ! empty( $missing ) ) {
            wp_die(
                '<h1>PDF-Erstellung nicht möglich</h1>' .
                '<p>Auf dem Server fehlen folgende PHP-Erweiterungen, die für die PDF-Erzeugung nötig sind: <strong>' .
                esc_html( implode( ', ', $missing ) ) .
                '</strong>.</p><p>Bitte beim Hosting-Anbieter aktivieren lassen (in den meisten Hosting-Panels unter „PHP-Einstellungen/Erweiterungen“ selbst aktivierbar).</p>',
                'PDF-Erstellung nicht möglich',
                array( 'back_link' => true )
            );
        }

        try {
            $pdf = self::render( $offer );
        } catch ( \Throwable $e ) {
            wp_die(
                '<h1>Fehler bei der PDF-Erstellung</h1><p>' . esc_html( $e->getMessage() ) . '</p>',
                'Fehler bei der PDF-Erstellung',
                array( 'back_link' => true )
            );
        }

        $pdf->stream( $filename . '.pdf', array( 'Attachment' => true ) );
        exit;
    }

    /**
     * Prüft die von Dompdf benötigten PHP-Erweiterungen.
     *
     * @return string[] Liste fehlender Erweiterungen (leer = alles vorhanden).
     */
    public static function missing_requirements() {
        $missing = array();
        if ( ! extension_loaded( 'mbstring' ) ) {
            $missing[] = 'mbstring';
        }
        if ( ! extension_loaded( 'gd' ) && ! extension_loaded( 'imagick' ) ) {
            $missing[] = 'gd (für die Logos im PDF)';
        }
        if ( ! extension_loaded( 'dom' ) ) {
            $missing[] = 'dom';
        }
        return $missing;
    }

    /**
     * Rendert und gibt das Dompdf-Objekt zurück (z. B. für Tests/Speichern).
     *
     * @param array $offer
     * @return \Dompdf\Dompdf
     */
    public static function render( array $offer ) {
        require_once AG_PLUGIN_DIR . 'lib/autoload.php';

        $options = new \Dompdf\Options();
        $options->set( 'isRemoteEnabled', true );
        $options->set( 'isHtml5ParserEnabled', true );
        $options->set( 'defaultFont', 'DejaVu Sans' );
        $options->set( 'chroot', AG_PLUGIN_DIR );

        $dompdf = new \Dompdf\Dompdf( $options );
        $dompdf->setPaper( 'A4', 'portrait' );
        $dompdf->loadHtml( self::build_html( $offer ), 'UTF-8' );
        $dompdf->render();

        return $dompdf;
    }

    /**
     * Baut das vollständige HTML-Dokument für das Angebot.
     */
    private static function build_html( array $offer ) {
        $logo_data  = self::image_data_uri( AG_PLUGIN_DIR . 'assets/img/logo.jpg', 'image/jpeg' );
        $hallo_data = self::image_data_uri( AG_PLUGIN_DIR . 'assets/img/hallo-hola.png', 'image/png' );

        $company = AG_Settings::get();

        $lang = isset( $offer['doc_language'] ) ? $offer['doc_language'] : 'ES';
        $t    = AG_I18n::strings( $lang );

        $number = esc_html( $offer['number'] );
        $date   = esc_html( AG_Offer::format_date_display( $offer['offer_date'] ) );

        $client = esc_html( self::client_display( $offer ) );
        $dni    = esc_html( $offer['dni'] );
        $addr   = esc_html( $offer['address'] );

        $intro = $offer['intro'] !== ''
            ? wp_kses_post( $offer['intro'] )
            : esc_html( $t['intro'] );

        // Positionszeilen
        $rows_html = '';
        foreach ( $offer['items'] as $item ) {
            $rows_html .= '<tr>'
                . '<td class="c-center">' . esc_html( self::num( $item['qty'] ) ) . '</td>'
                . '<td>' . nl2br( esc_html( $item['concept'] ) ) . '</td>'
                . '<td class="c-right">' . esc_html( AG_Offer::format_money( $item['price'], false ) ) . '</td>'
                . '<td class="c-center">' . esc_html( self::num( $item['units'] ) ) . '</td>'
                . '<td class="c-right">' . esc_html( AG_Offer::format_money( $item['amount'] ) ) . '</td>'
                . '</tr>';
        }
        if ( '' === $rows_html ) {
            $rows_html = '<tr><td colspan="5" class="c-center" style="color:#999;">' . esc_html( $t['no_items'] ) . '</td></tr>';
        }

        $sum_items = esc_html( AG_Offer::format_money( $offer['sum_items'] ) );
        $discount  = esc_html( AG_Offer::format_money( $offer['discount'] ) );
        $total     = esc_html( AG_Offer::format_money( $offer['total'] ) );

        $unit_h_checked  = ( 'h' === $offer['unit'] ) ? '&#9746;' : '&#9744;';   // ☒ / ☐
        $unit_hl_checked = ( 'hl' === $offer['unit'] ) ? '&#9746;' : '&#9744;';

        $notes = $offer['notes'] !== '' ? '<div class="notes">' . wp_kses_post( $offer['notes'] ) . '</div>' : '';

        $note_text = sprintf( $t['note_text'], '<strong>' . esc_html( $company['email'] ) . '</strong>' );

        ob_start();
        ?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<style>
    @page { margin: 1.5cm 1.4cm 2.2cm 1.4cm; }
    * { font-family: "DejaVu Sans", sans-serif; }
    body { color: #1a1a1a; font-size: 10.5px; line-height: 1.5; }
    .green { color: #0f6734; }
    .orange { color: #b5651d; }
    h1 { color: #0f6734; font-size: 17px; margin: 0 0 2px; }
    .header-table { width: 100%; border-collapse: collapse; margin-bottom: 10px; }
    .header-table td { vertical-align: top; }
    .header-meta { font-size: 11px; }
    .header-logo { text-align: right; }
    .header-logo img { width: 130px; }
    .company-line { color: #6b6b6b; font-size: 8.5px; margin-top: 6px; text-align: right; }
    .hallo { text-align: right; margin: 2px 0 12px; }
    .hallo img { width: 190px; border-radius: 6px; }
    /* Bankdaten-Fußzeile auf jeder Seite */
    .footer {
        position: fixed; bottom: -1.4cm; left: 0; right: 0;
        border-top: 1px solid #d0e8d6; padding-top: 4px;
        color: #0f6734; font-size: 8px; font-weight: bold;
    }
    .client-box {
        background: #edf6ef; border: 1px solid #d0e8d6; border-radius: 4px;
        padding: 8px 12px; margin-bottom: 12px;
    }
    .client-box p { margin: 2px 0; }
    .badges { width: 100%; border-collapse: collapse; margin: 12px 0; }
    .badges td {
        width: 33%; text-align: center; background: #edf6ef;
        border: 1px solid #d0e8d6; padding: 8px; color: #0f6734; font-weight: bold;
    }
    table.items { width: 100%; border-collapse: collapse; margin-top: 6px; }
    table.items th {
        background: #0f6734; color: #fff; padding: 7px 8px; text-align: left; font-size: 10px;
        white-space: nowrap; vertical-align: middle;
    }
    table.items td { padding: 7px 8px; border-bottom: 1px solid #e1e8e3; vertical-align: top; }
    .c-center { text-align: center; }
    .c-right { text-align: right; }
    .totals { width: 100%; border-collapse: collapse; margin-top: 4px; }
    .totals td { padding: 5px 8px; }
    .totals .label { text-align: right; }
    .totals .val { text-align: right; width: 130px; }
    .totals .total-row td {
        background: #0f6734; color: #fff; font-weight: bold; font-size: 12px;
    }
    .unit-line { margin: 12px 0 4px; font-size: 11px; }
    .legal { font-size: 9px; color: #555; margin: 2px 0; }
    .pay-title { color: #0f6734; font-weight: bold; margin: 16px 0 6px; font-size: 12px; }
    .pay-box {
        background: #edf6ef; border: 1px solid #d0e8d6; border-radius: 4px;
        padding: 8px 12px; margin-bottom: 8px;
    }
    .pay-box .chk { color: #0f6734; font-weight: bold; }
    .closing { margin: 14px 0; }
    .notes {
        background: #edf6ef; border: 1px solid #d0e8d6; border-radius: 4px;
        padding: 8px 12px; margin-top: 10px; font-size: 10px;
    }
    .sign-table { width: 100%; border-collapse: collapse; margin-top: 18px; border: 1px solid #0f6734; }
    .sign-table td { padding: 10px; border: 1px solid #cfe0d5; vertical-align: top; height: 46px; }
    .sign-head { font-weight: bold; font-size: 10px; }
</style>
</head>
<body>

    <div class="footer">
        <?php echo esc_html( $t['bank_label'] . ' · ' . $company['company'] . ' · N.I.F. ' . $company['nif'] ); ?><br>
        <?php echo esc_html( $company['bank1'] ); ?><br>
        <?php echo esc_html( $company['bank2'] ); ?>
    </div>

    <table class="header-table">
        <tr>
            <td class="header-meta">
                <h1><?php echo esc_html( $t['title'] ); ?></h1>
                <div><?php echo esc_html( $t['subtitle'] ); ?></div>
                <div style="margin-top:6px;">
                    <strong class="green"><?php echo esc_html( $t['number'] ); ?></strong> <strong class="orange"><?php echo $number; ?></strong><br>
                    <strong class="green"><?php echo esc_html( $t['date'] ); ?></strong> <?php echo $date; ?>
                </div>
            </td>
            <td class="header-logo">
                <?php if ( $logo_data ) : ?><img src="<?php echo $logo_data; ?>" alt="Die Schule"><?php endif; ?>
                <div class="company-line">
                    <?php echo esc_html( $company['address'] ); ?><br>
                    <?php echo esc_html( 't ' . $company['phone'] ); ?><br>
                    <?php echo esc_html( $company['email'] . ' · ' . $company['web'] ); ?>
                </div>
            </td>
        </tr>
    </table>

    <?php if ( $hallo_data ) : ?>
        <div class="hallo"><img src="<?php echo $hallo_data; ?>" alt=""></div>
    <?php endif; ?>

    <div class="client-box">
        <p><strong><?php echo esc_html( $t['client'] ); ?></strong> <?php echo $client; ?></p>
        <p><strong><?php echo esc_html( $t['id'] ); ?></strong> <?php echo $dni; ?></p>
        <p><strong><?php echo esc_html( $t['address'] ); ?></strong> <?php echo $addr; ?></p>
    </div>

    <p><?php echo $intro; ?></p>

    <table class="badges">
        <tr>
            <td>&#10003; <?php echo esc_html( $t['badge1'] ); ?></td>
            <td>&#10003; <?php echo esc_html( $t['badge2'] ); ?></td>
            <td>&#10003; <?php echo esc_html( $t['badge3'] ); ?></td>
        </tr>
    </table>

    <table class="items">
        <thead>
            <tr>
                <th style="width:8%;"><?php echo esc_html( $t['th_qty'] ); ?></th>
                <th style="width:40%;"><?php echo esc_html( $t['th_concept'] ); ?></th>
                <th style="width:18%;"><?php echo esc_html( $t['th_price'] ); ?></th>
                <th style="width:13%;"><?php echo esc_html( $t['th_units'] ); ?></th>
                <th style="width:21%;"><?php echo esc_html( $t['th_amount'] ); ?></th>
            </tr>
        </thead>
        <tbody>
            <?php echo $rows_html; // phpcs:ignore ?>
        </tbody>
    </table>

    <table class="totals">
        <tr>
            <td class="label"><?php echo esc_html( $t['discount'] ); ?></td>
            <td class="val orange"><strong><?php echo $discount; ?></strong></td>
        </tr>
        <tr>
            <td class="label"><?php echo esc_html( $t['sum'] ); ?></td>
            <td class="val orange"><strong><?php echo $sum_items; ?></strong></td>
        </tr>
        <tr>
            <td class="label"><?php echo esc_html( $t['vat'] ); ?></td>
            <td class="val">0,00 EUR</td>
        </tr>
        <tr class="total-row">
            <td class="label"><?php echo esc_html( $t['total'] ); ?></td>
            <td class="val"><?php echo $total; ?></td>
        </tr>
    </table>

    <div class="unit-line">
        <strong><?php echo esc_html( $t['unit_line'] ); ?></strong>
        &nbsp;&nbsp; <?php echo $unit_h_checked; ?> <?php echo esc_html( $t['unit_h'] ); ?>
        &nbsp;&nbsp; <?php echo $unit_hl_checked; ?> <?php echo esc_html( $t['unit_hl'] ); ?>
    </div>
    <p class="legal"><?php echo esc_html( $t['legal_unit'] ); ?></p>
    <p class="legal"><?php echo esc_html( $t['legal_vat'] ); ?></p>

    <div class="pay-title"><?php echo esc_html( $t['pay_title'] ); ?></div>

    <div class="pay-box">
        <span class="chk">&#9744;</span>
        <?php echo esc_html( $t['pay_full'] ); ?>
    </div>

    <div class="pay-box">
        <span class="chk">&#9744;</span>
        <?php echo esc_html( $t['pay_sepa'] ); ?>
    </div>

    <div class="closing"><?php echo esc_html( $t['closing'] ); ?></div>

    <?php echo $notes; // phpcs:ignore ?>

    <div class="client-box" style="margin-top:14px;">
        <strong class="green"><?php echo esc_html( $t['note_label'] ); ?></strong> <?php echo $note_text; // phpcs:ignore ?>
    </div>

    <table class="sign-table">
        <tr>
            <td><span class="sign-head"><?php echo esc_html( $t['sig_name'] ); ?></span></td>
            <td><span class="sign-head"><?php echo esc_html( $t['sig_email'] ); ?></span></td>
        </tr>
        <tr>
            <td><span class="sign-head"><?php echo esc_html( $t['sig_id'] ); ?></span></td>
            <td><span class="sign-head"><?php echo esc_html( $t['sig_schedule'] ); ?></span></td>
        </tr>
        <tr>
            <td><span class="sign-head"><?php echo esc_html( $t['sig_phone'] ); ?></span></td>
            <td><span class="sign-head"><?php echo esc_html( $t['sig_sign'] ); ?></span></td>
        </tr>
        <tr>
            <td><span class="sign-head"><?php echo esc_html( $t['sig_address'] ); ?></span></td>
            <td>&nbsp;</td>
        </tr>
    </table>

</body>
</html>
        <?php
        return ob_get_clean();
    }

    /**
     * Setzt Vor-/Nachname bzw. den freien Client-Namen zusammen.
     */
    private static function client_display( array $offer ) {
        if ( ! empty( $offer['client_name'] ) ) {
            return $offer['client_name'];
        }
        $name = trim( $offer['first_name'] . ' ' . $offer['last_name'] );
        return $name;
    }

    /**
     * Zahl ohne unnötige Nachkommastellen (z. B. 2 statt 2,00; 1,5 bleibt).
     */
    private static function num( $value ) {
        $value = (float) $value;
        if ( floor( $value ) === $value ) {
            return (string) (int) $value;
        }
        return rtrim( rtrim( number_format( $value, 2, ',', '.' ), '0' ), ',' );
    }

    /**
     * Lädt ein Bild als data:-URI (damit Dompdf es sicher einbettet).
     */
    private static function image_data_uri( $path, $mime ) {
        if ( ! file_exists( $path ) ) {
            return '';
        }
        $content = file_get_contents( $path );
        if ( false === $content ) {
            return '';
        }
        return 'data:' . $mime . ';base64,' . base64_encode( $content );
    }
}
