<?php
/**
 * ============================================================
 * ORDER TRACKING PAGE
 * ============================================================
 */

require_once APP_PATH . '/services/order_service.php';

$orderNo = sanitize($_GET['order'] ?? '');
$order = null;
$orderItems = [];
$statusHistory = [];

if ($orderNo) {
    // Get order - allow viewing if logged in and owns order, or by order number lookup
    if (isLoggedIn()) {
        $order = Database::fetchOne(
            "SELECT o.*, u.full_name as user_name FROM orders o 
             JOIN users u ON o.user_id = u.id 
             WHERE o.order_no = ? AND o.user_id = ?",
            [$orderNo, getUserId()]
        );
    }
    
    if ($order) {
        $orderItems = Database::fetchAll(
            "SELECT oi.*, p.name as product_name, 
                    (SELECT file_path FROM product_images WHERE product_id = oi.product_id AND is_primary = 1 LIMIT 1) as image
             FROM order_items oi
             JOIN products p ON oi.product_id = p.id
             WHERE oi.order_id = ?",
            [$order['id']]
        );
        
        $statusHistory = Database::fetchAll(
            "SELECT osh.*, a.full_name as admin_name 
             FROM order_status_history osh
             LEFT JOIN admins a ON osh.changed_by_admin_id = a.id
             WHERE osh.order_id = ?
             ORDER BY osh.created_at DESC",
            [$order['id']]
        );
    }
}

$pageTitle = $order ? 'অর্ডার #' . $order['order_no'] : 'অর্ডার ট্র্যাক';

include PUBLIC_PATH . '/includes/head.php';
include PUBLIC_PATH . '/includes/navbar.php';
?>

