<?php
/**
 * Freefactu Invoice Template
 *
 * This template renders a Verifactu-compliant invoice with all required elements.
 * Used by the DOMPDF generator to create PDF invoices.
 *
 * IMPORTANT: This template uses inline <style> tags intentionally.
 * This is NOT a WordPress page - it generates standalone HTML for DOMPDF
 * to convert into a PDF document. DOMPDF requires inline CSS because:
 * 1. External stylesheets cannot be reliably loaded during PDF generation
 * 2. wp_enqueue_style() is not available in this context (no WordPress page rendering)
 * 3. The HTML is never displayed in a browser - only converted to PDF
 *
 * @see https://github.com/dompdf/dompdf/wiki/CSSCompatibility
 *
 * @var array $data Template data prepared by Generator implementation
 */

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

// Extract template data
$freefactu_source_data = isset( $data ) ? $data : ( isset( $freefactu_data ) ? $freefactu_data : array() );

$freefactu_invoice_number = isset( $freefactu_source_data['invoice_number'] ) ? $freefactu_source_data['invoice_number'] : '';
$freefactu_invoice_date   = isset( $freefactu_source_data['invoice_date'] ) ? $freefactu_source_data['invoice_date'] : '';
$freefactu_company        = isset( $freefactu_source_data['company'] ) ? $freefactu_source_data['company'] : array();
$freefactu_customer       = isset( $freefactu_source_data['customer'] ) ? $freefactu_source_data['customer'] : array();
$freefactu_items          = isset( $freefactu_source_data['items'] ) ? $freefactu_source_data['items'] : array();
$freefactu_totals         = isset( $freefactu_source_data['totals'] ) ? $freefactu_source_data['totals'] : array();
$freefactu_tax_breakdown  = isset( $freefactu_source_data['tax_breakdown'] ) ? $freefactu_source_data['tax_breakdown'] : array();
$freefactu_verifactu      = isset( $freefactu_source_data['verifactu'] ) ? $freefactu_source_data['verifactu'] : array();
$freefactu_order_id       = isset( $freefactu_source_data['order_id'] ) ? $freefactu_source_data['order_id'] : '';
$freefactu_order_date     = isset( $freefactu_source_data['order_date'] ) ? $freefactu_source_data['order_date'] : '';

// Rectificativa data
$freefactu_is_rectificativa      = isset( $freefactu_source_data['is_rectificativa'] ) && $freefactu_source_data['is_rectificativa'];
$freefactu_rectified_invoice     = isset( $freefactu_source_data['rectified_invoice'] ) ? $freefactu_source_data['rectified_invoice'] : array();
$freefactu_tipo_factura          = isset( $freefactu_source_data['tipo_factura'] ) ? $freefactu_source_data['tipo_factura'] : '';
$freefactu_metodo_rectificativa  = isset( $freefactu_source_data['metodo_rectificativa'] ) ? $freefactu_source_data['metodo_rectificativa'] : '';
$freefactu_motivo_rectificativa  = isset( $freefactu_source_data['motivo_rectificativa'] ) ? $freefactu_source_data['motivo_rectificativa'] : '';

// Helper function to format currency with sign for diferencias method
if ( ! function_exists( 'freefactu_format_amount' ) ) {
    function freefactu_format_amount( $amount, $show_sign = false ) {
        if ( $show_sign ) {
            $formatted = number_format( abs( $amount ), 2, ',', '.' );
            if ( $amount > 0 ) {
                return '+' . $formatted;
            } elseif ( $amount < 0 ) {
                return '-' . $formatted; // Explicitly show minus for negative with aligned formatting
            }
            return $formatted;
        }
        // Standard formatting (respects negative sign automatically)
        return number_format( $amount, 2, ',', '.' );
    }
}

