<?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());
$current_year = gmdate('Y');
$template = !empty($settings['template']) ? $settings['template'] : 'default';

// Start output buffering to capture styles
ob_start();
wp_print_styles("pdfinvx-{$template}");
$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">
            <table class="header-table">
                <tr>
                    <td class="company-details">
                        <?php if ($logo && filter_var($logo, FILTER_VALIDATE_URL)) : ?>
                            <div style="display: block;">
                            <?php // phpcs:ignore PluginCheck.CodeAnalysis.ImageFunctions.NonEnqueuedImage -- Logo is a settings-based URL from attachment ID ?>
                                <img src="<?php echo esc_url($logo); ?>" alt="Store Logo" style="width: 25mm; height: 12mm; object-fit: contain;" dpi="96">
                            </div>
                        <?php else : ?>
                            <div style="font-size: 9pt; color: #ff0000; display: <?php echo defined('WP_DEBUG') && WP_DEBUG ? 'block' : 'none'; ?>;">
                                <?php esc_html_e('Logo not available', 'pdf-invoicex'); ?>
                            </div>
                        <?php endif; ?>
                        <div style="display: block; margin-top: 5px;">
                            <?php echo nl2br(wp_kses_post($store_address)); ?>
                        </div>
                    </td>
                    <td class="invoice-details">
                        <div class="invoice-title"><?php esc_html_e('INVOICE', 'pdf-invoicex'); ?></div>
                        <div><strong><?php esc_html_e('Invoice #:', 'pdf-invoicex'); ?></strong> <?php echo esc_html($invoice_number); ?></div>
                        <div><strong><?php esc_html_e('Date:', 'pdf-invoicex'); ?></strong> <?php echo esc_html($created_date); ?></div>
                        <div><strong><?php esc_html_e('Payment Method:', 'pdf-invoicex'); ?></strong> <?php echo esc_html($order->get_payment_method_title()); ?></div>
                        <div><strong><?php esc_html_e('Order Status:', 'pdf-invoicex'); ?></strong> <?php echo esc_html(wc_get_order_status_name($order->get_status())); ?></div>
                    </td>
                </tr>
            </table>
        </div>
        
        <!-- Customer & Shipping Details -->
        <table class="customer-shipping-table">
            <tr>
                <td class="billing-info">
                    <div class="info-title"><?php esc_html_e('Billing Details', 'pdf-invoicex'); ?></div>
                    <?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 esc_html_e('Email:', 'pdf-invoicex'); ?> <?php echo esc_html($order->get_billing_email()); ?></div>
                    <?php endif; ?>
                    <?php if ($order->get_billing_phone()) : ?>
                        <div><?php esc_html_e('Phone:', 'pdf-invoicex'); ?> <?php echo esc_html($order->get_billing_phone()); ?></div>
                    <?php endif; ?>
                </td>
                <td class="shipping-info">
                    <div class="info-title"><?php esc_html_e('Shipping Details', 'pdf-invoicex'); ?></div>
                    <?php if ($order->get_formatted_shipping_full_name()) : ?>
                        <div><?php echo esc_html($order->get_formatted_shipping_full_name()); ?></div>
                        <?php if ($order->get_shipping_company()) : ?>
                            <div><?php echo esc_html($order->get_shipping_company()); ?></div>
                        <?php endif; ?>
                        <?php if ($order->get_shipping_address_1()) : ?>
                            <div><?php echo esc_html($order->get_shipping_address_1()); ?></div>
                        <?php endif; ?>
                        <?php if ($order->get_shipping_address_2()) : ?>
                            <div><?php echo esc_html($order->get_shipping_address_2()); ?></div>
                        <?php endif; ?>
                        <?php if ($order->get_shipping_city() || $order->get_shipping_state() || $order->get_shipping_postcode()) : ?>
                            <div><?php echo esc_html($order->get_shipping_city()); ?><?php echo $order->get_shipping_city() && ($order->get_shipping_state() || $order->get_shipping_postcode()) ? ', ' : ''; ?><?php echo esc_html($order->get_shipping_state()); ?> <?php echo esc_html($order->get_shipping_postcode()); ?></div>
                        <?php endif; ?>
                        <?php if ($order->get_shipping_country()) : ?>
                            <div><?php echo esc_html(WC()->countries->countries[$order->get_shipping_country()]); ?></div>
                        <?php endif; ?>
                    <?php elseif ($order->get_formatted_billing_address()) : ?>
                        <div><em><?php esc_html_e('Same as billing address', 'pdf-invoicex'); ?></em></div>
                    <?php else : ?>
                        <div><em><?php esc_html_e('No shipping address provided', 'pdf-invoicex'); ?></em></div>
                    <?php endif; ?>
                </td>
            </tr>
        </table>
        
        <!-- Order Items -->
        <table class="items-table">
            <thead>
                <tr>
                    <th><?php esc_html_e('Item', 'pdf-invoicex'); ?></th>
                    <th><?php esc_html_e('SKU', 'pdf-invoicex'); ?></th>
                    <th><?php esc_html_e('Quantity', 'pdf-invoicex'); ?></th>
                    <th><?php esc_html_e('Price', 'pdf-invoicex'); ?></th>
                    <th class="text-right"><?php esc_html_e('Total', 'pdf-invoicex'); ?></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($order->get_items() as $item_id => $item) : 
                    $product = $item->get_product();
                    $sku = $product ? $product->get_sku() : '';
                ?>
                    <tr>
                        <td>
                            <strong><?php echo esc_html($item->get_name()); ?></strong>
                            <?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($sku); ?></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 class="text-right"><?php echo wp_kses_post(wc_price($item->get_subtotal(), ['currency' => $order->get_currency()])); ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        
        <!-- Totals Section -->
        <div class="totals-section">
            <table class="totals-table-container">
                <tr>
                    <td class="totals-table-wrapper">
                        <table class="totals-table">
                            <tr>
                                <td class="totals-label"><?php esc_html_e('Subtotal:', 'pdf-invoicex'); ?></td>
                                <td class="totals-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>
                                    <td class="totals-label"><?php esc_html_e('Shipping:', 'pdf-invoicex'); ?></td>
                                    <td class="totals-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>
                                    <td class="totals-label"><?php echo esc_html($tax->label); ?>:</td>
                                    <td class="totals-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>
                                    <td class="totals-label"><?php esc_html_e('Discount:', 'pdf-invoicex'); ?></td>
                                    <td class="totals-value">-<?php echo wp_kses_post(wc_price($order->get_discount_total(), ['currency' => $order->get_currency()])); ?></td>
                                </tr>
                            <?php endif; ?>
                            <tr class="total-row">
                                <td class="totals-label"><?php esc_html_e('Total:', 'pdf-invoicex'); ?></td>
                                <td class="totals-value"><?php echo wp_kses_post(wc_price($order->get_total(), ['currency' => $order->get_currency()])); ?></td>
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>
        </div>
        
        <!-- Notes Section -->
        <?php if ($order->get_customer_note()) : ?>
            <div class="notes-section">
                <div class="notes-title"><?php esc_html_e('Customer Notes:', 'pdf-invoicex'); ?></div>
                <div><?php echo esc_html($order->get_customer_note()); ?></div>
            </div>
        <?php endif; ?>
        
        <!-- Payment Instructions -->
        <?php if (!empty($footer_text)) : ?>
            <div class="notes-section">
                <div class="notes-title"><?php esc_html_e('Instructions', 'pdf-invoicex'); ?></div>
                <p><?php echo nl2br(wp_kses_post($footer_text)); ?></p>
            </div>
        <?php endif; ?>
        
        <!-- Invoice 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>