<?php
defined('ABSPATH') || exit;

$order = wc_get_order($order_id);
if (!$order) {
    return;
}

$settings = get_option('pdfinvx_settings', []);
// Fetch logo from store_logo_id (attachment ID)
$logo = '';
if (!empty($settings['store_logo_id']) && is_numeric($settings['store_logo_id'])) {
    $logo = wp_get_attachment_url($settings['store_logo_id']);
    if ($logo) {
        $logo = esc_url($logo);
    }
}
// Fallback to default logo if invalid or empty
if (!$logo || !filter_var($logo, FILTER_VALIDATE_URL)) {
    $logo = defined('PDFINVX51_PLUGIN_URL') ? esc_url(PDFINVX51_PLUGIN_URL . 'assets/images/default-logo.png') : '';
}

$store_address = !empty($settings['store_address']) ? wp_kses_post($settings['store_address']) : '';
$footer_text = !empty($settings['footer_text']) ? wp_kses_post($settings['footer_text']) : '';
$invoice_number = $this->get_invoice_number($order_id);
$created_date = date_i18n(get_option('date_format'), time());
$store_name = get_bloginfo('name');
$current_year = gmdate('Y');

// Start output buffering to capture styles
ob_start();
wp_print_styles('pdfinvx-classic');
$styles = ob_get_clean();
?>

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title><?php echo esc_html__('Invoice', 'pdf-invoicex') . ' ' . esc_html($invoice_number); ?></title>
    <?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $styles is safe CSS output from wp_print_styles() ?>
    <?php echo $styles; ?>
