<?php

ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(E_ALL);

require_once __DIR__ . "/includes/db.php";
require_once __DIR__ . "/includes/security.php";
require_once __DIR__ . "/includes/auth.php";
require_once __DIR__ . "/includes/functions.php";

ensure_manager();

$restaurant_id = $_SESSION['restaurant_id'];

/* جلب فروع المطعم */
$branches = get_branches($restaurant_id);

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

$page_title = "إدارة الفروع";
require_once "includes/header.php";
?>

<div class="content">

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2 class="text-warning"><?= $page_title ?></h2>
    <button class="btn btn-orange" id="btn_add">+ إضافة فرع</button>
</div>

<!--------------------------------
    نموذج إضافة / تعديل فرع
---------------------------------->
<div id="branchFormBox" class="card p-3 mb-4" style="display:none;background:#1e1e1e;border:1px solid #333;border-radius:12px;">
<form id="branchForm" method="POST" enctype="multipart/form-data">

    <input type="hidden" name="id">

    <div class="row g-3">

        <?php foreach($languages as $lang): ?>
        <div class="col-md-4">
            <label class="form-label">اسم الفرع (<?= htmlspecialchars($lang['name']) ?>)</label>
            <input type="text" name="name_<?= $lang['code'] ?>" class="form-control form-control-dark" required>
        </div>
        <?php endforeach; ?>

        <div class="col-md-12">
            <label class="form-label d-block">أرقام الهاتف</label>
            <div id="phones_box">
                <div class="phone-item mb-2 d-flex">
                    <input type="text" name="phone[]" class="form-control form-control-dark" placeholder="مثال: 07700000000">
                    <button class="btn btn-success btn-sm ms-2" type="button" onclick="addPhone()">+</button>
                </div>
            </div>
        </div>

        <div class="col-md-12">
            <label class="form-label">رابط الخريطة</label>
            <input type="text" name="map_url" class="form-control form-control-dark">
        </div>

        <div class="col-md-12">
            <label class="form-label">نوع المنيو</label>
            <select name="menu_mode" class="form-select form-control-dark" required>
                <option value="shared">مشترك</option>
                <option value="independent">مستقل</option>
                <option value="copy">مشترك + أسعار فرعية</option>
            </select>
        </div>

        <div class="col-12">
            <button class="btn btn-orange w-100 py-2 fs-5 fw-bold" id="saveBtn"></button>
        </div>

    </div>
</form>
</div>

<!--------------------------------
    عرض فروع المطعم
---------------------------------->
<div id="branchList">
<?php foreach($branches as $b): ?>
    <div class="card p-3 mb-3 card-branch" data-id="<?= $b['id'] ?>">

        <div class="row align-items-center">

            <div class="col-md-4">
                <b><?= htmlspecialchars($b['name']) ?></b><br>
                <?php if($b['active']): ?>
                    <span class="status-active">نشط</span>
                <?php else: ?>
                    <span class="status-inactive">متوقف</span>
                <?php endif; ?>
            </div>

            <div class="col-md-3">
                زيارات: <?= fetch_value("SELECT COUNT(*) FROM visits WHERE branch_id=?", [$b['id']]) ?>
            </div>

            <div class="col-md-5 text-end">

                <button class="btn btn-sm btn-edit" onclick='openEditBranch(<?= json_encode($b) ?>)'>تعديل</button>

                <?php if($b['active']): ?>
                    <a href="branch_toggle.php?id=<?= $b['id'] ?>&status=0" class="btn btn-sm btn-dark">إيقاف</a>
                <?php else: ?>
                    <a href="branch_toggle.php?id=<?= $b['id'] ?>&status=1" class="btn btn-sm btn-success">تشغيل</a>
                <?php endif; ?>

                <a href="branch_delete.php?id=<?= $b['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('حذف هذا الفرع؟')">حذف</a>
            </div>

        </div>
    </div>
<?php endforeach; ?>
</div>

</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/Sortable/1.15.0/Sortable.min.js"></script>
<script>

new Sortable(document.getElementById('branchList'), {
    animation:150,
    onEnd:function(){
        let order=[];
        document.querySelectorAll('[data-id]').forEach(el=>order.push(el.getAttribute('data-id')));
        fetch("ajax/branch_order.php",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(order)});
    }
});

document.getElementById("btn_add").onclick=function(){
    document.getElementById("branchForm").reset();
    document.querySelector("[name=id]").value="";
    document.getElementById("branchFormBox").style.display='block';
    document.getElementById("saveBtn").innerHTML="حفظ الفرع";
    document.getElementById("branchForm").action="branch_add.php";
    window.scrollTo({top:0,behavior:"smooth"});
};

function openEditBranch(data){
    document.getElementById("branchFormBox").style.display='block';
    document.querySelector("[name=id]").value = data.id;

    // تعبئة أسماء الفروع حسب اللغات الديناميكية
    <?php foreach($languages as $lang): ?>
    if(document.querySelector("[name=name_<?= $lang['code'] ?>]") && data["name_<?= $lang['code'] ?>"]){
        document.querySelector("[name=name_<?= $lang['code'] ?>]").value = data["name_<?= $lang['code'] ?>"];
    }
    <?php endforeach; ?>

    // تعبئة أرقام الهاتف JSON
    document.getElementById("phones_box").innerHTML = "";
    if(data.phone){
        try {
            let arr = JSON.parse(data.phone);
            if(Array.isArray(arr)){
                arr.forEach(ph => addPhone(ph));
            } else {
                addPhone(data.phone); // حالة قديمة
            }
        } catch(e){
            addPhone(data.phone); // في حال لم يكن JSON
        }
    } else {
        addPhone(); // حقل فارغ واحد
    }

    // رابط الخريطة
    if(data.map_url) document.querySelector("[name=map_url]").value = data.map_url;

    // نوع المنيو
    if(data.menu_mode) document.querySelector("[name=menu_mode]").value = data.menu_mode;

    // زر حفظ تعديـل
    document.getElementById("saveBtn").innerHTML="تعديل الفرع";
    document.getElementById("branchForm").action="branch_edit.php";
    window.scrollTo({top:0,behavior:"smooth"});
}


function addPhone(val=""){
    let box = document.getElementById("phones_box");
    let div = document.createElement("div");
    div.className="phone-item mb-2 d-flex";
    div.innerHTML = `
        <input type="text" name="phone[]" class="form-control form-control-dark" value="${val}">
        <button class="btn btn-danger btn-sm ms-2" type="button" onclick="this.parentElement.remove()">-</button>
    `;
    box.appendChild(div);
}

</script>

<style>
.card-branch{background:#1c1c1c;border:1px solid #333;border-radius:12px;cursor:grab;transition:.2s;}
.card-branch:hover{transform:scale(.99);background:#262626;}
.status-active{color:#20c997;font-weight:bold;}
.status-inactive{color:#dc3545;font-weight:bold;}
.btn-orange{background:#ff7a00;color:#fff;border-radius:8px;}
.btn-orange:hover{background:#e86c00;color:#fff;}
.btn-edit{background:#ffc107;color:#000;border-radius:6px;}
.btn-edit:hover{background:#d39e00;}
.form-control-dark,.form-select.form-control-dark{background:#1c1c1c!important;border:1px solid #444!important;color:#fff!important;}
.form-control-dark:focus{border-color:#ff7a00!important;box-shadow:none!important;}
</style>
