<?php
ob_start();
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(E_ALL);
require_once "includes/auth.php";
ensure_manager();
require_once "includes/functions.php";
$lang = $_SESSION['panel_lang'] ?? 'ar';
$tr   = require __DIR__."/lang/$lang.php";
$restaurant_id = $_SESSION['restaurant_id'];
$role          = $_SESSION['manager_role'] ?? null;

// لغة لوحة التحكم (واجهة المدير)
$panel_lang = $_SESSION['panel_lang'] ?? 'en';

// جلب لغات المطعم الفعّالة
$restaurant_lang_rows = fetch_all("
    SELECT l.code 
    FROM restaurant_languages rl
    JOIN languages l ON l.id = rl.language_id
    WHERE rl.restaurant_id = ? AND rl.active = 1
", [$restaurant_id]);

$languages = $restaurant_lang_rows ? array_column($restaurant_lang_rows, 'code') : ['ar'];

// إذا لغة اللوحة غير مفعّلة للمطعم، رجع لأول لغة متاحة
if (!in_array($panel_lang, $languages)) {
    $panel_lang = $languages[0];
}

// جلب التصنيفات والعناصر
$categories = fetch_all("SELECT * FROM categories WHERE restaurant_id = ? ORDER BY ordering ASC", [$restaurant_id]);
$items      = fetch_all("SELECT * FROM items WHERE restaurant_id = ? ORDER BY ordering ASC", [$restaurant_id]);

// تنظيم العناصر داخل التصنيفات
$cat_items = [];
foreach ($categories as $c) {
    $cat_items[$c['id']] = [];
}
foreach ($items as $i) {
    if (isset($cat_items[$i['category_id']])) {
        $cat_items[$i['category_id']][] = $i;
    }
}

// مساعد لبناء رابط image (يدعم القديم والجديد)
function build_image_url($image, $folder) {
    if (!$image) return "../assets/no-image.png";

    // إجبار أول حرف كبير
    $folder = ucfirst($folder);

    // إذا image مخزنة بطريقة قديمة بمسار كامل
    if (strpos($image, 'uploads/') === 0) {
        return "../" . $image;
    }

    return "../uploads/$folder/" . $image;
}

?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8">
<title>menu_builder (Menu Builder)</title>
<meta name="viewport" content="width=device-width, initial-scale=1">

<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>

<style>
.page-title{
    font-size:26px;
    margin-bottom:20px;
    color:#ff7a00;
}
.top-actions{
    display:flex;
    gap:15px;
    margin-bottom:25px;
}
.btn{
    padding:10px 20px;
    background:#ff7a00;
    color:#000;
    border:none;
    border-radius:8px;
    cursor:pointer;
    font-weight:bold;
}
.btn:hover{ opacity:0.85; }
.btn-dark{
    padding:10px 20px;
    background:#222;
    color:#fff;
    border:none;
    border-radius:8px;
    cursor:pointer;
}
.category-box{
    background:#1c1c1c;
    padding:15px;
    border-radius:10px;
    margin-bottom:20px;
    border:1px solid #333;
}
.category-header{
    display:flex;
    align-items:center;
    gap:15px;
    margin-bottom:10px;
}
.category-header img{
    width:60px;
    height:60px;
    object-fit:cover;
    border-radius:8px;
}
.category-name{
    font-size:20px;
    font-weight:bold;
}
.cat-actions{
    margin-right:auto;
    display:flex;
    gap:8px;
}
.action-btn{
    background:#333;
    color:#fff;
    border:none;
    padding:6px 10px;
    border-radius:6px;
    cursor:pointer;
}
.action-btn:hover{ background:#444; }

.items-list{
    margin-top:10px;
    padding-right:20px;
}
.item-row{
    display:flex;
    align-items:flex-start;
    background:#222;
    padding:10px;
    border-radius:8px;
    margin-bottom:8px;
    gap:12px;
}
.item-row img{
    width:60px;
    height:60px;
    border-radius:6px;
    object-fit:cover;
}
.item-info{
    flex:1;
}
.item-title{
    font-size:15px;
    font-weight:bold;
}
.item-desc{
    font-size:13px;
    opacity:0.8;
    margin-top:4px;
}
.item-price{
    font-size:15px;
    font-weight:bold;
    color:#ff7a00;
    min-width:70px;
    text-align:left;
}
.toggle{
    cursor:pointer;
    font-size:13px;
    padding:4px 10px;
    border-radius:6px;
    margin-inline-start:8px;
}
.toggle.on{ background:#28a745; color:#fff; }
.toggle.off{ background:#a00; color:#fff; }

/************* MODALS **************/
.modal {
    display:none;
    position:fixed;
    top:0;
    left:0;
    width:100%;
    height:100%;
    background:rgba(0,0,0,0.85);
    justify-content:center;
    align-items:flex-start; /* مهم */
    z-index:9999;

    overflow-y:auto;           /* scroll عام */
    padding:40px 15px;         /* فراغ من فوق وتحت */
}

.modal-content {
    background:#1e1e1e;
    padding:25px;
    width:380px;
    max-width:100%;
    border-radius:12px;
    border:1px solid #444;
    color:#fff;

    max-height:calc(100vh - 80px); /* يمنع الخروج عن الشاشة */
    overflow-y:auto;               /* scroll داخلي */
}

.modal-content h3 {
    margin-top:0;
    text-align:center;
    position:sticky;
    top:0;
    background:#1e1e1e;
    padding-bottom:10px;
    z-index:2;
}

.modal-content input,
.modal-content textarea {
    width:100%;
    padding:10px;
    border-radius:8px;
    border:none;
    margin-bottom:10px;
    background:#333;
    color:#fff;
}

.preview {
    width:80px;
    height:80px;
    margin-bottom:10px;
    border-radius:8px;
    object-fit:cover;
    border:1px solid #444;
}
.btn-primary {
    background:#ff7a00;
    padding:10px;
    border-radius:8px;
    border:none;
    width:100%;
    margin-top:10px;
    cursor:pointer;
}
.btn-danger {
    background:#a00;
    padding:10px;
    border-radius:8px;
    border:none;
    width:100%;
    margin-top:10px;
    cursor:pointer;
}
/* ===== CATEGORIES GRID ===== */
#categories-list{
    display:grid;
    grid-template-columns:repeat(1,1fr);
    gap:20px;
}

/* Tablet */
@media (max-width:1024px){
    #categories-list{
        grid-template-columns:repeat(2,1fr);
    }
}

/* Desktop */
@media (min-width:1200px){
    #categories-list{
        grid-template-columns:repeat(1,1fr);
    }
}
/* ===== ITEMS GRID ===== */
.items-list{
    display:grid;
    grid-template-columns:repeat(1,1fr);
    gap:10px;
}

/* Tablet */
@media (max-width:1024px){
    .items-list{
        grid-template-columns:repeat(2,1fr);
    }
}

/* Desktop */
@media (min-width:1200px){
    .items-list{
        grid-template-columns:repeat(1,1fr);
    }
}
.item-row{
    width:100%;
    box-sizing:border-box;
}

.category-box{
    height:fit-content;
}
/* ===============================
   TABLET FIX – نفس التقارير
   تقليص الزحوفة والمسافات
=============================== */
@media (min-width:768px) and (max-width:1024px){

  

    /* العنوان */
    .page-title{
        margin-bottom:15px;
        font-size:22px;
    }

    /* الأزرار العلوية */
    .top-actions{
        margin-bottom:18px;
        gap:10px;
    }

    /* التصنيفات */
    .category-box{
        padding:14px;
    }

    /* العناصر */
    .item-row{
        padding:8px;
    }

    .item-price{
        min-width:55px;
        text-align:left;
    }
}
/* Tablet 11 inch */
@media (max-width:1024px){
    .content{
        margin-right:200px;
        padding-left:20px;
        padding-right:20px;
    }
}
</style>

</head>
<body>

<?php include "includes/header.php"; ?>

<div class="content">

<h2 class="page-title"><?= $tr['menu_builder'] ?></h2>






<div class="top-actions">

    <form action="menu_builder_actions.php" method="POST" enctype="multipart/form-data">
        <input type="hidden" name="action" value="upload_excel">
        <input type="file" name="excel" accept=".xlsx,.xls">
      <button class="btn"><?= $tr['upload_excel'] ?></button>
    </form>
<a href="menu_template_download.php" class="btn-dark"> download_excel</a>

    <button class="btn-dark" type="button" onclick="openAddCategory()">add_category</button>

</div>

<div id="categories-list">

<?php foreach ($categories as $cat): ?>
<?php
    $ln = $panel_lang;
    $cat_name = $cat["name_$ln"] ?: $cat['name'];
?>
<div class="category-box" data-id="<?= $cat['id'] ?>" id="cat_<?= $cat['id'] ?>">

    <div class="category-header">

        <img src="<?= build_image_url($cat['image'], 'Categories') ?>" 
             onerror="this.src='../assets/no-image.png'">

        <div class="category-name">
            <?= htmlspecialchars($cat_name) ?>
        </div>

        <div class="cat-actions">
            <button class="action-btn" type="button" onclick="openEditCategory(<?= $cat['id'] ?>)">edit</button>
        
            <button class="action-btn" type="button" onclick="deleteCategory(<?= $cat['id'] ?>)">delete</button>
        </div>

    </div>

    <div class="items-list" id="items_cat_<?= $cat['id'] ?>">

        <?php foreach ($cat_items[$cat['id']] as $item): ?>
        <?php
            $name = $item["name_$ln"] ?: $item['name'];
            $desc = $item["description_$ln"] ?: $item['description'];
            $price = $item['base_price'];
        ?>
        <div class="item-row" data-id="<?= $item['id'] ?>" id="item_<?= $item['id'] ?>">

            <img src="<?= build_image_url($item['image'], 'Items') ?>" 
                 onerror="this.src='../assets/no-image.png'">

            <div class="item-info">
                <div class="item-title"><?= htmlspecialchars($name) ?></div>
                <?php if ($desc): ?>
                    <div class="item-desc"><?= nl2br(htmlspecialchars($desc)) ?></div>
                <?php endif; ?>
            </div>

            <div class="item-price">
                <?= number_format($price, 0) ?>
            </div>

            <div class="toggle <?= $item['active'] ? 'on':'off' ?>" onclick="toggleItem(<?= $item['id'] ?>)">
                <?= $item['active'] ? 'active':'inactive' ?>
            </div>

            <button class="action-btn" type="button" onclick="openEditItem(<?= $item['id'] ?>)">edit</button>
            <button class="action-btn" type="button" onclick="openOptions(<?= $item['id'] ?>)">options</button>
            <?php
$options = fetch_all("SELECT * FROM item_options WHERE item_id=? AND active=1 ORDER BY ordering ASC", [$item['id']]);
if ($options):
?>
<div style="margin-top:6px; font-size:13px; color:#ffae00;">
    customizable (<?= count($options) ?>)
</div>
<?php endif; ?>

            <button class="action-btn" type="button" onclick="deleteItem(<?= $item['id'] ?>)">delete</button>

        </div>
        <?php endforeach; ?>

        <button class="btn-dark" type="button" onclick="openAddItem(<?= $cat['id'] ?>)">add_item</button>

    </div>

</div>
<?php endforeach; ?>

</div>
<script>
    const PANEL_LANG = "<?= $panel_lang ?>";
</script>

<script>
// ترتيب التصنيفات
new Sortable(document.getElementById('categories-list'), {
    animation:150,
    onEnd:function(){
        let order=[];
        document.querySelectorAll(".category-box").forEach((el,i)=>{
            order.push({id:el.dataset.id,pos:i});
        });
        saveOrder(order,"category");
    }
});

// ترتيب العناصر داخل كل تصنيف
<?php foreach ($categories as $cat): ?>
new Sortable(document.getElementById('items_cat_<?= $cat['id'] ?>'), {
    animation:150,
    onEnd:function(){
        let order=[];
        document.querySelectorAll("#items_cat_<?= $cat['id'] ?> .item-row").forEach((el,i)=>{
            order.push({id:el.dataset.id,pos:i,category:<?= $cat['id'] ?>});
        });
        saveOrder(order,"item");
    }
});
<?php endforeach; ?>

function saveOrder(order,type){
    fetch("menu_builder_actions.php",{
        method:"POST",
        headers:{"Content-Type":"application/json"},
        body:JSON.stringify({action:"reorder",type:type,list:order})
    });
}

function toggleItem(id){
    fetch("menu_builder_actions.php",{
        method:"POST",
        headers:{"Content-Type":"application/x-www-form-urlencoded"},
        body:"action=toggle_item&id="+encodeURIComponent(id)
    }).then(()=>location.reload());
}

function deleteCategory(id){
    if(!confirm("هل تريد delete التصنيف وكل العناصر داخله؟")) return;
    fetch("menu_builder_actions.php",{
        method:"POST",
        headers:{"Content-Type":"application/x-www-form-urlencoded"},
        body:"action=delete_category&id="+encodeURIComponent(id)
    }).then(()=>location.reload());
}

function deleteItem(id){
   if(!confirm("<?= $tr['confirm_delete_item'] ?>")) return;
    fetch("menu_builder_actions.php",{
        method:"POST",
        headers:{"Content-Type":"application/x-www-form-urlencoded"},
        body:"action=delete_item&id="+encodeURIComponent(id)
    }).then(()=>location.reload());
}

function closeModal(id){ document.getElementById(id).style.display="none"; }
function openAddCategory(){ document.getElementById("modal_add_category").style.display="flex"; }
function openAddItem(cat){ document.getElementById("add_item_cat").value=cat; document.getElementById("modal_add_item").style.display="flex"; }

function openEditCategory(id){
    loadCategory(id);
    document.getElementById("modal_edit_category").style.display="flex";
}
function openEditItem(id){
    loadItem(id);
    document.getElementById("modal_edit_item").style.display="flex";
}

function loadCategory(id){
    fetch("menu_builder_actions.php",{
        method:"POST",
        headers:{"Content-Type":"application/x-www-form-urlencoded"},
        body:"action=get_category&id="+encodeURIComponent(id)
    })
    .then(res=>res.json())
    .then(cat=>{
        if(!cat || cat.error) return;
        document.getElementById("edit_cat_id").value = cat.id;
        let img = document.getElementById("edit_cat_image");
        img.src = cat.image_url;
        img.style.display = "block";
        <?php foreach ($languages as $lang): ?>
        document.getElementById("edit_cat_name_<?= $lang ?>").value = cat["name_<?= $lang ?>"] || "";
        <?php endforeach; ?>
    });
}

function loadItem(id){
    fetch("menu_builder_actions.php",{
        method:"POST",
        headers:{"Content-Type":"application/x-www-form-urlencoded"},
        body:"action=get_item&id="+encodeURIComponent(id)
    })
    .then(res=>res.json())
    .then(item=>{
        if(!item || item.error) return;
        document.getElementById("edit_item_id").value = item.id;
        document.getElementById("edit_item_price").value = item.price;

        let img = document.getElementById("edit_item_image");
        img.src = item.image_url;
        img.style.display = "block";

        <?php foreach ($languages as $lang): ?>
        document.getElementById("edit_item_name_<?= $lang ?>").value = item["name_<?= $lang ?>"] || "";
        document.getElementById("edit_item_desc_<?= $lang ?>").value = item["description_<?= $lang ?>"] || "";
        <?php endforeach; ?>
    });
}
function openOptions(item_id){
    document.getElementById("modal_options").style.display="flex";
    document.getElementById("opt_item_id").value = item_id;

    fetch("menu_builder_actions.php",{
        method:"POST",
        headers:{"Content-Type":"application/x-www-form-urlencoded"},
        body:"action=get_options&id="+item_id
    })
    .then(r=>r.json())
    .then(res=>{
        let box = "";
        res.forEach(op=>{
            let title =
                PANEL_LANG === "en" ? (op.name_en || op.name_ar) :
                PANEL_LANG === "ku" ? (op.name_ku || op.name_ar) :
                                      (op.name_ar); // default ar

            box += `
            <div class="item-row" style="margin-bottom:10px;">
                <img src="${op.image}" style="width:50px;height:50px;border-radius:6px;">
                <div class="item-info">
                    <div class="item-title">${title}</div>
                </div>
                <div class="item-price">${op.price}</div>
                <button class="action-btn" onclick="deleteOption(${op.id})">delete</button>
            </div>`;
        });
        document.getElementById("options_container").innerHTML = box;
    });
}


function openAddOption(){
    document.getElementById("modal_add_option").style.display="flex";
}

function deleteOption(id){
    if(!confirm("delete الخيار؟")) return;
    fetch("menu_builder_actions.php",{
        method:"POST",
        headers:{"Content-Type":"application/x-www-form-urlencoded"},
        body:"action=delete_option&id="+id
    }).then(()=>openOptions(document.getElementById("opt_item_id").value));
}

</script>

<!-- ADD CATEGORY MODAL -->
<div class="modal" id="modal_add_category">
<div class="modal-content">
<h3>ADD CATEGORY</h3>
<form action="menu_builder_actions.php" method="POST" enctype="multipart/form-data">
    <input type="hidden" name="action" value="add_category">
    <label>image:</label>
    <input type="file" name="image" required>

    <?php foreach ($languages as $lang): ?>
        <label>name (<?= strtoupper($lang) ?>):</label>
        <input type="text" name="name_<?= $lang ?>" required>
        
<label>description (<?= strtoupper($lang) ?>):</label>
<textarea name="description_<?= $lang ?>"></textarea>
    <?php endforeach; ?>

    <button type="button" class="btn-danger" onclick="closeModal('modal_add_category')">close</button>
    <button class="btn-primary">إضافة</button>
</form>
</div>
</div>

<!-- EDIT CATEGORY MODAL -->
<div class="modal" id="modal_edit_category">
<div class="modal-content">
<h3>EDIT CATEGORY</h3>
<form action="menu_builder_actions.php" method="POST" enctype="multipart/form-data">
    <input type="hidden" name="action" value="edit_category">
    <input type="hidden" id="edit_cat_id" name="id">

    <label>image:</label>
    <input type="file" name="image">
    <img id="edit_cat_image" class="preview" style="display:none;">

    <?php foreach ($languages as $lang): ?>
        <label>name (<?= strtoupper($lang) ?>):</label>
        <input type="text" id="edit_cat_name_<?= $lang ?>" name="name_<?= $lang ?>" required>
    <?php endforeach; ?>

    <button type="button" class="btn-danger" onclick="closeModal('modal_edit_category')">close</button>
    <button class="btn-primary">حفظ التعديلات</button>
</form>
</div>
</div>

<!-- ADD ITEM MODAL -->
<div class="modal" id="modal_add_item">
<div class="modal-content">
<h3>إضافة عنصر</h3>
<form action="menu_builder_actions.php" method="POST" enctype="multipart/form-data">
    <input type="hidden" name="action" value="add_item">
    <input type="hidden" id="add_item_cat" name="category_id">

    <label>image:</label>
    <input type="file" name="image" required>

    <?php foreach ($languages as $lang): ?>
        <label>name (<?= strtoupper($lang) ?>):</label>
        <input type="text" name="name_<?= $lang ?>" required>

        <label>description (<?= strtoupper($lang) ?>):</label>
        <textarea name="description_<?= $lang ?>"></textarea>
    <?php endforeach; ?>

    <label>price:</label>
    <input type="number" step="0.01" name="price" required>

    <button type="button" class="btn-danger" onclick="closeModal('modal_add_item')">close</button>
    <button class="btn-primary">إضافة</button>
</form>
</div>
</div>

<!-- EDIT ITEM MODAL -->
<div class="modal" id="modal_edit_item">
<div class="modal-content">
<h3>تعديل العنصر</h3>

<form action="menu_builder_actions.php" method="POST" enctype="multipart/form-data">
    <input type="hidden" name="action" value="edit_item">
    <input type="hidden" id="edit_item_id" name="id">

    <label>image:</label>
    <input type="file" name="image">
    <img id="edit_item_image" class="preview" style="display:none;">

    <?php foreach ($languages as $lang): ?>
        <label>name (<?= strtoupper($lang) ?>):</label>
        <input type="text" id="edit_item_name_<?= $lang ?>" name="name_<?= $lang ?>" required>

        <label>description (<?= strtoupper($lang) ?>):</label>
        <textarea id="edit_item_desc_<?= $lang ?>" name="description_<?= $lang ?>"></textarea>
    <?php endforeach; ?>

    <label>السعر:</label>
    <input type="number" step="0.01" id="edit_item_price" name="price" required>

    <button type="button" class="btn-danger" onclick="closeModal('modal_edit_item')">close</button>
    <button class="btn-primary">save_changes</button>
</form>

</div>
</div>
<!-- OPTIONS MODAL -->
<div class="modal" id="modal_options">
<div class="modal-content" style="width:450px;">
<h3>manage_options</h3>

<div id="options_container"></div>

<button class="btn-primary" onclick="openAddOption()">add_option</button>
<button class="btn-danger" onclick="closeModal('modal_options')">close</button>
</div>
</div>

<!-- ADD OPTION MODAL -->
<div class="modal" id="modal_add_option">
<div class="modal-content" style="width:450px;">
<h3>add_option</h3>

<form action="menu_builder_actions.php" method="POST" enctype="multipart/form-data">
<input type="hidden" name="action" value="add_option">
<input type="hidden" id="opt_item_id" name="item_id">

<label>image:</label>
<input type="file" name="image" required>

<?php foreach ($languages as $lang): ?>
    <label>name (<?= strtoupper($lang) ?>):</label>
    <input type="text" name="name_<?= $lang ?>" required>

    <label>description (<?= strtoupper($lang) ?>):</label>
    <textarea name="description_<?= $lang ?>"></textarea>
<?php endforeach; ?>

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

<button class="btn-primary">إضافة</button>
<button type="button" class="btn-danger" onclick="closeModal('modal_add_option')">close</button>
</form>

</div>
</div>


</body>
</html>
<?php ob_end_flush(); ?>
