<?php
/**
 * Packing List Template
 * Accessed via: /wp-content/plugins/ggm-commerce/templates/packing-list.php?order_id=X&key=NONCE
 */

// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery
// phpcs:disable WordPress.DB.DirectDatabaseQuery.NoCaching
// phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter

// Load WordPress if not already loaded (standalone entry point).
if ( ! defined( 'ABSPATH' ) ) {
    require_once(dirname(__FILE__) . '/../../../../wp-load.php');
}

// Security checks
if (!isset($_GET['order_id']) || !isset($_GET['key'])) {
    wp_die('Invalid request');
}

$order_id = intval($_GET['order_id']);
$key = sanitize_text_field(wp_unslash($_GET['key']));

// Verify nonce
if (!wp_verify_nonce($key, 'ggmc_print_order_' . $order_id)) {
    wp_die('Security check failed');
}

// Check user permissions
if (!current_user_can('manage_options')) {
    wp_die('Insufficient permissions');
}

// Get order data
global $wpdb;
$order = $wpdb->get_row($wpdb->prepare(
    "SELECT * FROM {$wpdb->prefix}ggmc_orders WHERE id = %d",
    $order_id
));

if (!$order) {
    wp_die('Order not found');
}

// Get order items
$items = $wpdb->get_results($wpdb->prepare(
    "SELECT * FROM {$wpdb->prefix}ggmc_order_items WHERE order_id = %d",
    $order_id
));

// Get business settings
$business_options = get_option('ggm_commerce_business_options', []);
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Packing List - Order #<?php echo esc_html($order->order_number); ?></title>
    <style>
        @media print {
            @page {
                margin: 0.5in;
            }
            body {
                margin: 0;
            }
            .no-print {
                display: none;
            }
        }
        body {
            font-family: Arial, sans-serif;
            font-size: 12pt;
            line-height: 1.4;
            color: #000;
            max-width: 8in;
            margin: 0 auto;
            padding: 20px;
            background: white;
        }
        .header {
            border-bottom: 3px solid #000;
            padding-bottom: 20px;
            margin-bottom: 30px;
        }
        .header h1 {
            margin: 0 0 10px 0;
            font-size: 24pt;
        }
        .header .company-info {
            font-size: 10pt;
        }
        .order-info {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 30px;
            margin-bottom: 30px;
        }
        .info-box h3 {
            margin: 0 0 10px 0;
            font-size: 12pt;
            border-bottom: 1px solid #ccc;
            padding-bottom: 5px;
        }
        .info-box p {
            margin: 5px 0;
            font-size: 11pt;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 30px;
        }
        table th {
            background: #f5f5f5;
            padding: 10px;
            text-align: left;
            border-bottom: 2px solid #000;
            font-size: 11pt;
        }
        table td {
            padding: 10px;
            border-bottom: 1px solid #ddd;
            font-size: 11pt;
        }
        .checkbox {
            display: inline-block;
            width: 18px;
            height: 18px;
            border: 2px solid #000;
            vertical-align: middle;
            margin-right: 8px;
        }
        .notes {
            margin-top: 30px;
            border-top: 1px solid #ccc;
            padding-top: 20px;
        }
        .notes h3 {
            margin: 0 0 10px 0;
        }
        .print-button {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 10px 20px;
            background: #0073aa;
            color: white;
            border: none;
            cursor: pointer;
            font-size: 14pt;
            border-radius: 4px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.3);
        }
        .print-button:hover {
            background: #005a87;
        }
    </style>
