<?php
/**
 * Order Confirmation Template
 * 
 * Shortcode: [instinctor_order_received]
 */

if (!defined('ABSPATH')) {
    exit;
}

// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only; ownership verified via order_key below
$order_id  = isset($_GET['order_id']) ? intval($_GET['order_id']) : (isset($_GET['order']) ? intval($_GET['order']) : 0);
// phpcs:ignore WordPress.Security.NonceVerification.Recommended,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
$order_key = isset($_GET['order_key']) ? sanitize_text_field(wp_unslash($_GET['order_key'])) : '';

// Impulse preview mode — use dummy data so the block renders properly
$is_preview = isset($GLOBALS['impulse_order_received_settings']);

if (!$order_id && !$is_preview) {
    echo '<p>' . esc_html__('Invalid order.', 'instinctor') . '</p>';
    return;
}

if ($is_preview && !$order_id) {
    // Dummy order object
    $acOrder = (object) [
        'id'             => 1001,
        'order_number'   => 'ORD-1001',
        'email'          => 'jane@example.com',
        'first_name'     => 'Jane',
        'last_name'      => 'Smith',
        'payment_method' => 'Card',
        'subtotal'       => 89.00,
        'shipping_total' => 5.00,
        'tax_total'      => 0.00,
        'total'          => 94.00,
        'customer_id'    => 0,
        'created_at'     => current_time('mysql'),
    ];
    // Dummy order items
    $items = [
        (object) [
            'name'     => 'Premium Widget',
            'quantity' => 1,
            'total'    => 59.00,
            'meta'     => '{}',
        ],
        (object) [
            'name'     => 'Accessory Pack',
            'quantity' => 2,
            'total'    => 30.00,
            'meta'     => '{}',
        ],
    ];
} else {
    global $wpdb;
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery,WordPress.DB.SlowDBQuery -- direct query against the plugin's own custom table; the WP options/post API does not model this data and the read is request-scoped (object caching would add complexity without benefit)
    $acOrder = $wpdb->get_row($wpdb->prepare(
        "SELECT o.*, c.email, c.first_name, c.last_name 
         FROM {$wpdb->prefix}instinctor_orders o
         LEFT JOIN {$wpdb->prefix}instinctor_customers c ON o.customer_id = c.id
         WHERE o.id = %d",
        $order_id
    ));

    if (!$acOrder) {
        echo '<p>' . esc_html__('Order not found.', 'instinctor') . '</p>';
        return;
    }

    // Verify order ownership: require a valid order_key OR an admin/shop-manager capability.
    // This prevents anonymous enumeration of order details via sequential order IDs.
    $storedMeta = json_decode($acOrder->meta ?? '{}', true) ?: [];
    $storedKey  = $storedMeta['order_key'] ?? '';
    $isAdmin    = class_exists('\\Instinctor\\Core\\Auth') && \Instinctor\Core\Auth::can('manage_options');
    if (!$is_preview && !$isAdmin && $storedKey !== '' && !hash_equals($storedKey, $order_key)) {
        echo '<p>' . esc_html__('Access denied. Please use the link from your order confirmation email.', 'instinctor') . '</p>';
        return;
    }

    // phpcs:ignore WordPress.DB.DirectDatabaseQuery,WordPress.DB.SlowDBQuery -- direct query against the plugin's own custom table; the WP options/post API does not model this data and the read is request-scoped (object caching would add complexity without benefit)
    $items = $wpdb->get_results($wpdb->prepare(
        "SELECT * FROM {$wpdb->prefix}instinctor_order_items WHERE order_id = %d",
        $order_id
    ));
}

$currency_symbol = '$';

// Impulse block settings override
$impulseOrSettings = $GLOBALS['impulse_order_received_settings'] ?? null;
$orHeading    = $impulseOrSettings ? ($impulseOrSettings['heading'] ?? '') : '';
$orHeading    = $orHeading ?: __('Thank you for your order!', 'instinctor');
$orContinueUrl = $impulseOrSettings ? ($impulseOrSettings['continue_url'] ?? '') : '';
$orContinueUrl = $orContinueUrl ?: '/shop';
$orButtonText = $impulseOrSettings ? ($impulseOrSettings['button_text'] ?? '') : '';
$orButtonText = $orButtonText ?: __('Continue Shopping', 'instinctor');
?>

