<?php
$pageTitle = "Track Order - Tom's Java Jive";
$metaDescription = "Track your Tom's Java Jive order status and shipment in real time.";
$breadcrumbs = [
    ['name' => 'Home', 'url' => 'https://tomsjavajive.com'],
    ['name' => 'Track Order', 'url' => 'https://tomsjavajive.com/track-order.php']
];
require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/includes/auth.php';

$order = null;
$error = null;
$searched = false;

// Pre-fill from query string (e.g. from order confirmation email link)
$prefillOrder = $_GET['order'] ?? '';
$prefillEmail = $_GET['email'] ?? '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' || ($prefillOrder && $prefillEmail)) {
    $searched = true;
    $orderNum = trim($_POST['order_number'] ?? $prefillOrder);
    $email    = strtolower(trim($_POST['email'] ?? $prefillEmail));

    if (empty($orderNum) || empty($email)) {
        $error = 'Please enter both your order number and email address.';
    } else {
        $order = db()->fetch(
            "SELECT * FROM orders WHERE (order_number = :num OR order_id = :id) AND LOWER(customer_email) = :email",
            ['num' => $orderNum, 'id' => $orderNum, 'email' => $email]
        );
        if (!$order) {
            $error = 'No order found with that order number and email. Please double-check and try again.';
        }
    }
}

// If logged in, also show their recent orders
$recentOrders = [];
if (CustomerAuth::isLoggedIn()) {
    $user = CustomerAuth::getUser();
    $recentOrders = db()->fetchAll(
        "SELECT * FROM orders WHERE customer_id = :cid ORDER BY created_at DESC LIMIT 5",
        ['cid' => $user['customer_id']]
    );
}

$statusSteps = ['pending','confirmed','processing','shipped','delivered'];
$statusLabels = [
    'pending'    => 'Order Received',
    'confirmed'  => 'Confirmed',
    'processing' => 'Roasting & Packing',
    'shipped'    => 'Shipped',
    'delivered'  => 'Delivered',
];
$statusIcons = [
    'pending'    => '📋',
    'confirmed'  => '✅',
    'processing' => '☕',
    'shipped'    => '🚚',
    'delivered'  => '🏠',
];
?>