<main class="py-4">
    <div class="container">
        <nav aria-label="breadcrumb" class="mb-4">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="<?= url('public/') ?>">হোম</a></li>
                <li class="breadcrumb-item active">অর্ডার ট্র্যাক</li>
            </ol>
        </nav>
        
        <?php if (!$order): ?>
        <!-- Search Form -->
        <div class="row justify-content-center">
            <div class="col-md-6">
                <div class="bg-white rounded shadow-sm p-4">
                    <h4 class="mb-4 text-center">অর্ডার ট্র্যাক করুন</h4>
                    <?php if ($orderNo): ?>
                    <div class="alert alert-warning">
                        অর্ডার পাওয়া যায়নি। লগইন করে আবার চেষ্টা করুন।
                    </div>
                    <?php endif; ?>
                    <form method="GET" action="">
                        <input type="hidden" name="page" value="track-order">
                        <div class="mb-3">
                            <label class="form-label">অর্ডার নম্বর</label>
                            <input type="text" class="form-control" name="order" placeholder="যেমন: ORD-20240101-XXXXX" required>
                        </div>
                        <button type="submit" class="btn btn-primary w-100">ট্র্যাক করুন</button>
                    </form>
                    <?php if (!isLoggedIn()): ?>
                    <p class="text-center text-muted mt-3 mb-0">
                        <a href="<?= url('public/?page=login') ?>">লগইন করুন</a> আপনার সব অর্ডার দেখতে
                    </p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php else: ?>
        
        <h2 class="mb-4">অর্ডার #<?= sanitize($order['order_no']) ?></h2>
        
        <div class="row g-4">
            <div class="col-lg-8">
                <!-- Status Timeline -->
                <div class="bg-white rounded shadow-sm p-4 mb-4">
                    <h5 class="mb-4">অর্ডার স্ট্যাটাস</h5>
                    <div class="order-timeline">
                        <?php 
                        $statuses = ['Pending', 'Processing', 'Shipped', 'Delivered'];
                        $currentIndex = array_search($order['status'], $statuses);
                        if ($order['status'] === 'Cancelled') $currentIndex = -1;
                        ?>
                        
                        <?php foreach ($statuses as $index => $status): ?>
                        <div class="timeline-step <?= $index <= $currentIndex ? 'completed' : '' ?> <?= $index === $currentIndex ? 'current' : '' ?>">
                            <div class="timeline-icon">
                                <?php if ($index < $currentIndex): ?>
                                <i class="bi bi-check"></i>
                                <?php elseif ($index === $currentIndex): ?>
                                <i class="bi bi-circle-fill"></i>
                                <?php else: ?>
                                <i class="bi bi-circle"></i>
                                <?php endif; ?>
                            </div>
                            <div class="timeline-content">
                                <strong><?= $status ?></strong>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    
                    <?php if ($order['status'] === 'Cancelled'): ?>
                    <div class="alert alert-danger mt-3 mb-0">
                        <i class="bi bi-x-circle me-2"></i>এই অর্ডার বাতিল করা হয়েছে।
                    </div>
                    <?php endif; ?>
                </div>
                
                <!-- Order Items -->
                <div class="bg-white rounded shadow-sm p-4">
                    <h5 class="mb-3">অর্ডার আইটেম</h5>
                    <?php foreach ($orderItems as $item): ?>
                    <div class="d-flex align-items-center border-bottom py-3">
                        <img src="<?= $item['image'] ? UPLOADS_URL . '/products/' . $item['image'] : asset('img/no-image.png') ?>" 
                             alt="" class="rounded me-3" width="60" height="60" style="object-fit: cover;">
                        <div class="flex-grow-1">
                            <strong><?= sanitize($item['product_name']) ?></strong>
                            <small class="d-block text-muted"><?= $item['qty'] ?> × <?= formatPrice($item['unit_price']) ?></small>
                        </div>
                        <strong><?= formatPrice($item['line_total']) ?></strong>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            
            <div class="col-lg-4">
                <!-- Order Summary -->
                <div class="bg-white rounded shadow-sm p-4 mb-4">
                    <h5 class="mb-3">অর্ডার সামারি</h5>
                    <p class="mb-2"><strong>তারিখ:</strong> <?= formatDateTime($order['created_at']) ?></p>
                    <p class="mb-2"><strong>পেমেন্ট:</strong> <?= $order['payment_method'] ?></p>
                    <p class="mb-2">
                        <strong>পেমেন্ট স্ট্যাটাস:</strong> 
                        <span class="badge <?= getPaymentStatusBadge($order['payment_status']) ?>"><?= $order['payment_status'] ?></span>
                    </p>
                    <hr>
                    <p class="mb-2">সাবটোটাল: <?= formatPrice($order['subtotal']) ?></p>
                    <p class="mb-2">ভ্যাট: <?= formatPrice($order['vat_amount']) ?></p>
                    <?php if ($order['discount_amount'] > 0): ?>
                    <p class="mb-2 text-success">ছাড়: -<?= formatPrice($order['discount_amount']) ?></p>
                    <?php endif; ?>
                    <p class="mb-0 fs-5"><strong>মোট: <?= formatPrice($order['grand_total']) ?></strong></p>
                </div>
                
                <!-- Shipping Address -->
                <div class="bg-white rounded shadow-sm p-4">
                    <h5 class="mb-3">শিপিং ঠিকানা</h5>
                    <p class="mb-1"><strong><?= sanitize($order['shipping_name']) ?></strong></p>
                    <p class="mb-1"><?= sanitize($order['shipping_phone']) ?></p>
                    <p class="mb-0"><?= sanitize($order['shipping_address']) ?>, <?= sanitize($order['shipping_city']) ?></p>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
</main>

<style>
.order-timeline { display: flex; justify-content: space-between; }
.timeline-step { flex: 1; text-align: center; position: relative; }
.timeline-step::before { content: ''; position: absolute; top: 15px; left: 0; right: 50%; height: 2px; background: #dee2e6; }
.timeline-step::after { content: ''; position: absolute; top: 15px; left: 50%; right: 0; height: 2px; background: #dee2e6; }
.timeline-step:first-child::before, .timeline-step:last-child::after { display: none; }
.timeline-step.completed::before, .timeline-step.completed::after { background: var(--bs-success); }
.timeline-icon { width: 32px; height: 32px; border-radius: 50%; background: #dee2e6; display: inline-flex; align-items: center; justify-content: center; position: relative; z-index: 1; }
.timeline-step.completed .timeline-icon { background: var(--bs-success); color: #fff; }
.timeline-step.current .timeline-icon { background: var(--bs-primary); color: #fff; }
</style>

<?php include PUBLIC_PATH . '/includes/footer.php'; ?>