</head>
<body>
    <button onclick="window.print()" class="print-button no-print">Print</button>

    <div class="header">
        <h1>PACKING LIST</h1>
        <div class="company-info">
            <?php if (!empty($business_options['name'])): ?>
                <strong><?php echo esc_html($business_options['name']); ?></strong><br>
            <?php endif; ?>
            <?php if (!empty($business_options['address'])): ?>
                <?php echo nl2br(esc_html($business_options['address'])); ?><br>
            <?php endif; ?>
            <?php if (!empty($business_options['phone'])): ?>
                Phone: <?php echo esc_html($business_options['phone']); ?><br>
            <?php endif; ?>
            <?php if (!empty($business_options['email'])): ?>
                Email: <?php echo esc_html($business_options['email']); ?>
            <?php endif; ?>
        </div>
    </div>

    <div class="order-info">
        <div class="info-box">
            <h3>Order Information</h3>
            <p><strong>Order Number:</strong> <?php echo esc_html($order->order_number); ?></p>
            <p><strong>Order Date:</strong> <?php echo esc_html(gmdate('F j, Y', strtotime($order->created_at))); ?></p>
            <p><strong>Order Status:</strong> <?php echo esc_html(ucfirst($order->status)); ?></p>
        </div>
        <div class="info-box">
            <h3>Ship To</h3>
            <p>
                <strong><?php echo esc_html($order->customer_first_name . ' ' . $order->customer_last_name); ?></strong><br>
                <?php if ($order->shipping_address_1): ?>
                    <?php echo esc_html($order->shipping_address_1); ?><br>
                    <?php if ($order->shipping_address_2): ?>
                        <?php echo esc_html($order->shipping_address_2); ?><br>
                    <?php endif; ?>
                    <?php echo esc_html($order->shipping_city); ?>, <?php echo esc_html($order->shipping_state); ?> <?php echo esc_html($order->shipping_postcode); ?><br>
                    <?php echo esc_html($order->shipping_country); ?>
                <?php else: ?>
                    <?php echo esc_html($order->billing_address_1); ?><br>
                    <?php if ($order->billing_address_2): ?>
                        <?php echo esc_html($order->billing_address_2); ?><br>
                    <?php endif; ?>
                    <?php echo esc_html($order->billing_city); ?>, <?php echo esc_html($order->billing_state); ?> <?php echo esc_html($order->billing_postcode); ?><br>
                    <?php echo esc_html($order->billing_country); ?>
                <?php endif; ?>
            </p>
            <p><strong>Phone:</strong> <?php echo esc_html($order->customer_phone); ?></p>
        </div>
    </div>

    <table>
        <thead>
            <tr>
                <th style="width: 50px;">Packed</th>
                <th style="width: 120px;">SKU</th>
                <th>Product Name</th>
                <th style="width: 140px;">Barcode</th>
                <th style="width: 80px; text-align: center;">Qty</th>
            </tr>
        </thead>
        <tbody>
            <?php
            $barcode_manager = GGM_Commerce_Barcode::get_instance();
            foreach ($items as $item):
                $primary_barcode = $barcode_manager->get_primary_barcode($item->product_id);

                // Get variation display - use stored data or look up from variation_id
                $variation_display = '';
                if (!empty($item->variation_data)) {
                    $variation_display = $item->variation_data;
                } elseif (!empty($item->variation_id) && class_exists('GGM_Commerce_Variations')) {
                    // Fallback: look up variation attributes from variation_id
                    $variations_manager = GGM_Commerce_Variations::instance();
                    $variation = $variations_manager->get_variation($item->variation_id);
                    if ($variation && !empty($variation['attributes'])) {
                        $attr_parts = [];
                        foreach ($variation['attributes'] as $attr) {
                            $attr_name = $attr['attribute_name'] ?? $attr['name'] ?? '';
                            $attr_value = $attr['attribute_value'] ?? $attr['value'] ?? '';
                            if (!empty($attr_name) && !empty($attr_value)) {
                                $attr_parts[] = $attr_name . ': ' . $attr_value;
                            }
                        }
                        if (!empty($attr_parts)) {
                            $variation_display = implode(', ', $attr_parts);
                        }
                    }
                }
            ?>
                <tr>
                    <td style="text-align: center;"><span class="checkbox"></span></td>
                    <td><?php echo esc_html($item->product_sku); ?></td>
                    <td>
                        <?php echo esc_html($item->product_name); ?>
                        <?php if (!empty($variation_display)): ?>
                            <br><small style="color: #666; font-style: italic;"><?php echo esc_html($variation_display); ?></small>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php if ($primary_barcode): ?>
                            <strong><?php echo esc_html($primary_barcode->barcode_value); ?></strong><br>
                            <small style="color: #666;"><?php echo esc_html($primary_barcode->barcode_type); ?></small>
                        <?php else: ?>
                            <span style="color: #999;">-</span>
                        <?php endif; ?>
                    </td>
                    <td style="text-align: center;"><strong><?php echo esc_html($item->quantity); ?></strong></td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <div class="notes">
        <h3>Packing Notes:</h3>
        <div style="border: 1px solid #ccc; min-height: 100px; padding: 10px; background: #fafafa;">
            <?php
            // Get picking list notes only
            $picking_notes = GGM_Commerce_Order_Notes::get_picking_notes($order_id);
            if (!empty($picking_notes)):
                foreach ($picking_notes as $note):
            ?>
                <p style="margin: 0 0 10px 0;"><?php echo nl2br(esc_html($note->content)); ?></p>
            <?php
                endforeach;
            else:
            ?>
                <p style="color: #999; font-style: italic;">No packing notes.</p>
            <?php endif; ?>
        </div>
    </div>

    <div style="margin-top: 40px; text-align: center; font-size: 10pt; color: #666;">
        <p>Packed by: __________________ Date: __________________ Time: __________________</p>
    </div>
</body>
</html>
