<?php
/**
 * Public Order Tracking Page
 * Shows tracking timeline visible to anyone with the tracking link/QR
 */
$statusOrder = ['pending','waiting_payment','paid','preparing','shipping','delivered','completed'];
$doneStatuses = array_column($history, 'status_key');
$currentStatus = $order['status'];

$stepLabels = [
    'pending'         => ['label' => 'รอยืนยัน',     'icon' => 'clock'],
    'paid'            => ['label' => 'ชำระเงินแล้ว', 'icon' => 'credit-card'],
    'preparing'       => ['label' => 'กำลังเตรียม',  'icon' => 'box-seam'],
    'shipping'        => ['label' => 'กำลังจัดส่ง', 'icon' => 'truck'],
    'delivered'       => ['label' => 'จัดส่งแล้ว',   'icon' => 'check2-all'],
    'completed'       => ['label' => 'สำเร็จ',        'icon' => 'star-fill'],
];
?>
<style>
.track-hero {
    background: linear-gradient(135deg, #0d6efd 0%, #0a4cba 100%);
    padding: 3rem 0 6rem;
    color: white;
}
.track-card {
    margin-top: -4rem;
    border-radius: 20px;
    border: none;
    box-shadow: 0 10px 40px rgba(0,0,0,.12);
}

/* Step tracker */
.steps-wrapper { overflow-x: auto; padding: .5rem 0 1rem; }
.steps { display: flex; align-items: flex-start; gap: 0; min-width: 600px; }
.step { flex: 1; text-align: center; position: relative; }
.step-connector {
    position: absolute; top: 20px; left: 50%; right: -50%;
    height: 3px; background: #dee2e6; z-index: 0;
}
.step:last-child .step-connector { display: none; }
.step-connector.done { background: #0d6efd; }
.step-icon {
    width: 42px; height: 42px; border-radius: 50%;
    background: #dee2e6; color: #aaa;
    display: flex; align-items: center; justify-content: center;
    margin: 0 auto 8px; position: relative; z-index: 1;
    font-size: 1.1rem; font-weight: 700;
    transition: all .3s;
}
.step-icon.done { background: #0d6efd; color: white; box-shadow: 0 0 0 4px rgba(13,110,253,.2); }
.step-icon.active { background: #0d6efd; color: white; box-shadow: 0 0 0 6px rgba(13,110,253,.25), 0 0 15px rgba(13,110,253,.4); animation: pulse 2s infinite; }
.step-icon.cancel { background: #dc3545; color: white; }
@keyframes pulse { 0%,100%{box-shadow:0 0 0 6px rgba(13,110,253,.25)} 50%{box-shadow:0 0 0 10px rgba(13,110,253,.1)} }
.step-label { font-size: .75rem; font-weight: 600; color: #aaa; }
.step-label.done, .step-label.active { color: #0d6efd; }
.step-label.cancel { color: #dc3545; }

/* History timeline */
.timeline { border-left: 3px solid #e9ecef; padding-left: 1.5rem; }
.timeline-item { margin-bottom: 1.25rem; position: relative; }
.timeline-item::before {
    content: ''; position: absolute; left: -1.85rem; top: 5px;
    width: 12px; height: 12px; border-radius: 50%;
    background: #0d6efd; border: 2px solid white;
    box-shadow: 0 0 0 2px #0d6efd;
}
.timeline-item.cancel::before { background: #dc3545; box-shadow: 0 0 0 2px #dc3545; }
</style>

<!-- Hero -->
<div class="track-hero">
    <div class="container text-center">
        <i class="bi bi-truck fs-1 mb-3 d-block"></i>
        <h2 class="fw-bold mb-1">ติดตามพัสดุ</h2>
        <p class="mb-0 opacity-75">Tracking ID: <strong><?= $trackingId ?></strong></p>
    </div>
</div>

<div class="container py-4">
    <div class="card track-card">
        <div class="card-body p-4">

            <!-- Order Summary -->
            <div class="row g-3 mb-4 pb-4 border-bottom">
                <div class="col-md-3">
                    <div class="text-muted small mb-1">หมายเลขออเดอร์</div>
                    <div class="fw-bold">#<?= Security::e($order['order_number']) ?></div>
                </div>
                <div class="col-md-3">
                    <div class="text-muted small mb-1">ร้านค้า</div>
                    <div class="fw-bold"><?= Security::e($order['shop_name']) ?></div>
                </div>
                <div class="col-md-3">
                    <div class="text-muted small mb-1">วันที่สั่งซื้อ</div>
                    <div class="fw-bold"><?= date('d/m/Y H:i', strtotime($order['created_at'])) ?></div>
                </div>
                <div class="col-md-3">
                    <div class="text-muted small mb-1">สถานะ</div>
                    <span class="badge bg-primary rounded-pill px-3 fs-6">
                        <?= Security::e($statusLabels[$currentStatus] ?? $currentStatus) ?>
                    </span>
                </div>
            </div>

            <?php if ($currentStatus === 'cancelled'): ?>
            <!-- Cancelled notice -->
            <div class="alert alert-danger rounded-3 border-0 d-flex align-items-center gap-3">
                <i class="bi bi-x-circle-fill fs-3"></i>
                <div>
                    <strong>คำสั่งซื้อถูกยกเลิก</strong>
                    <?php if (!empty($order['cancel_reason'])): ?>
                        <p class="mb-0 small">เหตุผล: <?= Security::e($order['cancel_reason']) ?></p>
                    <?php endif; ?>
                </div>
            </div>

            <?php else: ?>
            <!-- Step Progress -->
            <h6 class="fw-bold mb-3 text-muted">ความคืบหน้า</h6>
            <div class="steps-wrapper mb-4">
                <div class="steps">
                    <?php
                    $mainSteps = ['pending','preparing','shipping','delivered','completed'];
                    $doneSet = array_flip($doneStatuses);
                    $activeFound = false;
                    foreach ($mainSteps as $idx => $sKey):
                        $isDone = isset($doneSet[$sKey]);
                        $isActive = ($sKey === $currentStatus && !$activeFound);
                        if ($isActive) $activeFound = true;
                        $nextDone = isset($mainSteps[$idx+1]) && isset($doneSet[$mainSteps[$idx+1]]);
                        $iconClass = $isActive ? 'active' : ($isDone ? 'done' : '');
                        $labelClass = $iconClass;
                        $sl = $stepLabels[$sKey] ?? ['label' => $sKey, 'icon' => 'circle'];
                    ?>
                    <div class="step">
                        <span class="step-connector <?= ($isDone && $nextDone) ? 'done' : '' ?>"></span>
                        <div class="step-icon <?= $iconClass ?>">
                            <i class="bi bi-<?= $sl['icon'] ?>"></i>
                        </div>
                        <div class="step-label <?= $labelClass ?>"><?= $sl['label'] ?></div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>

            <!-- Status History Timeline -->
            <h6 class="fw-bold mb-3 text-muted">ประวัติการจัดส่ง</h6>
            <?php if (empty($history)): ?>
                <p class="text-muted small">ยังไม่มีการอัปเดตสถานะ</p>
            <?php else: ?>
            <div class="timeline">
                <?php foreach (array_reverse($history) as $h):
                    $isCancel = ($h['status_key'] === 'cancelled');
                ?>
                <div class="timeline-item <?= $isCancel ? 'cancel' : '' ?>">
                    <strong class="<?= $isCancel ? 'text-danger' : 'text-primary' ?>"><?= Security::e($h['status_name']) ?></strong>
                    <span class="text-muted small ms-2"><?= date('d/m/Y H:i', strtotime($h['event_time'])) ?></span>
                    <?php if (!empty($h['description'])): ?>
                        <p class="mb-0 small text-muted"><?= Security::e($h['description']) ?></p>
                    <?php endif; ?>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>

        </div>
    </div>

    <!-- Back to shop -->
    <div class="text-center mt-4">
        <a href="<?= APP_URL ?>" class="btn btn-outline-primary rounded-pill px-4">
            <i class="bi bi-shop me-1"></i>กลับสู่หน้าร้านค้า
        </a>
    </div>
</div>
