<?php
include('config/constants.php');

// جلب الأصناف والفئات
$cats = [];
$res1 = mysqli_query($conn, "SELECT * FROM tbl_category WHERE active='Yes'");
while ($row = mysqli_fetch_assoc($res1)) $cats[] = $row;

$foods = [];
$res2 = mysqli_query($conn, "SELECT * FROM tbl_food WHERE active='Yes'");
while ($row = mysqli_fetch_assoc($res2)) $foods[] = $row;
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8">
<title>صفحة النادل - طلب جديد</title>
<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@600&display=swap" rel="stylesheet">
<style>
body { background: #f6fafd; font-family: 'Cairo', Arial, sans-serif; margin: 0; }
.header { background:#1976d2; color:#fff; padding: 21px 0 14px 0; font-size: 2.1rem; text-align:center; font-weight: bold; letter-spacing: 1px; box-shadow:0 2px 16px #1976d22a;}
.categories-bar { background:#fff; text-align:center; padding:14px 0 7px 0; position:sticky; top:0; z-index:90; box-shadow:0 3px 15px #e3e3e3;}
.categories-bar button { margin:0 9px 7px 0; background:#1976d2; color:#fff; border:none; padding:9px 30px; border-radius:14px; font-weight:bold; font-size:1.07em; cursor:pointer; transition:background 0.14s;}
.categories-bar button.active, .categories-bar button:hover { background:#1459ad; }
.container { max-width:1200px; margin:38px auto 80px; }
.table-num { font-size:1.22em; font-weight:600; margin-bottom:23px; background:#fff; display:inline-block; border-radius:14px; padding:9px 18px 9px 10px; box-shadow:0 3px 10px #e0f0f3; }
.food-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(225px, 1fr)); gap: 28px; margin-top:18px;}
.food-card { background: #fff; border-radius: 23px; box-shadow: 0 5px 30px #dbe7f350; padding: 20px 9px 14px 9px; text-align: center; transition: box-shadow 0.2s; position:relative; cursor:pointer;}
.food-card:hover { box-shadow: 0 10px 36px #1976d230; }
.food-card img { width: 130px; height: 115px; object-fit:cover; border-radius: 16px; border:2px solid #f0f4f8; box-shadow:0 1px 5px #6b6b6b18;}
.food-title { font-size: 1.25rem; font-weight: 700; margin:14px 0 7px 0;}
.food-price { color: #1976d2; font-size: 1.19rem; margin-bottom: 7px;}
.add-btn { background:#1976d2; color:#fff; border:none; padding:8px 27px; border-radius:10px; font-weight:bold; font-size:1.07em; cursor:pointer; margin-top:9px;}
.add-btn:hover { background:#0d47a1;}
#cart-float-btn {position:fixed;bottom:24px;right:24px;z-index:300;background:#1976d2;color:#fff;padding:17px 23px 15px 23px;border-radius:99px;font-size:2em;box-shadow:0 4px 14px #1976d288;cursor:pointer;border:none;}
.cart-badge {background:#e53935;color:#fff;font-size:0.87em;padding:4px 11px 4px 10px;border-radius:15px;position:absolute;top:1px;left:1px;}
.order-cart-popup {display:none;position:fixed;bottom:90px;right:26px;width:385px;max-width:95vw;background:#fff;border-radius:17px;box-shadow:0 8px 44px #9ea2ad99,0 3px 18px #1976d220;z-index:500;padding:20px 12px 18px 12px;}
.cart-table { width:100%; background:#fcfcfd; border-radius:13px; box-shadow:0 1px 10px #dbe7f32f; margin-bottom:8px;}
.cart-table th, .cart-table td { padding:9px 3px; text-align:center; font-size:1.09em;}
.cart-table th { color:#1976d2; }
.cart-table input { width:54px; text-align:center; border-radius:7px; border:1px solid #e2e8f0; padding:4px;}
.cart-remove { background:#d32f2f; color:#fff; border:none; border-radius:7px; padding:5px 14px; font-size:1em; cursor:pointer;}
.cart-remove:hover { background:#b71c1c;}
.cart-submit { background:#43a047; color:#fff; border:none; border-radius:12px; padding:10px 36px; font-size:1.21em; margin:12px auto 0 auto; display:block; cursor:pointer;}
.cart-submit:disabled { background:#cfcfcf; color:#777; }
#cart-popup-title { font-weight:bold;font-size:1.11em;margin-bottom:10px;text-align:center;letter-spacing:0.5px; }
#cart-total {text-align:left; font-weight:bold; font-size:1.07em; color:#1976d2; margin:12px 0 3px 10px;}
@media (max-width: 700px) {
    .container {padding:0 5px;}
    .food-grid {grid-template-columns: repeat(auto-fit, minmax(164px, 1fr));gap:10px;}
    .food-card img { width:85px; height:70px;}
    .order-cart-popup {width:98vw;max-width:98vw;right:0;}
}
</style>
</head>
<body>
<div class="header">لوحة طلبات النادل</div>
<div class="categories-bar" id="categories-bar">
    <button onclick="filterCategory(0,this)" class="active">جميع الأطعمة</button>
    <?php foreach($cats as $cat): ?>
        <button onclick="filterCategory(<?php echo $cat['id'] ?>,this)"><?php echo htmlspecialchars($cat['title']) ?></button>
    <?php endforeach; ?>
</div>
<div class="container">
    <div class="table-num">
        رقم الطاولة:
        <input type="number" id="table_num" min="1" style="width:70px;font-size:1.1em;border-radius:7px;border:1.2px solid #bcdff5;padding:4px 10px;">
    </div>
    <div class="food-grid" id="food-grid">
        <?php foreach($foods as $f): ?>
        <div class="food-card"
            onclick="addToOrder(<?php echo $f['id'] ?>, '<?php echo htmlspecialchars($f['title'], ENT_QUOTES) ?>', <?php echo $f['price'] ?>, '<?php echo htmlspecialchars($f['image_name'], ENT_QUOTES) ?>')"
            style="cursor:pointer;">

            <img src="images/food/<?php echo htmlspecialchars($f['image_name']); ?>" alt="<?php echo htmlspecialchars($f['title']); ?>">
            <div class="food-title"><?php echo htmlspecialchars($f['title']); ?></div>
            <div class="food-price"><?php echo $f['price']; ?> د.ع</div>
            <button class="add-btn"
                onclick="event.stopPropagation();addToOrder(<?php echo $f['id'] ?>, '<?php echo htmlspecialchars($f['title'], ENT_QUOTES) ?>', <?php echo $f['price'] ?>, '<?php echo htmlspecialchars($f['image_name'], ENT_QUOTES) ?>')">
                إضافة
            </button>
        </div>
        <?php endforeach; ?>
    </div>
</div>

<!-- زر السلة العائم -->
<button id="cart-float-btn" onclick="toggleCart()" title="عرض الطلب">
    🛒
    <span id="cart-badge" class="cart-badge" style="display:none">0</span>
</button>
<!-- نافذة السلة -->
<div class="order-cart-popup" id="cart-popup">
    <div id="cart-popup-title">سلة الطلب</div>
    <table class="cart-table">
        <thead>
            <tr><th>الصورة</th><th>الصنف</th><th>الكمية</th><th>تعديل</th><th>حذف</th></tr>
        </thead>
        <tbody id="cart-tbody"></tbody>
    </table>
    <div id="cart-total"></div>
    <button class="cart-submit" onclick="submitOrder()" id="send-btn">إرسال الطلب</button>
    <div id="order-msg" style="color:green; font-weight:bold; margin-top:8px;text-align:center;"></div>
</div>
<script>
// بيانات الأصناف من PHP
let foodData = <?php echo json_encode($foods); ?>;
// بيانات السلة
let orderCart = {}; // {id: {name, price, qty, image}}
let currentCat = 0;

function renderFoods(list) {
    let grid = document.getElementById('food-grid');
    grid.innerHTML = '';
    for (const f of list) {
        grid.innerHTML += `
        <div class="food-card"
            onclick="addToOrder(${f.id}, '${f.title.replace(/'/g,"\\'")}', ${f.price}, '${f.image_name ? f.image_name : 'no-image.png'}')"
            style="cursor:pointer;">
            <img src="images/food/${f.image_name ? f.image_name : 'no-image.png'}" alt="${f.title}">
            <div class="food-title">${f.title}</div>
            <div class="food-price">${f.price} د.ع</div>
            <button class="add-btn"
                onclick="event.stopPropagation();addToOrder(${f.id}, '${f.title.replace(/'/g,"\\'")}', ${f.price}, '${f.image_name ? f.image_name : 'no-image.png'}')">
                إضافة
            </button>
        </div>`;
    }
}
function filterCategory(catId, btn) {
    currentCat = catId;
    document.querySelectorAll('.categories-bar button').forEach(b=>b.classList.remove('active'));
    if(btn) btn.classList.add('active');
    if (catId==0) renderFoods(foodData);
    else {
        let filtered = foodData.filter(f=>f.category_id == catId);
        renderFoods(filtered);
    }
}
function addToOrder(id, name, price, image) {
    if (!orderCart[id]) {
        orderCart[id] = {name: name, price: price, qty: 1, image: image};
    } else {
        orderCart[id].qty += 1;
    }
    renderCart();
}
function renderCart() {
    const tbody = document.getElementById("cart-tbody");
    let total = 0, cnt=0;
    tbody.innerHTML = '';
    for (const id in orderCart) {
        const item = orderCart[id];
        cnt++;
        total += item.qty * item.price;
        tbody.innerHTML += `
            <tr>
                <td><img src="images/food/${item.image}" style="width:44px;height:44px;border-radius:8px;"></td>
                <td>${item.name}</td>
                <td>
                    <input type="number" min="1" value="${item.qty}" onchange="updateQty(${id}, this.value)">
                </td>
                <td>
                    <button onclick="updateQty(${id}, prompt('أدخل الكمية الجديدة:', ${item.qty}) )">تعديل</button>
                </td>
                <td>
                    <button class="cart-remove" onclick="removeFromCart(${id})">حذف</button>
                </td>
            </tr>
        `;
    }
    document.getElementById('cart-total').innerHTML = "الإجمالي: " + total + " د.ع";
    document.getElementById('cart-badge').textContent = cnt;
    document.getElementById('cart-badge').style.display = cnt>0 ? "inline-block":"none";
}
function updateQty(id, qty) {
    qty = parseInt(qty);
    if (qty > 0) {
        orderCart[id].qty = qty;
    } else {
        delete orderCart[id];
    }
    renderCart();
}
function removeFromCart(id) {
    delete orderCart[id];
    renderCart();
}
function toggleCart() {
    let cart = document.getElementById('cart-popup');
    cart.style.display = (cart.style.display=='none'||cart.style.display=='') ? 'block' : 'none';
}
window.onclick = function(e) {
    let cart = document.getElementById('cart-popup');
    let btn = document.getElementById('cart-float-btn');
    if (cart.style.display=='block' && !cart.contains(e.target) && e.target !== btn) {
        cart.style.display = 'none';
    }
}
function submitOrder() {
    const tableNum = document.getElementById("table_num").value;
    if (!tableNum || isNaN(tableNum) || tableNum < 1) {
        alert("يرجى إدخال رقم الطاولة.");
        return;
    }
    if (Object.keys(orderCart).length == 0) {
        alert("يرجى إضافة صنف واحد على الأقل للطلب.");
        return;
    }
    document.getElementById('send-btn').disabled = true;
    const qtys = {};
    for (const id in orderCart) {
        qtys[id] = orderCart[id].qty;
    }
    let formData = new FormData();
    formData.append('table_num', tableNum);
    for (const id in qtys) {
        formData.append('qty['+id+']', qtys[id]);
    }
    fetch('submit-waiter-order.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.text())
    .then(data => {
        document.getElementById('order-msg').innerHTML = data;
        orderCart = {}; // افرغ السلة بعد الطلب
        renderCart();
        document.getElementById('send-btn').disabled = false;
        setTimeout(()=>{ document.getElementById('order-msg').innerHTML=''; toggleCart(); }, 1500);
    });
}

// تحميل أولي
renderFoods(foodData);
renderCart();

</script>
</body>
</html>