// Tipos de rectificativa descriptions
$freefactu_tipos_rectificativa = array(
    'R1' => __( 'R1 – Error fundado en derecho y Art. 80.1, 80.2 y 80.6 LIVA', 'freefactu' ),
    'R2' => __( 'R2 – Art. 80.3 LIVA', 'freefactu' ),
    'R3' => __( 'R3 – Art. 80.4 LIVA', 'freefactu' ),
    'R4' => __( 'R4 – Art. 80 resto de causas LIVA', 'freefactu' ),
    'R5' => __( 'R5 – Rectificativa simplificada', 'freefactu' ),
);

// Show + sign only for diferencias method (I)
$freefactu_show_sign = ( $freefactu_is_rectificativa && $freefactu_metodo_rectificativa === 'I' );
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title><?php 
        if ( $freefactu_is_rectificativa ) {
            /* translators: %s: Invoice number */
            echo esc_html( sprintf( __( 'Factura Rectificativa %s', 'freefactu' ), $freefactu_invoice_number ) );
        } else {
            /* translators: %s: Invoice number */
            echo esc_html( sprintf( __( 'Factura %s', 'freefactu' ), $freefactu_invoice_number ) );
        }
    ?></title>
    <?php // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet -- DOMPDF PDF template: wp_enqueue_style() is unavailable in this context. See file docblock. ?>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: DejaVu Sans, sans-serif; font-size: 10pt; line-height: 1.4; color: #333; padding: 10mm 15mm; }
        
        /* Three-column top header: Company left, QR center, Invoice info right */
        .top-header { margin-bottom: 8mm; display: table; width: 100%; }
        .top-header > div { display: table-cell; vertical-align: top; }
        .top-header .company-info { width: 35%; text-align: left; }
        .top-header .verifactu-qr-section { width: 30%; text-align: center; padding: 0 2mm; }
        .top-header .invoice-info { width: 35%; text-align: right; }
        
        .verifactu-qr-header { font-size: 9pt; font-weight: bold; margin-bottom: 1mm; }
        .verifactu-qr-image { width: 30mm; height: 30mm; margin: 1mm auto; display: block; }
        .verifactu-qr-footer { font-size: 9pt; font-weight: bold; margin-top: 1mm; }
        
        /* Company info styles */
        .company-logo { margin-bottom: 3mm; }
        .company-logo .logo-image { max-width: 50mm; max-height: 30mm; height: auto; }
        .site-name { font-size: 9pt; color: #666; margin-bottom: 1mm; }
        .company-name { font-size: 9pt; font-weight: bold; color: #333; margin-bottom: 1mm; }
        .company-nif { font-size: 9pt; font-weight: bold; color: #333; margin-bottom: 1mm; }
        .company-address { font-size: 9pt; color: #666; }
        
        /* Invoice info styles */
        .invoice-title { font-size: 16pt; font-weight: bold; color: #2c3e50; margin-bottom: 2mm; }
        .invoice-number { font-size: 11pt; font-weight: bold; margin-bottom: 1mm; }
        .invoice-date { font-size: 9pt; color: #666; }
        
        /* Customer section - full width below header */
        .customer-section { margin-bottom: 8mm; padding: 5mm; background-color: #f8f9fa; border: 1px solid #e9ecef; }
        .customer-title { font-size: 10pt; font-weight: bold; color: #666; margin-bottom: 3mm; text-transform: uppercase; }
        .customer-name { font-size: 9pt; font-weight: bold; color: #555; margin-bottom: 1mm; }
        .customer-nif { font-size: 9pt; font-weight: bold; color: #555; margin-bottom: 2mm; }
        .customer-details { font-size: 9pt; color: #555; }
        .clearfix::after { content: ""; display: table; clear: both; }
        .items-table { width: 100%; border-collapse: collapse; margin: 8mm 0; }
        .items-table th { background-color: #2c3e50; color: white; padding: 3mm 2mm; text-align: left; font-size: 9pt; font-weight: bold; }
        .items-table th.text-right { text-align: right; }
        .items-table td { padding: 2.5mm 2mm; border-bottom: 1px solid #e9ecef; font-size: 9pt; }
        .items-table td.text-right { text-align: right; }
        .items-table tbody tr:nth-child(even) { background-color: #f8f9fa; }
        .tax-section { margin: 8mm 0; width: 60%; margin-left: auto; }
        .tax-title { font-size: 10pt; font-weight: bold; margin-bottom: 3mm; text-align: left; }
        .tax-table { width: 100%; border-collapse: collapse; }
        .tax-table th, .tax-table td { padding: 2mm; font-size: 9pt; border: 1px solid #e9ecef; }
        .tax-table th { background-color: #f8f9fa; text-align: left; font-weight: bold; }
        .tax-table td.text-right { text-align: right; }
        .totals-section { margin-top: 5mm; }
        .totals-table { width: 40%; margin-left: auto; border-collapse: collapse; }
        .totals-table td { padding: 2mm 3mm; font-size: 10pt; }
        .totals-table td.label { text-align: right; color: #666; }
        .totals-table td.value { text-align: right; font-weight: bold; }
        .totals-table tr.total-row td { font-size: 12pt; border-top: 2px solid #2c3e50; padding-top: 3mm; }
        .totals-table tr.total-row td.value { color: #2c3e50; }
        .invoice-footer { margin-top: 15mm; padding-top: 5mm; border-top: 1px solid #e9ecef; font-size: 8pt; color: #999; text-align: center; }
    </style>
</head>
<body>
    <!-- Top Header: Company (left) + QR (center) + Invoice Info (right) -->
    <div class="top-header">
        <!-- Company info (left) -->
        <div class="company-info">
            <?php if ( ! empty( $freefactu_company['logo'] ) ) : ?>
                <div class="company-logo">
                    <img src="<?php echo esc_url( $freefactu_company['logo'] ); ?>" alt="<?php echo esc_attr( $freefactu_company['name'] ?? '' ); ?>" class="logo-image" />
                </div>
            <?php endif; ?>
            <?php if ( ! empty( $freefactu_company['site_name'] ) && $freefactu_company['site_name'] !== ( $freefactu_company['name'] ?? '' ) ) : ?>
                <div class="site-name"><?php echo esc_html( $freefactu_company['site_name'] ); ?></div>
            <?php endif; ?>
            <div class="company-name"><?php echo esc_html( $freefactu_company['name'] ?? '' ); ?></div>
            <div class="company-nif">NIF: <?php echo esc_html( $freefactu_company['nif'] ?? '' ); ?></div>
            <?php if ( ! empty( $freefactu_company['address'] ) ) : ?>
                <div class="company-address"><?php echo esc_html( $freefactu_company['address'] ); ?></div>
            <?php endif; ?>
            <?php if ( ! empty( $freefactu_company['email'] ) ) : ?>
                <div class="company-address"><?php echo esc_html( $freefactu_company['email'] ); ?></div>
            <?php endif; ?>
            <?php if ( ! empty( $freefactu_company['phone'] ) ) : ?>
                <div class="company-address"><?php echo esc_html( $freefactu_company['phone'] ); ?></div>
            <?php endif; ?>
        </div>

        <!-- QR code (center) -->
        <?php if ( ! empty( $freefactu_verifactu['csv'] ) ) : ?>
        <div class="verifactu-qr-section">
            <div class="verifactu-qr-header">QR tributario:</div>
            <?php if ( ! empty( $freefactu_verifactu['qr_image'] ) ) : ?>
                <img src="<?php echo esc_attr( $freefactu_verifactu['qr_image'] ); ?>" alt="Verifactu QR" class="verifactu-qr-image" />
            <?php elseif ( ! empty( $freefactu_verifactu['qr_url'] ) ) : ?>
                <div style="font-size: 8pt; color: #666;">
                    <a href="<?php echo esc_url( $freefactu_verifactu['qr_url'] ); ?>" target="_blank"><?php esc_html_e( 'Verificar', 'freefactu' ); ?></a>
                </div>
            <?php endif; ?>
            <div class="verifactu-qr-footer">VERI*FACTU</div>
        </div>
        <?php else : ?>
        <div class="verifactu-qr-section"></div>
        <?php endif; ?>

        <!-- Invoice info (right) -->
        <div class="invoice-info">
            <?php if ( $freefactu_is_rectificativa ) : ?>
                <div class="invoice-title" style="color: #e67e22; font-size: 14pt;"><?php esc_html_e( 'FACTURA RECTIFICATIVA', 'freefactu' ); ?></div>
            <?php else : ?>
                <div class="invoice-title"><?php esc_html_e( 'FACTURA', 'freefactu' ); ?></div>
            <?php endif; ?>
            <div class="invoice-number">
                <?php
                /* translators: %s: Invoice number */
                echo esc_html( sprintf( __( 'Nº: %s', 'freefactu' ), $freefactu_invoice_number ) );
                ?>
            </div>
            <div class="invoice-date">
                <?php
                /* translators: %s: Invoice date */
                echo esc_html( sprintf( __( 'Fecha factura: %s', 'freefactu' ), $freefactu_invoice_date ) );
                ?>
            </div>
            <?php if ( $freefactu_order_id ) : ?>
                <div class="invoice-date">
                    <?php
                    /* translators: %s: Order ID */
                    echo esc_html( sprintf( __( 'Pedido: #%s', 'freefactu' ), $freefactu_order_id ) );
                    ?>
                </div>
            <?php endif; ?>
            <?php if ( $freefactu_is_rectificativa ) : ?>
                <?php 
                $freefactu_rectified_number = isset( $freefactu_rectified_invoice['invoice_number'] ) ? $freefactu_rectified_invoice['invoice_number'] : '';
                $freefactu_rectified_date = isset( $freefactu_rectified_invoice['invoice_date'] ) ? $freefactu_rectified_invoice['invoice_date'] : '';
                if ( ! empty( $freefactu_rectified_date ) ) {
                    $freefactu_timestamp = is_numeric( $freefactu_rectified_date ) ? $freefactu_rectified_date : strtotime( $freefactu_rectified_date );
                    $freefactu_rectified_date = date_i18n( get_option( 'date_format' ), $freefactu_timestamp );
                }
                ?>
                <div class="rectified-invoice" style="margin-top: 2mm; padding: 2mm; background-color: #fdf2e4; border: 1px solid #e67e22; border-radius: 2mm; font-size: 8pt; line-height: 1.3; text-align: left;">
                    <?php if ( ! empty( $freefactu_rectified_number ) ) : ?>
                        <div style="margin-bottom: 1mm;">
                            <strong><?php esc_html_e( 'Rectifica:', 'freefactu' ); ?></strong> <?php echo esc_html( $freefactu_rectified_number ); ?>
                            <?php if ( ! empty( $freefactu_rectified_date ) ) : ?>
                                <span style="color: #666;">(<?php echo esc_html( $freefactu_rectified_date ); ?>)</span>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                    <?php if ( ! empty( $freefactu_tipo_factura ) && isset( $freefactu_tipos_rectificativa[ $freefactu_tipo_factura ] ) ) : ?>
                        <div style="margin-bottom: 1mm; color: #555;"><?php echo esc_html( $freefactu_tipos_rectificativa[ $freefactu_tipo_factura ] ); ?></div>
                    <?php endif; ?>
                    <?php if ( $freefactu_metodo_rectificativa === 'S' ) : ?>
                        <div style="font-style: italic; color: #666;"><?php esc_html_e( 'Método: S - Sustitución. Los importes reflejados sustituyen a los indicados en la factura original.', 'freefactu' ); ?></div>
                    <?php elseif ( $freefactu_metodo_rectificativa === 'I' ) : ?>
                        <div style="font-style: italic; color: #666;"><?php esc_html_e( 'Método: I - Diferencias. Los importes reflejados incrementan o reducen los importes originales.', 'freefactu' ); ?></div>
                    <?php endif; ?>
                    <?php if ( ! empty( $freefactu_motivo_rectificativa ) ) : ?>
                        <div style="margin-top: 1mm; color: #333;"><strong><?php esc_html_e( 'Motivo:', 'freefactu' ); ?></strong> <?php echo esc_html( $freefactu_motivo_rectificativa ); ?></div>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Customer Information (full width) -->
    <div class="customer-section">
        <div class="customer-title"><?php esc_html_e( 'Datos del Cliente', 'freefactu' ); ?></div>
        <div class="customer-name">
            <?php 
            $freefactu_customer_name = trim( $freefactu_customer['name'] ?? '' );
            if ( ! empty( $freefactu_customer['company'] ) ) {
                $freefactu_customer_name .= ( $freefactu_customer_name ? ' - ' : '' ) . $freefactu_customer['company'];
            }
            echo esc_html( $freefactu_customer_name ?: __( 'Cliente', 'freefactu' ) );
            ?>
        </div>
        <?php if ( ! empty( $freefactu_customer['nif'] ) ) : ?>
            <div class="customer-nif">NIF/DNI: <?php echo esc_html( $freefactu_customer['nif'] ); ?></div>
        <?php endif; ?>
        <div class="customer-details">
            <?php if ( ! empty( $freefactu_customer['address_1'] ) ) : ?>
                <?php echo esc_html( $freefactu_customer['address_1'] ); ?><br>
            <?php endif; ?>
            <?php if ( ! empty( $freefactu_customer['address_2'] ) ) : ?>
                <?php echo esc_html( $freefactu_customer['address_2'] ); ?><br>
            <?php endif; ?>
            <?php 
            $freefactu_location_parts = array_filter( array(
                $freefactu_customer['postcode'] ?? '',
                $freefactu_customer['city'] ?? '',
                $freefactu_customer['country'] ?? ''
            ) );
            if ( ! empty( $freefactu_location_parts ) ) : ?>
                <?php echo esc_html( implode( ', ', $freefactu_location_parts ) ); ?><br>
            <?php endif; ?>
            <?php if ( ! empty( $freefactu_customer['phone'] ) ) : ?>
                <?php esc_html_e( 'Tel:', 'freefactu' ); ?> <?php echo esc_html( $freefactu_customer['phone'] ); ?><br>
            <?php endif; ?>
            <?php if ( ! empty( $freefactu_customer['email'] ) ) : ?>
                <?php echo esc_html( $freefactu_customer['email'] ); ?>
            <?php endif; ?>
        </div>
    </div>

    <!-- Order Line Items -->
    <table class="items-table">
        <thead>
            <tr>
                <th style="width: 45%;"><?php esc_html_e( 'Descripción', 'freefactu' ); ?></th>
                <th class="text-right" style="width: 12%;"><?php esc_html_e( 'Cantidad', 'freefactu' ); ?></th>
                <th class="text-right" style="width: 15%;"><?php esc_html_e( 'Precio Unit.', 'freefactu' ); ?></th>
                <th class="text-right" style="width: 10%;"><?php esc_html_e( 'IVA %', 'freefactu' ); ?></th>
                <th class="text-right" style="width: 18%;"><?php esc_html_e( 'Total', 'freefactu' ); ?></th>
            </tr>
        </thead>
        <tbody>
            <?php if ( ! empty( $freefactu_items ) ) : ?>
                <?php foreach ( $freefactu_items as $freefactu_item ) : ?>
                    <tr>
                        <td><?php echo esc_html( $freefactu_item['name'] ?? '' ); ?></td>
                        <td class="text-right"><?php echo esc_html( $freefactu_item['quantity'] ?? 1 ); ?></td>
                        <td class="text-right"><?php echo esc_html( freefactu_format_amount( $freefactu_item['unit_price'] ?? 0, $freefactu_show_sign ) ); ?> €</td>
                        <td class="text-right"><?php echo esc_html( $freefactu_item['tax_rate'] ?? 0 ); ?>%</td>
                        <td class="text-right"><?php echo esc_html( freefactu_format_amount( $freefactu_item['total'] ?? 0, $freefactu_show_sign ) ); ?> €</td>
                    </tr>
                <?php endforeach; ?>
            <?php else : ?>
                <tr>
                    <td colspan="5" style="text-align: center; color: #999;"><?php esc_html_e( 'No hay artículos', 'freefactu' ); ?></td>
                </tr>
            <?php endif; ?>
        </tbody>
    </table>

    <!-- Tax Breakdown -->
    <?php if ( ! empty( $freefactu_tax_breakdown ) ) : ?>
    <div class="tax-section">
        <div class="tax-title"><?php esc_html_e( 'Desglose de Impuestos', 'freefactu' ); ?></div>
        <table class="tax-table">
            <thead>
                <tr>
                    <th><?php esc_html_e( 'Tipo IVA', 'freefactu' ); ?></th>
                    <th class="text-right"><?php esc_html_e( 'Base Imponible', 'freefactu' ); ?></th>
                    <th class="text-right"><?php esc_html_e( 'Cuota IVA', 'freefactu' ); ?></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ( $freefactu_tax_breakdown as $freefactu_tax ) : ?>
                    <tr>
                        <td><?php 
                            $freefactu_tax_rate = $freefactu_tax['rate'] ?? 0;
                            $freefactu_tax_name = $freefactu_tax['name'] ?? '';
                            
                            // Format rate for display/check (remove trailing zeros if integer)
                            $freefactu_display_rate = (float) $freefactu_tax_rate;
                            if ( floor( $freefactu_display_rate ) == $freefactu_display_rate ) {
                                $freefactu_display_rate = (int) $freefactu_display_rate;
                            }
                            
                            if ( ! empty( $freefactu_tax_name ) ) {
                                // Check if name already contains the rate (e.g. "IVA 21%" or "IVA (21%)")
                                if ( strpos( $freefactu_tax_name, $freefactu_display_rate . '%' ) !== false ) {
                                    echo esc_html( $freefactu_tax_name );
                                } else {
                                    echo esc_html( $freefactu_tax_name . ' (' . $freefactu_display_rate . '%)' );
                                }
                            } else {
                                echo esc_html( $freefactu_display_rate . '%' );
                            }
                        ?></td>
                        <td class="text-right"><?php echo esc_html( freefactu_format_amount( $freefactu_tax['base'] ?? 0, $freefactu_show_sign ) ); ?> €</td>
                        <td class="text-right"><?php echo esc_html( freefactu_format_amount( $freefactu_tax['amount'] ?? 0, $freefactu_show_sign ) ); ?> €</td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>

    <!-- Totals -->
    <div class="totals-section">
        <table class="totals-table">
            <tr>
                <td class="label"><?php esc_html_e( 'Subtotal:', 'freefactu' ); ?></td>
                <td class="value"><?php echo esc_html( freefactu_format_amount( $freefactu_totals['subtotal'] ?? 0, $freefactu_show_sign ) ); ?> €</td>
            </tr>
            <tr>
                <td class="label"><?php esc_html_e( 'IVA:', 'freefactu' ); ?></td>
                <td class="value"><?php echo esc_html( freefactu_format_amount( $freefactu_totals['tax_total'] ?? 0, $freefactu_show_sign ) ); ?> €</td>
            </tr>
            <tr class="total-row">
                <td class="label"><?php esc_html_e( 'TOTAL:', 'freefactu' ); ?></td>
                <td class="value"><?php echo esc_html( freefactu_format_amount( $freefactu_totals['total'] ?? 0, $freefactu_show_sign ) ); ?> €</td>
            </tr>
        </table>
    </div>

    <!-- Footer -->
    <div class="invoice-footer">
        <?php
        /* translators: %s: Company name */
        echo esc_html( sprintf( __( 'Factura generada por Freefactu - %s', 'freefactu' ), $freefactu_company['name'] ?? '' ) );
        ?>
    </div>
</body>
</html>
