<?php

require_once __DIR__ . '/../app/config/config.php';
require_once __DIR__ . '/../app/config/database.php';
require_once __DIR__ . '/../app/helpers/functions.php';
require_once __DIR__ . '/../app/helpers/auth.php';
require_once __DIR__ . '/../app/helpers/cart.php';

$pageTitle = 'Order Tracking | LOVE-U Essentials';
$pageDescription = 'Track your LOVE-U Essentials order status, payment status, shipping status, and tracking number.';

$error = '';
$order = null;
$orderItems = [];
$giftOrder = null;

if (is_post()) {
    if (!verify_csrf()) {
        $error = 'Invalid request. Please refresh and try again.';
    } else {
        $orderNumber = strtoupper(trim($_POST['order_number'] ?? ''));
        $email = trim($_POST['email'] ?? '');

        if ($orderNumber === '' || $email === '') {
            $error = 'Please enter your order number and email address.';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = 'Please enter a valid email address.';
        } else {
            $stmt = $pdo->prepare("
                SELECT *
                FROM orders
                WHERE order_number = ?
                  AND customer_email = ?
                LIMIT 1
            ");
            $stmt->execute([$orderNumber, $email]);
            $order = $stmt->fetch();

            if (!$order) {
                $error = 'No order found with those details.';
            } else {
                $stmt = $pdo->prepare("
                    SELECT oi.*, p.slug,
                        (
                            SELECT image_path
                            FROM product_images
                            WHERE product_id = oi.product_id
                            ORDER BY is_primary DESC, sort_order ASC, id ASC
                            LIMIT 1
                        ) AS primary_image
                    FROM order_items oi
                    LEFT JOIN products p ON oi.product_id = p.id
                    WHERE oi.order_id = ?
                    ORDER BY oi.id ASC
                ");
                $stmt->execute([$order['id']]);
                $orderItems = $stmt->fetchAll();

                $stmt = $pdo->prepare("
                    SELECT *
                    FROM gift_orders
                    WHERE order_id = ?
                    LIMIT 1
                ");
                $stmt->execute([$order['id']]);
                $giftOrder = $stmt->fetch();
            }
        }
    }
}

function status_label($value)
{
    return ucwords(str_replace('_', ' ', $value));
}

require_once __DIR__ . '/includes/header.php';
?>

<section class="shop-hero">
    <div class="container">
        <div class="eyebrow">Track Your Order</div>
        <h1>Order Tracking</h1>
        <p>Enter your order number and email address to view your order progress.</p>
    </div>
</section>

<section class="section">
    <div class="container">
        <div class="checkout-layout">
            <div>
                <div class="checkout-form" style="margin-bottom:24px;">
                    <h2>Find Your Order</h2>

                    <?php if ($error): ?>
                        <div class="admin-alert admin-alert-error"><?= e($error); ?></div>
                    <?php endif; ?>

                    <form method="POST">
                        <?= csrf_field(); ?>

                        <div class="checkout-grid">
                            <div class="checkout-field">
                                <label>Order Number *</label>
                                <input
                                    type="text"
                                    name="order_number"
                                    placeholder="LUE-20260519-ABC123"
                                    value="<?= e($_POST['order_number'] ?? ''); ?>"
                                    required
                                >
                            </div>

                            <div class="checkout-field">
                                <label>Email Address *</label>
                                <input
                                    type="email"
                                    name="email"
                                    placeholder="you@example.com"
                                    value="<?= e($_POST['email'] ?? ''); ?>"
                                    required
                                >
                            </div>
                        </div>

                        <button type="submit" class="btn">Track Order</button>
                    </form>
                </div>

                <?php if ($order): ?>
                    <div class="checkout-form">
                        <h2>Order Items</h2>

                        <?php foreach ($orderItems as $item): ?>
                            <div class="checkout-product">
                                <div class="checkout-product-image">
                                    <?php if (!empty($item['primary_image'])): ?>
                                        <img src="<?= e(BASE_URL . '/' . $item['primary_image']); ?>" alt="<?= e($item['product_name']); ?>">
                                    <?php else: ?>
                                        <div class="product-placeholder"><?= e($item['product_name']); ?></div>
                                    <?php endif; ?>
                                </div>

                                <div>
                                    <h3>
                                        <?php if (!empty($item['slug'])): ?>
                                            <a href="<?= e(BASE_URL); ?>/public/product.php?slug=<?= e($item['slug']); ?>">
                                                <?= e($item['product_name']); ?>
                                            </a>
                                        <?php else: ?>
                                            <?= e($item['product_name']); ?>
                                        <?php endif; ?>
                                    </h3>

                                    <p>
                                        Qty <?= e($item['quantity']); ?>
                                        ×
                                        <?= e(format_price($item['unit_price'], $order['currency_code'])); ?>
                                    </p>
                                </div>

                                <strong><?= e(format_price($item['total_price'], $order['currency_code'])); ?></strong>
                            </div>
                        <?php endforeach; ?>

                        <?php if ($giftOrder): ?>
                            <div style="margin-top:22px; padding:18px; background:#f7f4ef; border-radius:18px; border:1px solid #eee8df;">
                                <h3 style="margin-top:0;">Gift Order</h3>
                                <p style="line-height:1.7; color:#555; margin-bottom:0;">
                                    <strong>Recipient:</strong> <?= e($giftOrder['recipient_name']); ?><br>
                                    <?php if (!empty($giftOrder['gift_message'])): ?>
                                        <strong>Message:</strong> <?= nl2br(e($giftOrder['gift_message'])); ?>
                                    <?php endif; ?>
                                </p>
                            </div>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            </div>

            <aside class="checkout-summary">
                <?php if (!$order): ?>
                    <h2>Tracking Help</h2>
                    <p style="line-height:1.8; color:#555;">
                        Your order number is shown after checkout and can also be provided through your order confirmation email once email automation is connected.
                    </p>

                    <a href="<?= e(BASE_URL); ?>/public/contact.php" class="btn btn-light" style="width:100%;">Contact Support</a>
                <?php else: ?>
                    <h2>Order Summary</h2>

                    <p style="line-height:1.8; color:#555;">
                        <strong>Order Number:</strong><br>
                        <?= e($order['order_number']); ?><br><br>

                        <strong>Order Date:</strong><br>
                        <?= e(date('d M Y, h:i A', strtotime($order['created_at']))); ?><br><br>

                        <strong>Payment Status:</strong><br>
                        <?= e(status_label($order['payment_status'])); ?><br><br>

                        <strong>Order Status:</strong><br>
                        <?= e(status_label($order['order_status'])); ?><br><br>

                        <strong>Shipping Status:</strong><br>
                        <?= e(status_label($order['shipping_status'])); ?><br><br>

                        <strong>Tracking Number:</strong><br>
                        <?= e($order['tracking_number'] ?? 'Not available yet'); ?>
                    </p>

                    <hr style="border:none; border-top:1px solid #e2d8cc; margin:22px 0;">

                    <div class="checkout-total-row">
                        <span>Subtotal</span>
                        <strong><?= e(format_price($order['subtotal'], $order['currency_code'])); ?></strong>
                    </div>

                    <?php if ((float)$order['discount_amount'] > 0): ?>
                        <div class="checkout-total-row">
                            <span>
                                Discount
                                <?php if (!empty($order['coupon_code'])): ?>
                                    <br><small><?= e($order['coupon_code']); ?></small>
                                <?php endif; ?>
                            </span>
                            <strong>-<?= e(format_price($order['discount_amount'], $order['currency_code'])); ?></strong>
                        </div>
                    <?php endif; ?>

                    <div class="checkout-total-row">
                        <span>Shipping</span>
                        <strong><?= e(format_price($order['shipping_fee'], $order['currency_code'])); ?></strong>
                    </div>

                    <div class="checkout-grand-total">
                        <span>Total</span>
                        <strong><?= e(format_price($order['total_amount'], $order['currency_code'])); ?></strong>
                    </div>

                    <a href="<?= e(BASE_URL); ?>/public/shop.php" class="btn" style="width:100%;">Continue Shopping</a>
                <?php endif; ?>
            </aside>
        </div>
    </div>
</section>

<?php require_once __DIR__ . '/includes/footer.php'; ?>