<?php

$pageTitle = 'complete_order';

require_once 'includes/header.php';

$db = getDB();

// ─────────────────────────────────────────────
// CART SESSION
// ─────────────────────────────────────────────
if (!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = [];
}

// ─────────────────────────────────────────────
// LAST ORDER SESSION
// ─────────────────────────────────────────────
if (!isset($_SESSION['last_order_id'])) {
    $_SESSION['last_order_id'] = 0;
}

// ─────────────────────────────────────────────
// ADD ITEM
// ─────────────────────────────────────────────
if (
    $_SERVER['REQUEST_METHOD'] === 'POST' &&
    ($_POST['action'] ?? '') === 'add'
) {

    $itemId = (int)($_POST['item_id'] ?? 0);

    if ($itemId > 0) {

        $stmt = $db->prepare("
            SELECT *
            FROM menu_items
            WHERE id = ?
            AND is_available = 1
        ");

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

        $menuItem = $stmt->fetch();

        if ($menuItem) {

            $found = false;

            foreach ($_SESSION['cart'] as &$ci) {

                if ($ci['id'] === $itemId) {
                    $ci['quantity']++;
                    $found = true;
                    break;
                }
            }

            unset($ci);

            if (!$found) {

                $_SESSION['cart'][] = [
                    'id'        => $itemId,
                    'name'      => $menuItem['name'],
                    'price'     => (float)$menuItem['price'],
                    'image_url' => $menuItem['image_url'],
                    'quantity'  => 1,
                ];
            }
        }
    }

    header('Location: order.php');
    exit;
}

// ─────────────────────────────────────────────
// UPDATE QUANTITY
// ─────────────────────────────────────────────
if (
    $_SERVER['REQUEST_METHOD'] === 'POST' &&
    ($_POST['action'] ?? '') === 'update'
) {

    $itemId = (int)($_POST['item_id'] ?? 0);
    $qty    = (int)($_POST['quantity'] ?? 0);

    if ($qty <= 0) {

        $_SESSION['cart'] = array_values(
            array_filter(
                $_SESSION['cart'],
                fn($ci) => $ci['id'] !== $itemId
            )
        );

    } else {

        foreach ($_SESSION['cart'] as &$ci) {

            if ($ci['id'] === $itemId) {
                $ci['quantity'] = $qty;
                break;
            }
        }

        unset($ci);
    }

    header('Location: order.php');
    exit;
}

// ─────────────────────────────────────────────
// REMOVE ITEM
// ─────────────────────────────────────────────
if (isset($_GET['remove'])) {

    $removeId = (int)$_GET['remove'];

    $_SESSION['cart'] = array_values(
        array_filter(
            $_SESSION['cart'],
            fn($ci) => $ci['id'] !== $removeId
        )
    );

    header('Location: order.php');
    exit;
}

// ─────────────────────────────────────────────
// CANCEL ORDER
// ─────────────────────────────────────────────
if (isset($_GET['cancel_order'])) {

    $orderId = (int)$_GET['cancel_order'];

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

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

    $order = $stmt->fetch();

    if ($order) {

        // DELETE ITEMS
        $stmt = $db->prepare("
            DELETE FROM order_items
            WHERE order_id = ?
        ");

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

        // DELETE ORDER
        $stmt = $db->prepare("
            DELETE FROM orders
            WHERE id = ?
        ");

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

        $_SESSION['last_order_id'] = 0;
    }

    header('Location: order.php');
    exit;
}

// ─────────────────────────────────────────────
// PLACE ORDER
// ─────────────────────────────────────────────
if (
    $_SERVER['REQUEST_METHOD'] === 'POST' &&
    ($_POST['action'] ?? '') === 'place'
) {

    if (empty($_SESSION['cart'])) {

        header('Location: order.php');
        exit;
    }

    $customerName    = trim($_POST['customer_name'] ?? '');
    $customerPhone   = trim($_POST['customer_phone'] ?? '');
    $deliveryAddress = trim($_POST['delivery_address'] ?? '');
    $notes           = trim($_POST['notes'] ?? '');

    $cart = $_SESSION['cart'];

    // SUBTOTAL
    $subtotal = array_sum(
        array_map(
            fn($ci) => $ci['price'] * $ci['quantity'],
            $cart
        )
    );

    // DELIVERY
    $deliveryFee =
        $subtotal >= FREE_DELIVERY_THRESHOLD
        ? 0
        : DELIVERY_FEE;

    // TAX
    $taxes = ($subtotal + $deliveryFee) * TAX_RATE;

    // TOTAL
    $grandTotal = $subtotal + $deliveryFee + $taxes;

    // SAVE ORDER
    $stmt = $db->prepare("
        INSERT INTO orders
        (
            customer_name,
            customer_phone,
            order_type,
            delivery_address,
            delivery_fee,
            total,
            status,
            notes
        )
        VALUES
        (
            ?,
            ?,
            'delivery',
            ?,
            ?,
            ?,
            'pending',
            ?
        )
    ");

    $stmt->execute([
        $customerName,
        $customerPhone,
        $deliveryAddress,
        $deliveryFee,
        $grandTotal,
        $notes
    ]);

    $orderId = $db->lastInsertId();

    // SAVE LAST ORDER
    $_SESSION['last_order_id'] = $orderId;

    // SAVE ORDER ITEMS
    foreach ($cart as $ci) {

        $stmt = $db->prepare("
            INSERT INTO order_items
            (
                order_id,
                menu_item_id,
                menu_item_name,
                quantity,
                unit_price,
                subtotal
            )
            VALUES
            (
                ?,
                ?,
                ?,
                ?,
                ?,
                ?
            )
        ");

        $stmt->execute([
            $orderId,
            $ci['id'],
            $ci['name'],
            $ci['quantity'],
            $ci['price'],
            $ci['price'] * $ci['quantity']
        ]);
    }

    // CLEAR CART
    $_SESSION['cart'] = [];

    // SUCCESS
    header('Location: order.php?success=1');
    exit;
}

// ─────────────────────────────────────────────
// GET LAST ORDER
// ─────────────────────────────────────────────
$lastOrder = null;

if ($_SESSION['last_order_id']) {

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

    $stmt->execute([
        $_SESSION['last_order_id']
    ]);

    $lastOrder = $stmt->fetch();
}

// ─────────────────────────────────────────────
// TOTALS
// ─────────────────────────────────────────────
$cart = $_SESSION['cart'];

$subtotal = array_sum(
    array_map(
        fn($ci) => $ci['price'] * $ci['quantity'],
        $cart
    )
);

$selectedOrderType =
    $_POST['order_type'] ?? 'delivery';

$deliveryFee =
    $selectedOrderType === 'delivery'
    ? ($subtotal >= FREE_DELIVERY_THRESHOLD ? 0 : DELIVERY_FEE)
    : 0;

$taxes = ($subtotal + $deliveryFee) * TAX_RATE;

$grandTotal = $subtotal + $deliveryFee + $taxes;

?>

<style>

.order-status-box{
    background:linear-gradient(135deg,#101010,#181818);
    border:1px solid rgba(255,255,255,.08);
    border-radius:34px;
    padding:34px;
    margin:35px 0;
    overflow:hidden;
    position:relative;
    box-shadow:0 20px 50px rgba(0,0,0,.45);
}

.order-status-box::before{
    content:'';
    position:absolute;
    width:320px;
    height:320px;
    border-radius:50%;
    background:rgba(255,255,255,.03);
    top:-120px;
    right:-120px;
}

.status-title{
    font-size:34px;
    font-family:var(--font-serif);
    margin-bottom:12px;
}

.status-sub{
    color:var(--fg40);
    margin-bottom:22px;
    font-size:14px;
}

.status-badge{
    display:inline-flex;
    align-items:center;
    gap:12px;
    padding:15px 26px;
    border-radius:999px;
    font-weight:700;
    font-size:15px;
    animation:pulse 2s infinite;
}

.status-pending{
    background:#3a2d08;
    color:#ffd25f;
}

.status-preparing{
    background:#1b2b42;
    color:#8bc4ff;
}

.status-way{
    background:#1f3827;
    color:#7dffac;
}

.status-completed{
    background:#1b3b1f;
    color:#89ff9d;
}

@keyframes pulse{
    0%{transform:scale(1)}
    50%{transform:scale(1.03)}
    100%{transform:scale(1)}
}

.status-track{
    display:flex;
    justify-content:space-between;
    gap:10px;
    margin-top:36px;
    flex-wrap:wrap;
}

.track-step{
    flex:1;
    min-width:120px;
    text-align:center;
    position:relative;
}

.track-circle{
    width:58px;
    height:58px;
    border-radius:50%;
    background:#202020;
    border:2px solid #333;
    display:flex;
    align-items:center;
    justify-content:center;
    margin:auto;
    margin-bottom:14px;
    font-size:24px;
    transition:.4s;
}

.track-active .track-circle{
    background:var(--primary);
    border-color:var(--primary);
    color:#000;
    box-shadow:0 0 35px rgba(255,255,255,.2);
    transform:scale(1.08);
}

.track-label{
    font-size:13px;
    color:#ddd;
}

.order-grid{
    display:grid;
    grid-template-columns:1.2fr .8fr;
    gap:30px;
}

@media(max-width:900px){

.order-grid{
    grid-template-columns:1fr;
}

}

</style>

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

  <div class="container">

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

    <div class="alert alert-success"
         style="margin-top:30px">

      ✅ تم إرسال الطلب بنجاح

    </div>

    <?php endif; ?>

    <!-- ORDER STATUS -->
<?php if ($lastOrder): ?>

<?php

$status = $lastOrder['status'];

$statusClass = 'status-pending';
$statusText  = 'قيد مراجعة الطلب';
$statusIcon  = '🕒';
$step        = 1;

if ($status === 'preparing') {

    $statusClass = 'status-preparing';
    $statusText  = 'جاري تحضير طلبك';
    $statusIcon  = '👨‍🍳';
    $step        = 2;
}

if ($status === 'on_the_way') {

    $statusClass = 'status-way';
    $statusText  = 'الكابتن في الطريق';
    $statusIcon  = '🚚';
    $step        = 3;
}

if ($status === 'completed') {

    $statusClass = 'status-completed';
    $statusText  = 'تم توصيل الطلب';
    $statusIcon  = '✅';
    $step        = 4;
}

?>

<div class="order-status-box">

  <div style="position:relative;z-index:2">

    <div style="
      display:flex;
      justify-content:space-between;
      align-items:center;
      gap:15px;
      flex-wrap:wrap
    ">

      <div>

        <div class="status-title">

          تتبع طلبك #<?= $lastOrder['id'] ?>

        </div>

        <div class="status-sub">

          يمكنك متابعة حالة الطلب مباشرة لحظة بلحظة

        </div>

      </div>

      <!-- DELETE BUTTON -->
      <?php if ($status === 'pending'): ?>

      <a href="order.php?cancel_order=<?= $lastOrder['id'] ?>"
         onclick="return confirm('هل تريد حذف الطلب؟')"
         style="
            background:#ff3b30;
            color:#fff;
            padding:14px 22px;
            border-radius:16px;
            font-weight:700;
            display:flex;
            align-items:center;
            gap:10px;
            box-shadow:0 10px 30px rgba(255,59,48,.25);
            transition:.3s;
         ">

         🗑 حذف الطلب

      </a>

      <?php endif; ?>

    </div>

    <div class="status-badge <?= $statusClass ?>">

      <span><?= $statusIcon ?></span>

      <span><?= $statusText ?></span>

    </div>

    <div class="status-track">

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

        <div class="track-circle">🧾</div>

        <div class="track-label">

          تم استلام الطلب

        </div>

      </div>

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

        <div class="track-circle">👨‍🍳</div>

        <div class="track-label">

          جاري التحضير

        </div>

      </div>

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

        <div class="track-circle">🚚</div>

        <div class="track-label">

          جاري التوصيل

        </div>

      </div>

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

        <div class="track-circle">✅</div>

        <div class="track-label">

          تم التسليم

        </div>

      </div>

    </div>

  </div>

</div>

<?php endif; ?>

    <!-- TITLE -->
    <h1 style="
      font-family:var(--font-serif);
      font-size:2.5rem;
      padding:10px 0 32px
    ">

      <?= t('complete_order') ?>

    </h1>

    <!-- EMPTY CART -->
    <?php if (empty($cart)): ?>

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

      <div style="
        font-size:4rem;
        margin-bottom:20px
      ">
        🛒
      </div>

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

        <?= t('cart_empty') ?>

      </h2>

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

         <?= t('explore_menu') ?>

      </a>

    </div>

    <?php else: ?>

    <!-- ORDER GRID -->
    <div class="order-grid">

      <!-- LEFT -->
      <div>

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

          <?= t('order_items_lbl') ?>
          (<?= count($cart) ?>)

        </div>

        <?php foreach ($cart as $ci): ?>

        <div class="cart-item">

          <img
            class="cart-item-img"

            src="<?= e($ci['image_url'] ?: 'assets/img/food-placeholder.jpg') ?>"

            alt="<?= e($ci['name']) ?>"

            onerror="this.src='assets/img/food-placeholder.jpg'"
          >

          <div style="flex:1">

            <div class="cart-item-name">

              <?= e($ci['name']) ?>

            </div>

            <div class="cart-item-price">

              $<?= number_format($ci['price'], 2) ?>

            </div>

            <div style="
              display:flex;
              align-items:center;
              gap:10px;
              margin-top:8px
            ">

              <form method="POST"
                    action="order.php"
                    style="
                      display:flex;
                      align-items:center;
                      gap:4px
                    ">

                <input type="hidden"
                       name="action"
                       value="update">

                <input type="hidden"
                       name="item_id"
                       value="<?= $ci['id'] ?>">

                <button type="submit"
                        name="quantity"
                        value="<?= $ci['quantity'] - 1 ?>"
                        class="btn btn-outline btn-sm"
                        style="padding:4px 10px">

                  −

                </button>

                <span style="
                  min-width:28px;
                  text-align:center;
                  font-weight:600
                ">

                  <?= $ci['quantity'] ?>

                </span>

                <button type="submit"
                        name="quantity"
                        value="<?= $ci['quantity'] + 1 ?>"
                        class="btn btn-outline btn-sm"
                        style="padding:4px 10px">

                  +

                </button>

              </form>

              <a href="order.php?remove=<?= $ci['id'] ?>"
                 style="
                   color:var(--red);
                   font-size:13px
                 ">

                 ✕

              </a>

              <span style="
                font-size:13px;
                color:var(--primary);
                margin-left:auto
              ">

                $<?= number_format($ci['price'] * $ci['quantity'], 2) ?>

              </span>

            </div>

          </div>

        </div>

        <?php endforeach; ?>

      </div>

      <!-- RIGHT -->
      <div class="sticky-top">

        <div class="card"
             style="padding:28px">

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

            <?= t('guest_details') ?>

          </div>

          <form method="POST"
                action="order.php">

            <input type="hidden"
                   name="action"
                   value="place">

            <div class="form-group">

              <label class="form-label">

                <?= t('full_name') ?>

              </label>

              <input
                class="form-input"
                type="text"
                name="customer_name"
                required
              >

            </div>

            <div class="form-group">

              <label class="form-label">

                <?= t('phone_number') ?>

              </label>

              <input
                class="form-input"
                type="tel"
                name="customer_phone"
                required
              >

            </div>

            <div class="form-group">

              <label class="form-label">

                <?= t('delivery_addr') ?>

              </label>

              <textarea
                class="form-textarea"
                name="delivery_address"
                required
              ></textarea>

            </div>

            <div class="form-group">

              <label class="form-label">

                <?= t('special_req') ?>

              </label>

              <textarea
                class="form-textarea"
                name="notes"
              ></textarea>

            </div>

            <hr class="separator">

            <div class="totals-row">

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

              <span>

                $<?= number_format($subtotal, 2) ?>

              </span>

            </div>

            <div class="totals-row">

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

              <span>

                $<?= number_format($deliveryFee, 2) ?>

              </span>

            </div>

            <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($grandTotal, 2) ?>

              </span>

            </div>

            <button type="submit"
                    class="btn btn-primary"
                    style="
                      width:100%;
                      margin-top:20px;
                      justify-content:center
                    ">

              <?= t('place_order') ?> →

            </button>

          </form>

        </div>

      </div>

    </div>

    <?php endif; ?>

  </div>

</div>

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