<?php

$pageTitle = 'track_title';

require_once 'includes/header.php';

$db = getDB();

$orderId = (int)($_GET['id'] ?? 0);

$order = null;
$orderItems = [];

// ─────────────────────────────────────────────
// Fetch Order
// ─────────────────────────────────────────────
if ($orderId > 0) {

    $stmt = $db->prepare("
        SELECT *
        FROM orders
        WHERE id = ?
    ");

    $stmt->execute([$orderId]);

    $order = $stmt->fetch();

    if ($order) {

        $stmt2 = $db->prepare("
            SELECT *
            FROM order_items
            WHERE order_id = ?
        ");

        $stmt2->execute([$orderId]);

        $orderItems = $stmt2->fetchAll();
    }
}

// ─────────────────────────────────────────────
// Status Map
// ─────────────────────────────────────────────
$statusMap = [

    'pending' => [
        'label_key' => 'st_pending',
        'icon'      => '📋'
    ],

    'confirmed' => [
        'label_key' => 'st_confirmed',
        'icon'      => '✅'
    ],

    'preparing' => [
        'label_key' => 'st_preparing',
        'icon'      => '👨‍🍳'
    ],

    'ready' => [
        'label_key' => 'st_ready',
        'icon'      => '📦'
    ],

    'out-for-delivery' => [
        'label_key' => 'st_out_delivery',
        'icon'      => '🚚'
    ],

    'delivered' => [
        'label_key' => 'st_delivered',
        'icon'      => '🎉'
    ],

];

$allSteps = array_keys($statusMap);

$isDelivery =
    ($order['order_type'] ?? '') === 'delivery';

$visibleSteps = $isDelivery
    ? $allSteps
    : array_filter(
        $allSteps,
        fn($s) => $s !== 'out-for-delivery'
    );

$currentStatus = $order['status'] ?? '';

?>

<div class="pt-page"
     style="padding-bottom:80px;min-height:100vh">

  <div class="container"
       style="max-width:700px">

    <!-- Back -->
    <div style="padding:40px 0 0">

      <a href="index.php"
         style="
           font-size:11px;
           letter-spacing:.15em;
           text-transform:uppercase;
           color:var(--fg40)
         ">

        ← <?= t('backToHome') ?>

      </a>

    </div>

    <!-- Search -->
    <?php if (!$orderId): ?>

    <div style="
      text-align:center;
      padding:80px 0
    ">

      <div style="
        font-size:3rem;
        margin-bottom:16px
      ">
        🔍
      </div>

      <h1 style="
        font-family:var(--font-serif);
        font-size:2.5rem;
        margin-bottom:12px
      ">

        <?= t('track_title') ?>

      </h1>

      <p style="
        color:var(--fg60);
        margin-bottom:32px
      ">

        <?= t('enter_order_id') ?>

      </p>

      <form method="GET"
            action="track.php"
            style="
              display:flex;
              gap:10px;
              max-width:380px;
              margin:0 auto
            ">

        <input
          class="form-input"
          type="number"
          name="id"
          required
          placeholder="<?= $isRTL
              ? 'رقم الطلب'
              : 'Order ID'
          ?>"
          style="
            text-align:center;
            font-size:1.1rem
          "
        >

        <button type="submit"
                class="btn btn-primary"
                style="white-space:nowrap">

          <?= t('track_btn') ?>

        </button>

      </form>

    </div>

    <!-- Order Not Found -->
    <?php elseif (!$order): ?>

    <div style="
      text-align:center;
      padding:80px 0
    ">

      <div style="
        font-size:3rem;
        margin-bottom:16px
      ">
        ❌
      </div>

      <h2 style="
        font-family:var(--font-serif);
        font-size:2rem;
        margin-bottom:12px
      ">

        <?= t('orderNotFound') ?>

      </h2>

      <p style="
        color:var(--fg60);
        margin-bottom:28px
      ">

        <?= t('orderNotFoundDesc') ?>

      </p>

      <a href="track.php"
         class="btn btn-outline">

         <?= t('track_btn') ?>

      </a>

      <a href="menu.php"
         class="btn btn-primary"
         style="margin-left:12px">

         <?= t('back_to_menu') ?>

      </a>

    </div>

    <!-- Order Details -->
    <?php else: ?>

    <!-- Success -->
    <?php if (isset($_GET['new'])): ?>

    <div class="alert alert-success"
         style="
           margin-top:24px;
           font-size:15px
         ">

      🎉
      <?= $isRTL
          ? 'تم تقديم طلبك بنجاح!'
          : 'Your order has been placed successfully!'
      ?>

    </div>

    <?php endif; ?>

    <!-- Header -->
    <div style="
      padding:36px 0 20px
    ">

      <span style="
        font-size:10px;
        letter-spacing:.3em;
        text-transform:uppercase;
        color:var(--primary);
        display:block;
        margin-bottom:6px
      ">

        <?= t('order_status') ?>

      </span>

      <h1 style="
        font-family:var(--font-serif);
        font-size:2.5rem;
        margin-bottom:6px
      ">

        <?= t('order_number') ?>
        <?= $order['id'] ?>

      </h1>

      <span style="
        font-size:12px;
        color:var(--fg40)
      ">

        <?= date(
            'F j, Y - H:i',
            strtotime($order['created_at'])
        ) ?>

      </span>

    </div>

    <!-- Cancelled -->
    <?php if ($currentStatus === 'cancelled'): ?>

    <div class="alert alert-error">

      <?= t('st_cancelled') ?>

    </div>

    <?php else: ?>

    <!-- Steps -->
    <div class="card"
         style="
           padding:28px 32px;
           margin-bottom:16px
         ">

      <?php

      $stepsArray = array_values($visibleSteps);

      $currentIdx =
          array_search(
              $currentStatus,
              $stepsArray
          );

      foreach ($stepsArray as $i => $step):

        $done    = $i <= $currentIdx;
        $current = $i === $currentIdx;

        $info = $statusMap[$step];

        $cls = $done
            ? 'done'
            : ($current ? 'current' : '');

      ?>

      <div class="track-step <?= $done ? 'done' : '' ?>">

        <div class="track-dot <?= $cls ?>">

          <?= $done ? '✓' : $info['icon'] ?>

        </div>

        <div>

          <div class="track-label"
               style="<?= $current
                    ? 'color:var(--primary)'
                    : ($done ? '' : 'color:var(--fg40)')
               ?>">

            <?= t($info['label_key']) ?>

          </div>

        </div>

      </div>

      <?php endforeach; ?>

    </div>

    <?php endif; ?>

    <!-- Address -->
    <?php if (
        $isDelivery &&
        !empty($order['delivery_address'])
    ): ?>

    <div class="card"
         style="
           padding:16px 20px;
           margin-bottom:16px;
           display:flex;
           gap:12px
         ">

      <span style="
        font-size:1.2rem
      ">
        📍
      </span>

      <div>

        <div style="
          font-size:10px;
          letter-spacing:.15em;
          text-transform:uppercase;
          color:var(--fg40);
          margin-bottom:4px
        ">

          <?= t('address_lbl') ?>

        </div>

        <div style="font-size:14px">

          <?= e($order['delivery_address']) ?>

        </div>

      </div>

    </div>

    <?php endif; ?>

    <!-- Summary -->
    <div class="card"
         style="padding:28px 32px">

      <div style="
        font-size:10px;
        font-weight:700;
        letter-spacing:.2em;
        text-transform:uppercase;
        color:var(--primary);
        border-bottom:1px solid var(--border);
        padding-bottom:14px;
        margin-bottom:18px
      ">

        <?= t('order_summary') ?>

      </div>

      <!-- Items -->
      <?php foreach ($orderItems as $oi): ?>

      <div style="
        display:flex;
        justify-content:space-between;
        padding:8px 0;
        border-bottom:1px solid rgba(255,255,255,.04);
        font-size:13px
      ">

        <span>

          <?= e($oi['menu_item_name']) ?>

          <span style="color:var(--fg40)">
            ×<?= $oi['quantity'] ?>
          </span>

        </span>

        <span style="color:var(--primary)">

          $<?= number_format($oi['subtotal'], 2) ?>

        </span>

      </div>

      <?php endforeach; ?>

      <!-- Totals -->
      <?php

      $df = (float)($order['delivery_fee'] ?? 0);

      $taxes = $order['total'] * TAX_RATE;

      ?>

      <div style="
        margin-top:14px;
        font-size:14px
      ">

        <div class="totals-row">

          <span><?= t('subtotal') ?></span>

          <span>
            $<?= number_format($order['total'], 2) ?>
          </span>

        </div>

        <?php if ($isDelivery): ?>

        <div class="totals-row">

          <span><?= t('delivery_fee_row') ?></span>

          <span>

            <?= $df == 0
                ? ($isRTL ? 'مجاني' : 'Free')
                : '$' . number_format($df, 2)
            ?>

          </span>

        </div>

        <?php endif; ?>

        <div class="totals-row">

          <span><?= t('taxes') ?></span>

          <span>
            $<?= number_format($taxes, 2) ?>
          </span>

        </div>

        <div class="totals-final">

          <span><?= t('total_lbl') ?></span>

          <span style="color:var(--primary)">

            $<?= number_format(
                $order['total'] + $df + $taxes,
                2
            ) ?>

          </span>

        </div>

      </div>

      <!-- Customer -->
      <hr class="separator">

      <div style="
        font-size:13px;
        color:var(--fg60)
      ">

        <div style="
          display:flex;
          justify-content:space-between;
          margin-bottom:6px
        ">

          <span><?= t('customer_lbl') ?></span>

          <span style="color:var(--fg)">

            <?= e($order['customer_name']) ?>

          </span>

        </div>

        <div style="
          display:flex;
          justify-content:space-between
        ">

          <span><?= t('phone_lbl') ?></span>

          <span style="color:var(--fg)">

            <?= e($order['customer_phone']) ?>

          </span>

        </div>

      </div>

    </div>

    <!-- Refresh -->
    <div style="
      text-align:center;
      margin-top:24px
    ">

      <p style="
        font-size:12px;
        color:var(--fg40);
        margin-bottom:16px
      ">

        <?= $isRTL
            ? 'يتم تحديث الصفحة كل 30 ثانية.'
            : 'Page refreshes every 30 seconds.'
        ?>

      </p>

      <a href="track.php"
         class="btn btn-outline btn-sm">

         <?= t('track_btn') ?>

      </a>

    </div>

    <?php endif; ?>

  </div>

</div>

<!-- Auto Refresh -->
<script>

<?php if (
    $order &&
    !in_array(
        $currentStatus,
        ['delivered', 'cancelled']
    )
): ?>

setTimeout(() => {
    location.reload();
}, 30000);

<?php endif; ?>

</script>

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