</head>
<body>
    <div class="invoice-container">
        <!-- Invoice Header -->
        <div class="invoice-header">
            <div class="invoice-title">
                <h1><?php esc_html_e('INVOICE', 'pdf-invoicex'); ?></h1>
            </div>
            <div class="company-details">
                <div class="company-left">
                    <?php if ($logo && filter_var($logo, FILTER_VALIDATE_URL)) : ?>
                        <?php // phpcs:ignore PluginCheck.CodeAnalysis.ImageFunctions.NonEnqueuedImage -- Logo is a settings-based URL from attachment ID ?>
                        <img src="<?php echo esc_url($logo); ?>" alt="<?php echo esc_attr($store_name); ?>" class="logo" style="width: 95px; height: 45px; object-fit: contain;">
                    <?php else : ?>
                        <div class="logo-fallback"><?php esc_html_e('Logo not available', 'pdf-invoicex'); ?></div>
                    <?php endif; ?>
                    <div class="address"><?php echo nl2br(wp_kses_post($store_address)); ?></div>
                </div>
            </div>
        </div>

        <!-- Invoice Info -->
        <div class="invoice-info">
            <table class="invoice-info-table">
                <tr>
                    <td class="client-info">
                        <h2><?php esc_html_e('Bill To:', 'pdf-invoicex'); ?></h2>
                        <?php if ($order->get_formatted_billing_full_name()) : ?>
                            <div><?php echo esc_html($order->get_formatted_billing_full_name()); ?></div>
                        <?php endif; ?>
                        <?php if ($order->get_billing_company()) : ?>
                            <div><?php echo esc_html($order->get_billing_company()); ?></div>
                        <?php endif; ?>
                        <?php if ($order->get_billing_address_1()) : ?>
                            <div><?php echo esc_html($order->get_billing_address_1()); ?></div>
                        <?php endif; ?>
                        <?php if ($order->get_billing_address_2()) : ?>
                            <div><?php echo esc_html($order->get_billing_address_2()); ?></div>
                        <?php endif; ?>
                        <?php if ($order->get_billing_city() || $order->get_billing_state() || $order->get_billing_postcode()) : ?>
                            <div>
                                <?php echo esc_html($order->get_billing_city()); ?>
                                <?php echo $order->get_billing_city() && ($order->get_billing_state() || $order->get_billing_postcode()) ? ', ' : ''; ?>
                                <?php echo esc_html($order->get_billing_state()); ?>
                                <?php echo esc_html($order->get_billing_postcode()); ?>
                            </div>
                        <?php endif; ?>
                        <?php if ($order->get_billing_country()) : ?>
                            <div><?php echo esc_html(WC()->countries->countries[$order->get_billing_country()]); ?></div>
                        <?php endif; ?>
                        <?php if ($order->get_billing_email()) : ?>
                            <div><?php echo esc_html($order->get_billing_email()); ?></div>
                        <?php endif; ?>
                        <?php if ($order->get_billing_phone()) : ?>
                            <div><?php echo esc_html($order->get_billing_phone()); ?></div>
                        <?php endif; ?>
                    </td>
                    <td class="invoice-details">
                        <table class="invoice-details-table">
                            <tr class="invoice-details-row">
                                <td class="invoice-details-label"><?php esc_html_e('Invoice Number:', 'pdf-invoicex'); ?></td>
                                <td><?php echo esc_html($invoice_number); ?></td>
                            </tr>
                            <tr class="invoice-details-row">
                                <td class="invoice-details-label"><?php esc_html_e('Invoice Date:', 'pdf-invoicex'); ?></td>
                                <td><?php echo esc_html($created_date); ?></td>
                            </tr>
                            <tr class="invoice-details-row">
                                <td class="invoice-details-label"><?php esc_html_e('Payment Method:', 'pdf-invoicex'); ?></td>
                                <td><?php echo esc_html($order->get_payment_method_title()); ?></td>
                            </tr>
                            <tr class="invoice-details-row">
                                <td class="invoice-details-label"><?php esc_html_e('Order Status:', 'pdf-invoicex'); ?></td>
                                <td><?php echo esc_html(wc_get_order_status_name($order->get_status())); ?></td>
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>
        </div>

        <!-- Invoice Items -->
        <table class="invoice-items">
            <thead>
                <tr>
                    <th style="width: 5%;"><?php esc_html_e('#', 'pdf-invoicex'); ?></th>
                    <th style="width: 50%;"><?php esc_html_e('Description', 'pdf-invoicex'); ?></th>
                    <th style="width: 10%;"><?php esc_html_e('Qty', 'pdf-invoicex'); ?></th>
                    <th style="width: 15%;"><?php esc_html_e('Unit Price', 'pdf-invoicex'); ?></th>
                    <th style="width: 20%;"><?php esc_html_e('Amount', 'pdf-invoicex'); ?></th>
                </tr>
            </thead>
            <tbody>
                <?php $item_count = 1; ?>
                <?php foreach ($order->get_items() as $item_id => $item) : 
                    $product = $item->get_product();
                    $sku = $product ? $product->get_sku() : '';
                ?>
                    <tr>
                        <td><?php echo esc_html($item_count++); ?></td>
                        <td>
                            <strong><?php echo esc_html($item->get_name()); ?></strong>
                            <?php if ($sku) : ?>
                                <div><?php esc_html_e('SKU:', 'pdf-invoicex'); ?> <?php echo esc_html($sku); ?></div>
                            <?php endif; ?>
                            <?php 
                            $metadata = $item->get_formatted_meta_data();
                            if (!empty($metadata)) : 
                            ?>
                                <div class="item-meta">
                                    <?php foreach ($metadata as $meta) : ?>
                                        <div><?php echo wp_kses_post($meta->display_key . ': ' . $meta->display_value); ?></div>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                        </td>
                        <td><?php echo esc_html($item->get_quantity()); ?></td>
                        <td><?php echo wp_kses_post(wc_price($item->get_subtotal() / $item->get_quantity(), ['currency' => $order->get_currency()])); ?></td>
                        <td><?php echo wp_kses_post(wc_price($item->get_subtotal(), ['currency' => $order->get_currency()])); ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

        <!-- Invoice Summary -->
        <div class="invoice-summary">
            <div class="summary-content">
                <table>
                    <tr class="summary-row">
                        <td class="summary-label"><?php esc_html_e('Subtotal:', 'pdf-invoicex'); ?></td>
                        <td class="summary-value"><?php echo wp_kses_post(wc_price($order->get_subtotal(), ['currency' => $order->get_currency()])); ?></td>
                    </tr>
                    <?php if ($order->get_shipping_total() > 0) : ?>
                        <tr class="summary-row">
                            <td class="summary-label"><?php esc_html_e('Shipping:', 'pdf-invoicex'); ?></td>
                            <td class="summary-value"><?php echo wp_kses_post(wc_price($order->get_shipping_total(), ['currency' => $order->get_currency()])); ?></td>
                        </tr>
                    <?php endif; ?>
                    <?php foreach ($order->get_tax_totals() as $tax_code => $tax) : ?>
                        <tr class="summary-row">
                            <td class="summary-label"><?php echo esc_html($tax->label); ?>:</td>
                            <td class="summary-value"><?php echo wp_kses_post(wc_price($tax->amount, ['currency' => $order->get_currency()])); ?></td>
                        </tr>
                    <?php endforeach; ?>
                    <?php if ($order->get_discount_total() > 0) : ?>
                        <tr class="summary-row">
                            <td class="summary-label"><?php esc_html_e('Discount:', 'pdf-invoicex'); ?></td>
                            <td class="summary-value">-<?php echo wp_kses_post(wc_price($order->get_discount_total(), ['currency' => $order->get_currency()])); ?></td>
                        </tr>
                    <?php endif; ?>
                    <tr class="summary-row total-row">
                        <td class="summary-label"><?php esc_html_e('Total:', 'pdf-invoicex'); ?></td>
                        <td class="summary-value"><?php echo wp_kses_post(wc_price($order->get_total(), ['currency' => $order->get_currency()])); ?></td>
                    </tr>
                </table>
            </div>
        </div>

        <!-- Payment Info -->
        <?php if (!empty($footer_text)) : ?>
            <div class="payment-info">
                <h2><?php esc_html_e('Payment Instructions', 'pdf-invoicex'); ?></h2>
                <p><?php echo nl2br(wp_kses_post($footer_text)); ?></p>
            </div>
        <?php endif; ?>

        <!-- Notes -->
        <?php if ($order->get_customer_note()) : ?>
            <div class="notes-section">
                <h2><?php esc_html_e('Notes', 'pdf-invoicex'); ?></h2>
                <p><?php echo esc_html($order->get_customer_note()); ?></p>
            </div>
        <?php endif; ?>

        <!-- Footer -->
        <div class="invoice-footer">
            <p><?php esc_html_e('This invoice was automatically generated and is valid without a signature.', 'pdf-invoicex'); ?></p>
            <p>© <?php echo esc_html($current_year); ?>. <?php esc_html_e('All rights reserved.', 'pdf-invoicex'); ?></p>
        </div>
    </div>
</body>
</html>