<div class="instinctor-order-received">
    <div class="instinctor-order-success">
        <div class="instinctor-success-icon">
            <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M22 11.08V12a10 10 0 11-5.93-9.14"/>
                <polyline points="22 4 12 14.01 9 11.01"/>
            </svg>
        </div>
        <h1><?php echo esc_html($orHeading); ?></h1>
        <?php /* translators: placeholder values */ ?>
        <p><?php /* translators: %s: order number */ printf(esc_html__('Order #%s has been placed successfully.', 'instinctor'), esc_html($acOrder->order_number)); ?></p>
    </div>

    <div class="instinctor-order-details">
        <div class="instinctor-order-section">
            <h2><?php esc_html_e('Items', 'instinctor'); ?></h2>
            
            <div class="instinctor-order-items">
                <?php foreach ($items as $item): 
                    $itemMeta = json_decode($item->meta ?? '{}', true);
                    $hasBooking = !empty($itemMeta['booking_date']) && !empty($itemMeta['booking_time']);
                ?>
                <div class="instinctor-order-item">
                    <div>
                        <span class="instinctor-item-name"><?php echo esc_html($item->name); ?> x <?php echo esc_html($item->quantity); ?></span>
                        <?php if ($hasBooking): ?>
                        <div class="instinctor-item-booking" style="font-size: 13px; color: #666; margin-top: 4px;">
                            <?php esc_html_e('Appointment:', 'instinctor'); ?> 
                            <?php echo esc_html(date_i18n(get_option('date_format'), strtotime($itemMeta['booking_date']))); ?>
                            <?php esc_html_e('at', 'instinctor'); ?> 
                            <?php echo esc_html($itemMeta['booking_time']); ?>
                        </div>
                        <?php endif; ?>
                    </div>
                    <span class="instinctor-item-total"><?php echo esc_html(\Instinctor\Services\CurrencyService::formatPrice($item->total)); ?></span>
                </div>
                <?php endforeach; ?>
            </div>

            <div class="instinctor-order-totals">
                <div class="instinctor-totals-row">
                    <span><?php esc_html_e('Subtotal', 'instinctor'); ?></span>
                    <span><?php echo esc_html(\Instinctor\Services\CurrencyService::formatPrice($acOrder->subtotal)); ?></span>
                </div>
                <?php if ($acOrder->tax_total > 0): ?>
                <div class="instinctor-totals-row">
                    <span><?php esc_html_e('Tax', 'instinctor'); ?></span>
                    <span><?php echo esc_html(\Instinctor\Services\CurrencyService::formatPrice($acOrder->tax_total)); ?></span>
                </div>
                <?php endif; ?>
                <?php if ($acOrder->shipping_total > 0): ?>
                <div class="instinctor-totals-row">
                    <span><?php esc_html_e('Shipping', 'instinctor'); ?></span>
                    <span><?php echo esc_html(\Instinctor\Services\CurrencyService::formatPrice($acOrder->shipping_total)); ?></span>
                </div>
                <?php endif; ?>
                <div class="instinctor-totals-row instinctor-total">
                    <span><?php esc_html_e('Total', 'instinctor'); ?></span>
                    <span><?php echo esc_html(\Instinctor\Services\CurrencyService::formatPrice($acOrder->total)); ?></span>
                </div>
            </div>
        </div>
    </div>

    <?php
    // Digital Downloads section — shown if any downloadable files are available (not in preview)
    if (!$is_preview && class_exists('\\Instinctor\\Services\\DigitalDownloadService') && $acOrder->customer_id) {
        $ddService   = \Instinctor\Services\DigitalDownloadService::instance();
        $ddPerms     = $ddService->getOrderDownloads((int)$order_id, (int)$acOrder->customer_id);
        if (!empty($ddPerms)) : ?>
    <div class="instinctor-order-section instinctor-downloads-section">
        <h2><?php esc_html_e('Your Downloads', 'instinctor'); ?></h2>
        <div class="instinctor-download-list">
            <?php
            $lastProduct = null;
            foreach ($ddPerms as $perm) :
                if ($perm['product_name'] !== $lastProduct) :
                    if ($lastProduct !== null) echo '</div>';
                    echo '<div class="instinctor-dl-product-group">';
                    echo '<div class="instinctor-dl-product-name">' . esc_html($perm['product_name']) . '</div>';
                    $lastProduct = $perm['product_name'];
                endif;
                $url       = $ddService->generateDownloadUrl((int)$perm['permission_id'], (int)$acOrder->customer_id);
                $remaining = $perm['download_limit'] ? ((int)$perm['download_limit'] - (int)$perm['download_count']) . ' remaining' : 'Unlimited';
                $expiry    = $perm['access_expires'] ? date_i18n(get_option('date_format'), strtotime($perm['access_expires'])) : null;
                ?>
            <div class="instinctor-dl-row">
                <div class="instinctor-dl-info">
                    <span class="instinctor-dl-name"><?php echo esc_html($perm['file_name']); ?></span>
                    <span class="instinctor-dl-meta">
                        <?php echo esc_html($remaining); ?>
                        <?php if ($expiry) : ?> · <?php /* translators: %s: expiry date */ printf(esc_html__('Expires %s', 'instinctor'), esc_html($expiry)); ?><?php endif; ?>
                    </span>
                </div>
                <a href="<?php echo esc_url($url); ?>" class="instinctor-dl-btn" download>
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 15V3"/><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/></svg>
                    <?php esc_html_e('Download', 'instinctor'); ?>
                </a>
            </div>
            <?php endforeach; ?>
            </div><!-- close last product group -->
        </div>
    </div>
    <?php ob_start(); ?>
    .instinctor-downloads-section { margin-bottom: 16px; }
    .instinctor-dl-product-name { font-size: 12px; font-weight: 600; color: #86868b; text-transform: uppercase; letter-spacing: 0.04em; margin-bottom: 8px; }
    .instinctor-dl-row { display: flex; align-items: center; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid #f5f5f7; gap: 12px; }
    .instinctor-dl-row:last-child { border-bottom: none; }
    .instinctor-dl-info { flex: 1; min-width: 0; }
    .instinctor-dl-name { display: block; font-size: 14px; color: #1d1d1f; font-weight: 500; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
    .instinctor-dl-meta { display: block; font-size: 12px; color: #86868b; margin-top: 2px; }
    .instinctor-dl-btn { display: inline-flex; align-items: center; gap: 6px; height: 32px; padding: 0 14px; background: #1d1d1f; color: #fff; border-radius: 6px; font-size: 12px; font-weight: 500; text-decoration: none; flex-shrink: 0; }
    .instinctor-dl-btn:hover { background: #000; color: #fff; }
    <?php $_inst_lcss = ob_get_clean(); wp_add_inline_style("instinctor-page-inline", $_inst_lcss); ?>
    <?php endif; }
    ?>

    <div class="instinctor-order-actions">
        <a href="<?php echo esc_url($orContinueUrl); ?>" class="instinctor-btn instinctor-btn-primary">
            <?php echo esc_html($orButtonText); ?>
        </a>
    </div>
</div>

<?php ob_start(); ?>
.instinctor-order-received { width: 100%; margin: 0 auto; padding: 16px 12px; box-sizing: border-box; }

.instinctor-order-success { text-align: center; margin-bottom: 16px; }
.instinctor-success-icon { color: #2e7d32; margin-bottom: 8px; }
.instinctor-success-icon svg { width: 36px; height: 36px; }
.instinctor-order-success h1 { font-size: 18px; font-weight: 600; margin: 0 0 4px; }
.instinctor-order-success p { color: #86868b; margin: 0; font-size: 13px; }

.instinctor-order-section { background: #fff; border: 1px solid #e8e8ed; border-radius: 8px; padding: 12px 14px; margin-bottom: 10px; }
.instinctor-order-section h2 { font-size: 12px; font-weight: 600; margin: 0 0 8px; color: #1d1d1f; }

.instinctor-order-item { display: flex; justify-content: space-between; padding: 4px 0; font-size: 12px; }
.instinctor-item-name { color: #1d1d1f; }
.instinctor-item-total { color: #86868b; }

.instinctor-order-totals { border-top: 1px solid #e8e8ed; margin-top: 8px; padding-top: 8px; }
.instinctor-totals-row { display: flex; justify-content: space-between; padding: 2px 0; font-size: 12px; }
.instinctor-totals-row.instinctor-total { font-weight: 600; font-size: 14px; margin-top: 4px; padding-top: 4px; border-top: 1px solid #e8e8ed; }

.instinctor-order-actions { text-align: center; margin-top: 12px; }
.instinctor-btn { display: inline-flex; align-items: center; justify-content: center; height: 36px; padding: 0 20px; font-size: 13px; font-weight: 500; border-radius: 6px; text-decoration: none; }
.instinctor-btn-primary { background: #1d1d1f; color: #fff; }
.instinctor-btn-primary:hover { background: #000; color: #fff; }
<?php $_inst_lcss = ob_get_clean(); wp_add_inline_style("instinctor-page-inline", $_inst_lcss); ?>
