<?php
/**
 * Default invoice template for Factur-X invoices.
 *
 * All mandatory French legal mentions are included.
 * This template is rendered to HTML, then converted to PDF via DOMPDF.
 *
 * Available variables:
 * @var array $invoice {
 *     @type string $invoice_number
 *     @type string $invoice_date
 *     @type string $delivery_date
 *     @type array  $seller
 *     @type array  $buyer
 *     @type array  $lines
 *     @type array  $tax_totals
 *     @type float  $total_ht
 *     @type float  $total_tax
 *     @type float  $total_ttc
 *     @type string $currency
 *     @type string $payment_method
 *     @type string $order_number
 * }
 *
 * @package FacturX_For_WooCommerce
 */

defined( 'ABSPATH' ) || exit;

$seller  = $invoice['seller'];
$buyer   = $invoice['buyer'];
$lines   = $invoice['lines'];
$cur     = $invoice['currency'];

$format_amount = function ( float $amount ) use ( $cur ): string {
    return number_format( $amount, 2, ',', ' ' ) . ' ' . $cur;
};

$format_rate = function ( float $rate ): string {
    return number_format( $rate, 1, ',', '' ) . '%';
};
?>
<!DOCTYPE html>
<html lang="<?php echo esc_attr( get_bloginfo( 'language' ) ); ?>">
<head>
<meta charset="UTF-8">
<style>
    @page { margin: 20mm 15mm 25mm 15mm; }
    body { font-family: 'DejaVu Sans', sans-serif; font-size: 9pt; color: #1a1a1a; line-height: 1.4; }
    h1 { font-size: 18pt; margin: 0 0 5mm; color: #2563eb; }
    .header { display: flex; margin-bottom: 8mm; }
    .header-left { width: 50%; }
    .header-right { width: 50%; text-align: right; }
    .meta-table { width: 100%; margin-bottom: 6mm; }
    .meta-table td { padding: 2mm 3mm; vertical-align: top; }
    .meta-label { font-weight: bold; color: #64748b; font-size: 7pt; text-transform: uppercase; letter-spacing: 0.5px; }
    .party-box { border: 1px solid #e2e8f0; border-radius: 3mm; padding: 4mm; margin-bottom: 4mm; }
    .party-title { font-size: 7pt; text-transform: uppercase; color: #64748b; margin: 0 0 2mm; letter-spacing: 0.5px; }
    .party-name { font-weight: bold; font-size: 10pt; margin: 0 0 1mm; }
    table.lines { width: 100%; border-collapse: collapse; margin-bottom: 6mm; }
    table.lines thead th { background: #f1f5f9; border-bottom: 2px solid #cbd5e1; padding: 2.5mm 3mm; text-align: left; font-size: 7pt; text-transform: uppercase; color: #64748b; letter-spacing: 0.5px; }
    table.lines tbody td { padding: 2mm 3mm; border-bottom: 1px solid #e2e8f0; vertical-align: top; }
    table.lines tbody tr:last-child td { border-bottom: 2px solid #cbd5e1; }
    .text-right { text-align: right; }
    .text-center { text-align: center; }
    .totals { width: 55%; margin-left: auto; margin-bottom: 6mm; }
    .totals td { padding: 1.5mm 3mm; }
    .totals .total-row td { border-top: 2px solid #1a1a1a; font-weight: bold; font-size: 11pt; padding-top: 2mm; }
    .legal { font-size: 7pt; color: #64748b; border-top: 1px solid #e2e8f0; padding-top: 3mm; line-height: 1.6; }
    .legal p { margin: 0 0 1mm; }
    .facturx-badge { display: inline-block; background: #dbeafe; color: #1d4ed8; font-size: 7pt; padding: 1mm 2mm; border-radius: 1mm; font-weight: bold; }
</style>
</head>
<body>

<!-- Header -->
<table style="width: 100%; margin-bottom: 6mm;">
<tr>
<td style="width: 50%; vertical-align: top;">
    <?php if ( ! empty( $seller['logo_path'] ) ) : ?>
    <img src="<?php echo esc_attr( $seller['logo_path'] ); ?>" style="max-height: 22mm; max-width: 60mm; display: block; margin-bottom: 3mm;" alt="">
    <?php endif; ?>
    <h1><?php esc_html_e( 'INVOICE', 'gofactox-e-invoicing-for-woocommerce' ); ?></h1>
    <span class="facturx-badge">Factur-X</span>
</td>
<td style="width: 50%; text-align: right; vertical-align: top;">
    <table style="margin-left: auto;">
        <tr><td class="meta-label"><?php esc_html_e( 'Invoice No.', 'gofactox-e-invoicing-for-woocommerce' ); ?></td><td style="padding-left: 3mm; font-weight: bold;"><?php echo esc_html( $invoice['invoice_number'] ); ?></td></tr>
        <tr><td class="meta-label"><?php esc_html_e( 'Date', 'gofactox-e-invoicing-for-woocommerce' ); ?></td><td style="padding-left: 3mm;"><?php echo esc_html( date_i18n( 'd/m/Y', strtotime( $invoice['invoice_date'] ) ) ); ?></td></tr>
        <?php if ( ! empty( $invoice['delivery_date'] ) ) : ?>
        <tr><td class="meta-label"><?php esc_html_e( 'Delivery Date', 'gofactox-e-invoicing-for-woocommerce' ); ?></td><td style="padding-left: 3mm;"><?php echo esc_html( date_i18n( 'd/m/Y', strtotime( $invoice['delivery_date'] ) ) ); ?></td></tr>
        <?php endif; ?>
        <tr><td class="meta-label"><?php esc_html_e( 'Order', 'gofactox-e-invoicing-for-woocommerce' ); ?></td><td style="padding-left: 3mm;">#<?php echo esc_html( $invoice['order_number'] ); ?></td></tr>
        <?php if ( ! empty( $invoice['buyer_reference'] ) ) : ?>
        <tr><td class="meta-label"><?php esc_html_e( 'PO No.', 'gofactox-e-invoicing-for-woocommerce' ); ?></td><td style="padding-left: 3mm;"><?php echo esc_html( $invoice['buyer_reference'] ); ?></td></tr>
        <?php endif; ?>
        <?php if ( ! empty( $invoice['billing_period']['start'] ) && ! empty( $invoice['billing_period']['end'] ) ) : ?>
        <tr><td class="meta-label"><?php esc_html_e( 'Period', 'gofactox-e-invoicing-for-woocommerce' ); ?></td><td style="padding-left: 3mm;"><?php
            printf(
                /* translators: 1: period start, 2: period end */
                esc_html__( '%1$s — %2$s', 'gofactox-e-invoicing-for-woocommerce' ),
                esc_html( date_i18n( 'd/m/Y', strtotime( $invoice['billing_period']['start'] ) ) ),
                esc_html( date_i18n( 'd/m/Y', strtotime( $invoice['billing_period']['end'] ) ) )
            );
        ?></td></tr>
        <?php endif; ?>
    </table>
</td>
</tr>
</table>

<!-- Seller & Buyer -->
<table style="width: 100%; margin-bottom: 6mm;">
<tr>
<td style="width: 48%; vertical-align: top;">
    <div class="party-box">
        <p class="party-title"><?php esc_html_e( 'From', 'gofactox-e-invoicing-for-woocommerce' ); ?></p>
        <p class="party-name"><?php echo esc_html( $seller['company_name'] ); ?></p>
        <p><?php echo esc_html( $seller['address_line1'] ); ?></p>
        <?php if ( $seller['address_line2'] ) : ?><p><?php echo esc_html( $seller['address_line2'] ); ?></p><?php endif; ?>
        <p><?php echo esc_html( $seller['postal_code'] . ' ' . $seller['city'] ); ?></p>
        <?php if ( $seller['siret'] ) : ?><p>SIRET : <?php echo esc_html( $seller['siret'] ); ?></p><?php endif; ?>
        <?php if ( $seller['vat_number'] ) : ?><p><?php esc_html_e( 'VAT', 'gofactox-e-invoicing-for-woocommerce' ); ?> : <?php echo esc_html( $seller['vat_number'] ); ?></p><?php endif; ?>
    </div>
</td>
<td style="width: 4%;"></td>
<td style="width: 48%; vertical-align: top;">
    <div class="party-box">
        <p class="party-title"><?php esc_html_e( 'Bill To', 'gofactox-e-invoicing-for-woocommerce' ); ?></p>
        <?php if ( $buyer['company'] ) : ?>
            <p class="party-name"><?php echo esc_html( $buyer['company'] ); ?></p>
            <p><?php echo esc_html( $buyer['name'] ); ?></p>
        <?php else : ?>
            <p class="party-name"><?php echo esc_html( $buyer['name'] ); ?></p>
        <?php endif; ?>
        <p><?php echo esc_html( $buyer['address_line1'] ); ?></p>
        <?php if ( $buyer['address_line2'] ) : ?><p><?php echo esc_html( $buyer['address_line2'] ); ?></p><?php endif; ?>
        <p><?php echo esc_html( $buyer['postal_code'] . ' ' . $buyer['city'] ); ?></p>
        <?php if ( ! empty( $buyer['siret'] ) ) : ?><p>SIRET : <?php echo esc_html( $buyer['siret'] ); ?></p><?php endif; ?>
        <?php if ( ! empty( $buyer['vat_number'] ) ) : ?><p><?php esc_html_e( 'VAT', 'gofactox-e-invoicing-for-woocommerce' ); ?> : <?php echo esc_html( $buyer['vat_number'] ); ?></p><?php endif; ?>
    </div>
    <?php if ( ! empty( $invoice['delivery_address'] ) ) : $ship = $invoice['delivery_address']; ?>
    <div class="party-box" style="margin-top: 3mm;">
        <p class="party-title"><?php esc_html_e( 'Deliver To', 'gofactox-e-invoicing-for-woocommerce' ); ?></p>
        <?php if ( ! empty( $ship['name'] ) ) : ?><p class="party-name"><?php echo esc_html( $ship['name'] ); ?></p><?php endif; ?>
        <p><?php echo esc_html( $ship['address_line1'] ); ?></p>
        <?php if ( ! empty( $ship['address_line2'] ) ) : ?><p><?php echo esc_html( $ship['address_line2'] ); ?></p><?php endif; ?>
        <p><?php echo esc_html( trim( $ship['postal_code'] . ' ' . $ship['city'] ) ); ?></p>
    </div>
    <?php endif; ?>
</td>
</tr>
</table>

<!-- Line Items -->
<table class="lines">
<thead>
    <tr>
        <th style="width: 5%;">#</th>
        <th style="width: 35%;"><?php esc_html_e( 'Description', 'gofactox-e-invoicing-for-woocommerce' ); ?></th>
        <th class="text-center" style="width: 8%;"><?php esc_html_e( 'Qty', 'gofactox-e-invoicing-for-woocommerce' ); ?></th>
        <th class="text-right" style="width: 15%;"><?php esc_html_e( 'Unit Price', 'gofactox-e-invoicing-for-woocommerce' ); ?></th>
        <th class="text-center" style="width: 10%;"><?php esc_html_e( 'VAT', 'gofactox-e-invoicing-for-woocommerce' ); ?></th>
        <th class="text-right" style="width: 15%;"><?php esc_html_e( 'Total excl. VAT', 'gofactox-e-invoicing-for-woocommerce' ); ?></th>
    </tr>
</thead>
<tbody>
    <?php foreach ( $lines as $i => $line ) : ?>
    <tr>
        <td><?php echo esc_html( $i + 1 ); ?></td>
        <td>
            <?php echo esc_html( $line['name'] ); ?>
            <?php if ( ! empty( $line['sku'] ) ) : ?>
                <br><span style="color: #94a3b8; font-size: 7pt;">SKU: <?php echo esc_html( $line['sku'] ); ?></span>
            <?php endif; ?>
        </td>
        <td class="text-center"><?php echo esc_html( $line['quantity'] ); ?></td>
        <td class="text-right"><?php echo esc_html( $format_amount( $line['unit_price'] ) ); ?></td>
        <td class="text-center"><?php echo esc_html( $format_rate( $line['tax_rate'] ) ); ?></td>
        <td class="text-right"><?php echo esc_html( $format_amount( $line['total_ht'] ) ); ?></td>
    </tr>
    <?php endforeach; ?>
</tbody>
</table>

<!-- Totals -->
<table class="totals">
    <?php
    $allowance_total = 0.0;
    foreach ( ($invoice['allowances'] ?? []) as $a ) {
        $allowance_total += (float) ( $a['amount'] ?? 0 );
    }
    $subtotal_before_allowance = (float) $invoice['total_ht'] + $allowance_total;
    ?>
    <tr>
        <td><?php esc_html_e( 'Subtotal excl. VAT', 'gofactox-e-invoicing-for-woocommerce' ); ?></td>
        <td class="text-right"><?php echo esc_html( $format_amount( $subtotal_before_allowance ) ); ?></td>
    </tr>
    <?php foreach ( ( $invoice['allowances'] ?? [] ) as $allowance ) : ?>
    <tr>
        <td><?php echo esc_html( $allowance['reason'] ?? __( 'Discount', 'gofactox-e-invoicing-for-woocommerce' ) ); ?></td>
        <td class="text-right">-<?php echo esc_html( $format_amount( (float) $allowance['amount'] ) ); ?></td>
    </tr>
    <?php endforeach; ?>
    <?php if ( $allowance_total > 0 ) : ?>
    <tr>
        <td><strong><?php esc_html_e( 'Net excl. VAT', 'gofactox-e-invoicing-for-woocommerce' ); ?></strong></td>
        <td class="text-right"><strong><?php echo esc_html( $format_amount( (float) $invoice['total_ht'] ) ); ?></strong></td>
    </tr>
    <?php endif; ?>
    <?php foreach ( $invoice['tax_totals'] as $tax ) : ?>
    <tr>
        <td><?php
            /* translators: %s: VAT rate percentage (e.g., "20,0%") */
            echo esc_html( sprintf( __( 'VAT %s', 'gofactox-e-invoicing-for-woocommerce' ), $format_rate( $tax['rate'] ) ) );
        ?></td>
        <td class="text-right"><?php echo esc_html( $format_amount( $tax['amount'] ) ); ?></td>
    </tr>
    <?php endforeach; ?>
    <tr class="total-row">
        <td><?php esc_html_e( 'Total incl. VAT', 'gofactox-e-invoicing-for-woocommerce' ); ?></td>
        <td class="text-right"><?php echo esc_html( $format_amount( $invoice['total_ttc'] ) ); ?></td>
    </tr>
</table>

<!-- Payment -->
<?php
$terms = GOFACTOX_Payment_Terms::resolve( $invoice['invoice_date'] );
?>
<table style="width:100%; margin-bottom:6mm;">
<tr>
<td style="width: 50%; vertical-align: top; padding-right:4mm;">
    <?php if ( ! empty( $invoice['payment_method'] ) ) : ?>
    <p style="margin:0 0 2mm;">
        <strong><?php esc_html_e( 'Payment method:', 'gofactox-e-invoicing-for-woocommerce' ); ?></strong>
        <?php echo esc_html( $invoice['payment_method'] ); ?>
    </p>
    <?php endif; ?>
    <p style="margin:0 0 2mm;">
        <strong><?php esc_html_e( 'Payment terms:', 'gofactox-e-invoicing-for-woocommerce' ); ?></strong>
        <?php echo esc_html( $terms['label'] ); ?>
    </p>
    <p style="margin:0 0 2mm;">
        <strong><?php esc_html_e( 'Due date:', 'gofactox-e-invoicing-for-woocommerce' ); ?></strong>
        <?php echo esc_html( $terms['due_date']->format( 'd/m/Y' ) ); ?>
    </p>
</td>
<td style="width: 50%; vertical-align: top;">
    <?php
    if ( ! empty( $seller['iban'] ) ) :
        $qr_enabled = get_option( 'gofactox_sepa_qr', 'yes' ) === 'yes';
        $qr_path    = ( $qr_enabled && class_exists( 'GOFACTOX_Sepa_QR' ) )
            ? GOFACTOX_Sepa_QR::generate_png( $invoice )
            : '';
    ?>
    <table style="width:100%; border:1px solid #e2e8f0; border-radius:2mm; background:#f8fafc;">
        <tr>
            <td style="padding:3mm; vertical-align:top;">
                <p class="party-title" style="margin:0 0 1mm;"><?php esc_html_e( 'Wire transfer details', 'gofactox-e-invoicing-for-woocommerce' ); ?></p>
                <?php if ( $seller['bank_name'] ) : ?>
                <p style="margin:0;"><?php echo esc_html( $seller['bank_name'] ); ?></p>
                <?php endif; ?>
                <p style="margin:0; font-family:'DejaVu Sans Mono', monospace; font-size:8.5pt;">IBAN: <?php echo esc_html( $seller['iban'] ); ?></p>
                <?php if ( $seller['bic'] ) : ?>
                <p style="margin:0; font-family:'DejaVu Sans Mono', monospace; font-size:8.5pt;">BIC: <?php echo esc_html( $seller['bic'] ); ?></p>
                <?php endif; ?>
                <?php if ( $qr_path ) : ?>
                <p style="margin:2mm 0 0; font-size:7pt; color:#64748b;"><?php esc_html_e( 'Scan with your SEPA banking app to pre-fill the wire transfer.', 'gofactox-e-invoicing-for-woocommerce' ); ?></p>
                <?php endif; ?>
            </td>
            <?php if ( $qr_path ) : ?>
            <td style="width:22mm; padding:2mm; vertical-align:middle; text-align:right;">
                <img src="<?php echo esc_attr( $qr_path ); ?>" style="width:22mm; height:22mm; display:block;" alt="SEPA QR">
            </td>
            <?php endif; ?>
        </tr>
    </table>
    <?php endif; ?>
</td>
</tr>
</table>

<!-- Legal Mentions (mandatory in France) -->
<div class="legal">
    <?php if ( $seller['vat_exempt'] ) : ?>
        <p><strong><?php esc_html_e( 'VAT not applicable, article 293 B of the French General Tax Code.', 'gofactox-e-invoicing-for-woocommerce' ); ?></strong></p>
    <?php endif; ?>

    <?php if ( ! empty( $invoice['operation_category']['label'] ) ) : ?>
        <p><?php echo esc_html( sprintf(
            /* translators: %s: operation category (goods / services / mixed) */
            __( 'Operation category: %s', 'gofactox-e-invoicing-for-woocommerce' ),
            $invoice['operation_category']['label']
        ) ); ?></p>
    <?php endif; ?>

    <?php if ( ! empty( $seller['vat_on_debits'] ) ) : ?>
        <p><?php esc_html_e( 'VAT paid on the basis of debits (option for payment of VAT on debits).', 'gofactox-e-invoicing-for-woocommerce' ); ?></p>
    <?php endif; ?>

    <?php
    $late_rate = get_option( 'gofactox_late_payment_rate', '' );
    if ( $late_rate ) :
        // Normalize to always display "X %" regardless of what the merchant typed.
        $late_rate_display = rtrim( (string) $late_rate, "% \t" ) . ' %';
    ?>
        <p><?php echo esc_html( sprintf(
            /* translators: %s: late payment interest rate with percentage symbol, e.g. "10.5 %%" */
            __( 'Late payment penalties: interest rate of %s per year, applied from the day after the due date.', 'gofactox-e-invoicing-for-woocommerce' ),
            $late_rate_display
        ) ); ?></p>
    <?php else : ?>
        <p><?php esc_html_e( 'Late payment penalties are due at the ECB reference rate increased by 10 percentage points.', 'gofactox-e-invoicing-for-woocommerce' ); ?></p>
    <?php endif; ?>

    <p><?php esc_html_e( 'Fixed indemnity for recovery costs in case of late payment: 40.00 euros.', 'gofactox-e-invoicing-for-woocommerce' ); ?></p>

    <p><?php esc_html_e( 'No discount for early payment.', 'gofactox-e-invoicing-for-woocommerce' ); ?></p>

    <?php if ( $seller['company_name'] && $seller['legal_form'] ) : ?>
    <p style="margin-top: 2mm;">
        <?php
        $parts   = array();
        $parts[] = $seller['company_name'];
        if ( $seller['share_capital'] ) {
            $capital = $seller['share_capital'];
            // If the merchant entered a plain number without currency, append the default (EUR).
            if ( preg_match( '/^[\d\s.,]+$/', $capital ) ) {
                $capital .= ' €';
            }
            /* translators: %1$s: legal form (e.g., SASU), %2$s: share capital amount with currency */
            $parts[] = sprintf( __( '%1$s with share capital of %2$s', 'gofactox-e-invoicing-for-woocommerce' ), $seller['legal_form'], $capital );
        } else {
            $parts[] = $seller['legal_form'];
        }
        if ( $seller['rcs_city'] ) {
            $siren   = $seller['siret'] ? substr( $seller['siret'], 0, 9 ) : '';
            $parts[] = 'RCS ' . $seller['rcs_city'] . ( $siren ? ' ' . $siren : '' );
        }
        if ( $seller['siret'] ) {
            $parts[] = 'SIRET ' . $seller['siret'];
        }
        if ( $seller['vat_number'] ) {
            $parts[] = __( 'VAT', 'gofactox-e-invoicing-for-woocommerce' ) . ' ' . $seller['vat_number'];
        }
        echo esc_html( implode( ', ', $parts ) );
        ?>
    </p>
    <?php endif; ?>
</div>

</body>
</html>