<section class="section" style="padding-top: 2rem; padding-bottom: 4rem;">
    <div class="container" style="max-width: 700px;">

        <div style="text-align: center; margin-bottom: 2.5rem;">
            <h1 style="font-size: 2.5rem; margin-bottom: 0.75rem;">Track Your Order</h1>
            <p style="color: var(--text-muted); font-size: 1.1rem;">Enter your order number and email to see your order status.</p>
        </div>

        <!-- Lookup Form -->
        <div class="card" style="margin-bottom: 2rem;">
            <div class="card-body">
                <form method="POST" action="/track-order.php">
                    <div style="display: grid; gap: 1rem; grid-template-columns: 1fr 1fr; margin-bottom: 1rem;">
                        <div>
                            <label style="display: block; font-weight: 600; margin-bottom: 0.4rem; font-size: 0.9rem;">Order Number</label>
                            <input type="text" name="order_number" placeholder="e.g. TJJ-12345"
                                value="<?= htmlspecialchars($_POST['order_number'] ?? $prefillOrder) ?>"
                                style="width: 100%; padding: 0.7rem 0.9rem; border: 1px solid var(--border); border-radius: 6px; font-size: 1rem; background: var(--bg); color: var(--text); box-sizing: border-box;"
                                required>
                        </div>
                        <div>
                            <label style="display: block; font-weight: 600; margin-bottom: 0.4rem; font-size: 0.9rem;">Email Address</label>
                            <input type="email" name="email" placeholder="you@example.com"
                                value="<?= htmlspecialchars($_POST['email'] ?? $prefillEmail) ?>"
                                style="width: 100%; padding: 0.7rem 0.9rem; border: 1px solid var(--border); border-radius: 6px; font-size: 1rem; background: var(--bg); color: var(--text); box-sizing: border-box;"
                                required>
                        </div>
                    </div>
                    <button type="submit" class="btn btn-primary" style="width: 100%;">Track Order</button>
                </form>
            </div>
        </div>

        <?php if ($error): ?>
        <div style="background: rgba(239,68,68,0.1); border: 1px solid #ef4444; border-radius: 8px; padding: 1rem 1.25rem; color: #ef4444; margin-bottom: 1.5rem;">
            <?= htmlspecialchars($error) ?>
        </div>
        <?php endif; ?>

        <?php if ($order): ?>
        <?php
            $shippingAddress = json_decode($order['shipping_address'], true) ?? [];
            $items = json_decode($order['items'], true) ?? [];
            $currentStep = array_search($order['order_status'], $statusSteps);
            if ($currentStep === false) $currentStep = 0;
            $isCancelled = $order['order_status'] === 'cancelled';
        ?>
        <div class="card" style="margin-bottom: 1.5rem;">
            <div class="card-body">
                <!-- Order Header -->
                <div style="display: flex; justify-content: space-between; align-items: flex-start; flex-wrap: wrap; gap: 0.5rem; margin-bottom: 1.5rem; padding-bottom: 1.25rem; border-bottom: 1px solid var(--border);">
                    <div>
                        <div style="font-size: 0.85rem; color: var(--text-muted); margin-bottom: 0.2rem;">Order Number</div>
                        <div style="font-size: 1.2rem; font-weight: 700;"><?= htmlspecialchars($order['order_number']) ?></div>
                    </div>
                    <div style="text-align: right;">
                        <div style="font-size: 0.85rem; color: var(--text-muted); margin-bottom: 0.2rem;">Placed</div>
                        <div style="font-weight: 600;"><?= date('M j, Y', strtotime($order['created_at'])) ?></div>
                    </div>
                </div>

                <?php if ($isCancelled): ?>
                <div style="text-align: center; padding: 1.5rem; background: rgba(239,68,68,0.08); border-radius: 8px; color: #ef4444; margin-bottom: 1.5rem;">
                    <div style="font-size: 2rem; margin-bottom: 0.5rem;">❌</div>
                    <div style="font-weight: 700; font-size: 1.1rem;">Order Cancelled</div>
                    <div style="font-size: 0.9rem; margin-top: 0.25rem; opacity: 0.8;">If you have questions, please <a href="/contact.php" style="color: #ef4444;">contact us</a>.</div>
                </div>
                <?php else: ?>
                <!-- Progress Steps -->
                <div style="margin-bottom: 1.75rem;">
                    <div style="display: flex; justify-content: space-between; position: relative; margin-bottom: 0.5rem;">
                        <!-- Progress bar background -->
                        <div style="position: absolute; top: 20px; left: 10%; right: 10%; height: 3px; background: var(--border); z-index: 0;"></div>
                        <!-- Progress bar fill -->
                        <div style="position: absolute; top: 20px; left: 10%; height: 3px; background: var(--primary); z-index: 1; width: <?= min(100, ($currentStep / (count($statusSteps) - 1)) * 100) ?>%; transition: width 0.5s;"></div>

                        <?php foreach ($statusSteps as $i => $step): ?>
                        <?php $done = $i <= $currentStep; $active = $i === $currentStep; ?>
                        <div style="display: flex; flex-direction: column; align-items: center; flex: 1; position: relative; z-index: 2;">
                            <div style="width: 40px; height: 40px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 1.1rem;
                                background: <?= $done ? 'var(--primary)' : 'var(--bg-secondary)' ?>;
                                border: 2px solid <?= $done ? 'var(--primary)' : 'var(--border)' ?>;
                                box-shadow: <?= $active ? '0 0 0 4px rgba(255,94,26,0.2)' : 'none' ?>;">
                                <?= $done ? '✓' : $statusIcons[$step] ?>
                            </div>
                            <div style="font-size: 0.72rem; font-weight: <?= $active ? '700' : '500' ?>; color: <?= $done ? 'var(--primary)' : 'var(--text-muted)' ?>; text-align: center; margin-top: 0.4rem; line-height: 1.3;">
                                <?= $statusLabels[$step] ?>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Tracking Number -->
                <?php if ($order['tracking_number']): ?>
                <div style="background: var(--bg-secondary); border-radius: 8px; padding: 1rem 1.25rem; margin-bottom: 1.25rem; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 0.75rem;">
                    <div>
                        <div style="font-size: 0.82rem; color: var(--text-muted); margin-bottom: 0.2rem;">Tracking Number</div>
                        <div style="font-weight: 700; font-size: 1rem;"><?= htmlspecialchars($order['tracking_number']) ?></div>
                    </div>
                    <?php if ($order['tracking_url']): ?>
                    <a href="<?= htmlspecialchars($order['tracking_url']) ?>" target="_blank" rel="noopener" class="btn btn-primary" style="padding: 0.5rem 1.25rem; font-size: 0.9rem;">
                        Track Shipment →
                    </a>
                    <?php endif; ?>
                </div>
                <?php elseif ($order['order_status'] !== 'shipped' && $order['order_status'] !== 'delivered'): ?>
                <div style="background: var(--bg-secondary); border-radius: 8px; padding: 1rem 1.25rem; margin-bottom: 1.25rem; color: var(--text-muted); font-size: 0.9rem;">
                    🔔 A tracking number will be emailed to you once your order ships.
                </div>
                <?php endif; ?>

                <!-- Order Items -->
                <div style="margin-bottom: 1.25rem;">
                    <div style="font-weight: 600; margin-bottom: 0.75rem;">Items Ordered</div>
                    <div style="display: flex; flex-direction: column; gap: 0.6rem;">
                        <?php foreach ($items as $item): ?>
                        <div style="display: flex; justify-content: space-between; padding: 0.6rem 0; border-bottom: 1px solid var(--border); font-size: 0.95rem;">
                            <span><?= htmlspecialchars($item['name'] ?? 'Item') ?> <?php if (!empty($item['quantity'])): ?><span style="color: var(--text-muted);">× <?= (int)$item['quantity'] ?></span><?php endif; ?></span>
                            <span style="font-weight: 600;">$<?= number_format(($item['price'] ?? 0) * ($item['quantity'] ?? 1), 2) ?></span>
                        </div>
                        <?php endforeach; ?>
                        <div style="display: flex; justify-content: space-between; padding-top: 0.5rem; font-weight: 700; font-size: 1.05rem;">
                            <span>Total</span>
                            <span style="color: var(--primary);">$<?= number_format($order['total'], 2) ?></span>
                        </div>
                    </div>
                </div>

                <!-- Shipping Address -->
                <?php if (!empty($shippingAddress)): ?>
                <div style="font-size: 0.9rem; color: var(--text-muted); padding-top: 1rem; border-top: 1px solid var(--border);">
                    <strong style="color: var(--text);">Shipping to:</strong>
                    <?= htmlspecialchars($shippingAddress['name'] ?? '') ?>,
                    <?= htmlspecialchars($shippingAddress['address'] ?? $shippingAddress['line1'] ?? '') ?>,
                    <?= htmlspecialchars($shippingAddress['city'] ?? '') ?>,
                    <?= htmlspecialchars($shippingAddress['state'] ?? '') ?>
                    <?= htmlspecialchars($shippingAddress['zip'] ?? $shippingAddress['postal_code'] ?? '') ?>
                </div>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>

        <!-- Recent Orders (logged-in users) -->
        <?php if (!empty($recentOrders) && !$order): ?>
        <div class="card">
            <div class="card-body">
                <h2 style="font-size: 1.15rem; margin-bottom: 1rem;">Your Recent Orders</h2>
                <div style="display: flex; flex-direction: column; gap: 0.6rem;">
                    <?php foreach ($recentOrders as $ro): ?>
                    <div style="display: flex; justify-content: space-between; align-items: center; padding: 0.85rem 1rem; background: var(--bg-secondary); border-radius: 8px; flex-wrap: wrap; gap: 0.5rem;">
                        <div>
                            <div style="font-weight: 600; font-size: 0.95rem;"><?= htmlspecialchars($ro['order_number']) ?></div>
                            <div style="font-size: 0.82rem; color: var(--text-muted);"><?= date('M j, Y', strtotime($ro['created_at'])) ?> · $<?= number_format($ro['total'], 2) ?></div>
                        </div>
                        <div style="display: flex; align-items: center; gap: 0.75rem;">
                            <span style="padding: 0.3rem 0.75rem; border-radius: 20px; font-size: 0.8rem; font-weight: 600;
                                background: <?= $ro['order_status'] === 'delivered' ? 'rgba(16,185,129,0.15)' : 'rgba(255,94,26,0.15)' ?>;
                                color: <?= $ro['order_status'] === 'delivered' ? '#10b981' : 'var(--primary)' ?>;">
                                <?= ucfirst($ro['order_status']) ?>
                            </span>
                            <form method="POST" action="/track-order.php" style="margin: 0;">
                                <input type="hidden" name="order_number" value="<?= htmlspecialchars($ro['order_number']) ?>">
                                <input type="hidden" name="email" value="<?= htmlspecialchars($ro['customer_email']) ?>">
                                <button type="submit" style="background: none; border: none; color: var(--primary); font-weight: 600; cursor: pointer; font-size: 0.88rem; padding: 0;">View →</button>
                            </form>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <?php if (!$order && !$searched): ?>
        <p style="text-align: center; color: var(--text-muted); margin-top: 1.5rem; font-size: 0.9rem;">
            Can't find your order? <a href="/contact.php">Contact us</a> and we'll look it up for you.
        </p>
        <?php endif; ?>

    </div>
</section>

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