<?php
/**
 * Default credit note template for Factur-X credit notes (type 381).
 *
 * Shares the structure of invoice-default.php with credit-note-specific labels,
 * a reference block to the original invoice, and an optional "AVOIR" watermark.
 * Amounts in $invoice are stored as positive values; the document type code
 * (381 vs 380) is what signals a credit to the receiving system.
 *
 * Available variables: same as invoice-default.php, plus:
 * @var array $invoice {
 *     @type bool   $is_credit_note  Always true here.
 *     @type array  $original_invoice { @type string $number, @type string $date }
 *     @type string $refund_reason    Optional, set by WC merchant on refund creation.
 * }
 *
 * @package FacturX_For_WooCommerce
 */

defined( 'ABSPATH' ) || exit;

$seller    = $invoice['seller'];
$buyer     = $invoice['buyer'];
$lines     = $invoice['lines'];
$cur       = $invoice['currency'];
$original  = $invoice['original_invoice'] ?? [];
$reason    = (string) ( $invoice['refund_reason'] ?? '' );
// Watermark is a Pro feature (in line with WPOvernight, WebToffee).
$watermark = get_option( 'gofactox_credit_note_watermark', 'yes' ) === 'yes'
    && class_exists( 'GOFACTOX_License' )
    && GOFACTOX_License::is_pro();

$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: #b91c1c; }
    .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; }
    .reference-box { background: #fef2f2; border-left: 3px solid #b91c1c; padding: 3mm 4mm; margin-bottom: 6mm; font-size: 9pt; }
    .reference-box strong { color: #991b1b; }
    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: #fee2e2; color: #b91c1c; font-size: 7pt; padding: 1mm 2mm; border-radius: 1mm; font-weight: bold; }
    <?php if ( $watermark ) : ?>
    .watermark { position: fixed; top: 120mm; left: 0; right: 0; text-align: center; font-size: 90pt; color: #fca5a5; opacity: 0.25; font-weight: bold; letter-spacing: 6mm; transform: rotate(-20deg); z-index: 1000; pointer-events: none; }
    <?php endif; ?>
</style>
</head>
<body>

<?php if ( $watermark ) : ?>
<div class="watermark"><?php echo esc_html( _x( 'CREDIT NOTE', 'watermark on the credit note PDF', 'gofactox-e-invoicing-for-woocommerce' ) ); ?></div>
<?php endif; ?>

<!-- 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( 'CREDIT NOTE', '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( 'Credit Note 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['order_number'] ) ) : ?>
        <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 endif; ?>
        <?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; ?>
    </table>
</td>
</tr>
</table>

<!-- Reference to original invoice (BT-25 + BT-26) -->
<?php if ( ! empty( $original['number'] ) ) : ?>
<div class="reference-box">
    <?php
    if ( ! empty( $original['date'] ) ) {
        printf(
            /* translators: %1$s: original invoice number, %2$s: original invoice date */
            esc_html__( 'Credit note related to invoice %1$s dated %2$s.', 'gofactox-e-invoicing-for-woocommerce' ),
            '<strong>' . esc_html( $original['number'] ) . '</strong>',
            '<strong>' . esc_html( date_i18n( 'd/m/Y', strtotime( $original['date'] ) ) ) . '</strong>'
        );
    } else {
        printf(
            /* translators: %s: original invoice number */
            esc_html__( 'Credit note related to invoice %s.', 'gofactox-e-invoicing-for-woocommerce' ),
            '<strong>' . esc_html( $original['number'] ) . '</strong>'
        );
    }
    ?>
    <?php if ( $reason !== '' ) : ?>
        <br><?php echo esc_html__( 'Reason:', 'gofactox-e-invoicing-for-woocommerce' ) . ' ' . esc_html( $reason ); ?>
    <?php endif; ?>
</div>
<?php endif; ?>

<!-- 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( 'Credit To', 'gofactox-e-invoicing-for-woocommerce' ); ?></p>
        <?php if ( ! empty( $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 ( ! empty( $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 (refunded) -->
<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">
    <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( $invoice['total_ht'] ) ); ?></td>
    </tr>
    <?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 credited (incl. VAT)', 'gofactox-e-invoicing-for-woocommerce' ); ?></td>
        <td class="text-right"><?php echo esc_html( $format_amount( $invoice['total_ttc'] ) ); ?></td>
    </tr>
</table>

<!-- Legal Mentions -->
<div class="legal">
    <p><?php esc_html_e( 'This credit note has been issued in accordance with article 289 of the French General Tax Code. It applies a partial or total reversal of the invoice referenced above.', 'gofactox-e-invoicing-for-woocommerce' ); ?></p>

    <?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 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 ( 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>
