<?php

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../lang.php';

$pageTitle = 'admin_panel';

// ─────────────────────────────────────────────
// LOGIN CHECK
// ─────────────────────────────────────────────
if (!isAdmin()) {
    redirect('login.php');
}

$db = getDB();

$tab = $_GET['tab'] ?? 'menu';

$msg = '';

// ─────────────────────────────────────────────
// UPLOADS FOLDER
// ─────────────────────────────────────────────
$uploadDir = __DIR__ . '/../uploads/';

if (!file_exists($uploadDir)) {
    mkdir($uploadDir, 0777, true);
}

// ─────────────────────────────────────────────
// HANDLE ACTIONS
// ─────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $action = $_POST['action'] ?? '';

    // ─────────────────────────
    // ADD ITEM
    // ─────────────────────────
    if ($action === 'add_item') {

        $name  = trim($_POST['name']);
        $price = (float)$_POST['price'];

        $imagePath = null;

        // IMAGE UPLOAD
        if (!empty($_FILES['image']['name'])) {

            $ext = strtolower(
                pathinfo(
                    $_FILES['image']['name'],
                    PATHINFO_EXTENSION
                )
            );

            $allowed = ['jpg', 'jpeg', 'png', 'webp'];

            if (in_array($ext, $allowed)) {

                $fileName = time() . '_' . rand(1000,9999) . '.' . $ext;

                $target = $uploadDir . $fileName;

                move_uploaded_file(
                    $_FILES['image']['tmp_name'],
                    $target
                );

                $imagePath = 'uploads/' . $fileName;
            }
        }

        if ($name && $price > 0) {

            // CATEGORY
            $cat = $db->query("
                SELECT id
                FROM categories
                LIMIT 1
            ")->fetch();

            if (!$cat) {

                $db->prepare("
                    INSERT INTO categories (name)
                    VALUES (?)
                ")->execute(['Menu']);

                $categoryId = $db->lastInsertId();

            } else {

                $categoryId = $cat['id'];
            }

            // INSERT ITEM
            $stmt = $db->prepare("
                INSERT INTO menu_items
                (
                    category_id,
                    name,
                    description,
                    price,
                    image_url,
                    is_available,
                    is_featured,
                    is_popular
                )
                VALUES
                (
                    ?,
                    ?,
                    '',
                    ?,
                    ?,
                    1,
                    0,
                    0
                )
            ");

            $stmt->execute([
                $categoryId,
                $name,
                $price,
                $imagePath
            ]);

            $msg = 'تم إضافة المنتج بنجاح!';
        }

        header(
            'Location: index.php?tab=menu&msg=' .
            urlencode($msg)
        );

        exit;
    }

    // ─────────────────────────
    // DELETE ITEM
    // ─────────────────────────
    if ($action === 'delete_item') {

        $id = (int)$_POST['id'];

        // GET IMAGE
        $stmt = $db->prepare("
            SELECT image_url
            FROM menu_items
            WHERE id = ?
        ");

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

        $item = $stmt->fetch();

        // DELETE IMAGE
        if ($item && !empty($item['image_url'])) {

            $img = __DIR__ . '/../' . $item['image_url'];

            if (file_exists($img)) {
                unlink($img);
            }
        }

        // DELETE ITEM
        $db->prepare("
            DELETE FROM menu_items
            WHERE id = ?
        ")->execute([$id]);

        $msg = 'تم حذف المنتج.';

        header(
            'Location: index.php?tab=menu&msg=' .
            urlencode($msg)
        );

        exit;
    }

    // ─────────────────────────
    // UPDATE ORDER STATUS
    // ─────────────────────────
    if ($action === 'update_order_status') {

        $id     = (int)$_POST['id'];
        $status = trim($_POST['status']);

        $stmt = $db->prepare("
            UPDATE orders
            SET status = ?
            WHERE id = ?
        ");

        $stmt->execute([
            $status,
            $id
        ]);

        $msg = 'تم تحديث حالة الطلب.';

        header(
            'Location: index.php?tab=orders&msg=' .
            urlencode($msg)
        );

        exit;
    }
}

if (isset($_GET['msg'])) {
    $msg = $_GET['msg'];
}

// ─────────────────────────────────────────────
// DATA
// ─────────────────────────────────────────────
$menuItems = $db->query("
    SELECT *
    FROM menu_items
    ORDER BY id DESC
")->fetchAll();

$orders = $db->query("
    SELECT *
    FROM orders
    WHERE status != 'completed'
    ORDER BY created_at DESC
    LIMIT 100
")->fetchAll();

$reservations = $db->query("
    SELECT *
    FROM reservations
    ORDER BY created_at DESC
    LIMIT 100
")->fetchAll();

$dir = $isRTL ? 'rtl' : 'ltr';

?>

<!DOCTYPE html>

<html lang="<?= $LANG ?>"
      dir="<?= $dir ?>">

<head>

<meta charset="UTF-8">

<meta name="viewport"
      content="width=device-width, initial-scale=1.0">

<title>

  SAVORIA — <?= t('admin_panel') ?>

</title>

<link rel="stylesheet"
      href="../assets/css/style.css">

<style>

.add-box{
    background:var(--card);
    border:1px solid var(--border);
    padding:22px;
    margin-bottom:28px;
    border-radius:20px;
}

.add-box input,
.add-box select{
    width:100%;
    margin-bottom:14px;
    padding:15px;
    background:#111;
    border:1px solid var(--border);
    color:#fff;
    border-radius:12px;
    outline:none;
}

.menu-grid{
    display:grid;
    grid-template-columns:repeat(auto-fit,minmax(260px,1fr));
    gap:22px;
}

.menu-card{
    background:var(--card);
    border:1px solid var(--border);
    border-radius:20px;
    overflow:hidden;
    transition:.3s;
}

.menu-card:hover{
    transform:translateY(-5px);
}

.menu-card img{
    width:100%;
    height:240px;
    object-fit:cover;
}

.menu-content{
    padding:18px;
}

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

.menu-price{
    color:var(--primary);
    font-size:20px;
    margin-bottom:16px;
}

.admin-table{
    width:100%;
    border-collapse:collapse;
}

.admin-table th,
.admin-table td{
    padding:14px;
    border-bottom:1px solid var(--border);
    text-align:left;
}

.order-items{
    margin-top:8px;
    font-size:13px;
    color:var(--fg40);
    line-height:1.7;
}

.status-select{
    padding:8px 10px;
    background:#111;
    border:1px solid var(--border);
    color:#fff;
    border-radius:10px;
}

</style>

</head>

<body>

<!-- NAV -->
<nav class="nav scrolled">

  <div class="container nav-inner">

    <a href="../index.php"
       class="nav-logo">

       SAVORIA

    </a>

    <span style="
      font-size:11px;
      letter-spacing:.2em;
      text-transform:uppercase;
      color:var(--primary)
    ">

      <?= t('admin_panel') ?>

    </span>

    <div class="nav-right">

      <a href="?lang=<?= $LANG === 'en' ? 'ar' : 'en' ?>"
         class="lang-btn">

         <?= $LANG === 'en' ? 'عربي' : 'EN' ?>

      </a>

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

         <?= t('logout') ?>

      </a>

    </div>

  </div>

</nav>

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

  <div class="container">

    <!-- TITLE -->
    <h1 style="
      font-family:var(--font-serif);
      font-size:2.7rem;
      padding:36px 0 30px
    ">

      <?= t('admin_panel') ?>

    </h1>

    <!-- ALERT -->
    <?php if ($msg): ?>

    <div class="alert alert-success">

      <?= e($msg) ?>

    </div>

    <?php endif; ?>

    <!-- TABS -->
    <div class="admin-tabs">

      <a href="?tab=menu"
         class="admin-tab <?= $tab === 'menu' ? 'active' : '' ?>">

         MENU
         (<?= count($menuItems) ?>)

      </a>

      <a href="?tab=orders"
         class="admin-tab <?= $tab === 'orders' ? 'active' : '' ?>">

         ORDERS
         (<?= count($orders) ?>)

      </a>

      <a href="?tab=reservations"
         class="admin-tab <?= $tab === 'reservations' ? 'active' : '' ?>">

         RESERVATIONS
         (<?= count($reservations) ?>)

      </a>

    </div>

    <!-- MENU -->
    <?php if ($tab === 'menu'): ?>

    <!-- ADD ITEM -->
    <div class="add-box">

      <form method="POST"
            enctype="multipart/form-data">

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

        <input type="text"
               name="name"
               placeholder="اسم المنتج"
               required>

        <input type="number"
               step="0.01"
               name="price"
               placeholder="السعر"
               required>

        <input type="file"
               name="image"
               accept="image/*"
               required>

        <button type="submit"
                class="btn btn-primary"
                style="width:100%">

          إضافة المنتج

        </button>

      </form>

    </div>

    <!-- MENU ITEMS -->
    <div class="menu-grid">

      <?php foreach ($menuItems as $item): ?>

      <div class="menu-card">

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

        <div class="menu-content">

          <div class="menu-title">

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

          </div>

          <div class="menu-price">

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

          </div>

          <form method="POST">

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

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

            <button type="submit"
                    class="btn btn-danger"
                    style="width:100%">

              حذف المنتج

            </button>

          </form>

        </div>

      </div>

      <?php endforeach; ?>

    </div>

    <!-- ORDERS -->
    <?php elseif ($tab === 'orders'): ?>

    <div style="overflow-x:auto">

      <table class="admin-table">

        <thead>

          <tr>

            <th>#</th>
            <th>العميل</th>
            <th>الطلب</th>
            <th>الإجمالي</th>
            <th>الحالة</th>
            <th>التاريخ</th>

          </tr>

        </thead>

        <tbody>

          <?php foreach ($orders as $ord): ?>

          <?php

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

          $stmt->execute([$ord['id']]);

          $orderItems = $stmt->fetchAll();

          ?>

          <tr>

            <td>

              #<?= $ord['id'] ?>

            </td>

            <td>

              <div>
                <?= e($ord['customer_name']) ?>
              </div>

              <div style="
                font-size:11px;
                color:var(--fg40)
              ">
                <?= e($ord['customer_phone']) ?>
              </div>

            </td>

            <td>

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

              <div class="order-items">

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

                × <?= $oi['quantity'] ?>

              </div>

              <?php endforeach; ?>

            </td>

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

              $<?= number_format($ord['total'], 2) ?>

            </td>

            <td>

              <form method="POST">

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

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

                <select name="status"
                        class="status-select"
                        onchange="this.form.submit()">

                  <option value="pending"
                    <?= $ord['status'] === 'pending' ? 'selected' : '' ?>>
                    Pending
                  </option>

                  <option value="preparing"
                    <?= $ord['status'] === 'preparing' ? 'selected' : '' ?>>
                    Preparing
                  </option>

                  <option value="on_the_way"
                    <?= $ord['status'] === 'on_the_way' ? 'selected' : '' ?>>
                    On The Way
                  </option>

                  <option value="completed"
                    <?= $ord['status'] === 'completed' ? 'selected' : '' ?>>
                    Completed
                  </option>

                </select>

              </form>

            </td>

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

              <?= date(
                  'd M, H:i',
                  strtotime($ord['created_at'])
              ) ?>

            </td>

          </tr>

          <?php endforeach; ?>

        </tbody>

      </table>

    </div>

    <!-- RESERVATIONS -->
    <?php elseif ($tab === 'reservations'): ?>

    <div style="overflow-x:auto">

      <table class="admin-table">

        <thead>

          <tr>

            <th><?= t('customer_lbl') ?></th>
            <th><?= t('guests_lbl') ?></th>
            <th><?= t('date_lbl') ?></th>
            <th><?= t('time_lbl') ?></th>

          </tr>

        </thead>

        <tbody>

          <?php foreach ($reservations as $r): ?>

          <tr>

            <td>

              <div>
                <?= e($r['customer_name']) ?>
              </div>

              <div style="
                font-size:11px;
                color:var(--fg40)
              ">
                <?= e($r['customer_phone']) ?>
              </div>

            </td>

            <td><?= $r['party_size'] ?></td>
            <td><?= e($r['date']) ?></td>
            <td><?= e($r['time']) ?></td>

          </tr>

          <?php endforeach; ?>

        </tbody>

      </table>

    </div>

    <?php endif; ?>

  </div>

</div>

</body>

</html>