<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(E_ALL);

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

ensure_manager();

$restaurant_id = $_SESSION['restaurant_id'];
$branches = get_branches($restaurant_id);

/* ================== ADD BANNER ================== */
if(isset($_POST['add_banner'])){
    $img = upload_custom("image", "Banners"); // حفظ في uploads/Banners

    if($img){
        $branch = $_POST['branch_id'] !== "all" ? intval($_POST['branch_id']) : null;
        $start  = !empty($_POST['start_date']) ? $_POST['start_date'] : null;
        $end    = !empty($_POST['end_date'])   ? $_POST['end_date']   : null;

        db()->prepare("
            INSERT INTO banners (restaurant_id, branch_id, image, title, start_date, end_date, ordering, active)
            VALUES (?,?,?,?,?,?,?,1)
        ")->execute([
            $restaurant_id, $branch, $img, clean($_POST['title']), $start, $end, 999
        ]);
    }
    header("Location: banners.php?added=1"); exit;
}

/* ================== TOGGLE ================== */
if(isset($_GET['toggle'])){
    db()->prepare("UPDATE banners SET active = NOT active WHERE id=? AND restaurant_id=?")
       ->execute([$_GET['toggle'], $restaurant_id]);
    header("Location: banners.php?update=1"); exit;
}

/* ================== DELETE ================== */
if(isset($_GET['delete'])){
    $img = fetch_value("SELECT image FROM banners WHERE id=? AND restaurant_id=?", [$_GET['delete'], $restaurant_id]);
    if($img && file_exists($_SERVER['DOCUMENT_ROOT']."/menu/uploads/Banners/".$img)){
        unlink($_SERVER['DOCUMENT_ROOT']."/menu/uploads/Banners/".$img);
    }
    db()->prepare("DELETE FROM banners WHERE id=? AND restaurant_id=?")
       ->execute([$_GET['delete'], $restaurant_id]);
    header("Location: banners.php?deleted=1"); exit;
}

/* ================== REORDER ================== */
if(isset($_POST['order'])){
    $o=1;
    foreach($_POST['order'] as $id){
        db()->prepare("UPDATE banners SET ordering=? WHERE id=? AND restaurant_id=?")
           ->execute([$o, $id, $restaurant_id]);
        $o++;
    }
    exit;
}

/* ================== LOAD ================== */
$banners = get_banners($restaurant_id);
include "includes/header.php";
?>

<div class="content">

<h2 class="page-title">إدارة البانرات</h2>

<?php if(isset($_GET['added']))  echo '<div class="msg success">تم إضافة بانر</div>'; ?>
<?php if(isset($_GET['update'])) echo '<div class="msg success">تم تحديث الحالة</div>'; ?>
<?php if(isset($_GET['deleted']))echo '<div class="msg danger">تم حذف البانر</div>'; ?>

<!-- ================== ADD FORM ================== -->
<div class="card">
<form method="post" enctype="multipart/form-data">
    <h3>إضافة بانر جديد</h3>

    <label>عنوان (اختياري)</label>
    <input type="text" name="title" placeholder="عنوان اختياري">

    <label>الصورة</label>
    <input type="file" name="image" accept="image/*" required>

    <label>فرع العرض</label>
    <select name="branch_id">
        <option value="all">جميع الفروع</option>
        <?php foreach($branches as $b): ?>
            <option value="<?= $b['id'] ?>"><?= $b['name_ar'] ?></option>
        <?php endforeach; ?>
    </select>

    <label>من تاريخ (اختياري)</label>
    <input type="date" name="start_date">

    <label>إلى تاريخ (اختياري)</label>
    <input type="date" name="end_date">

    <button name="add_banner" class="save-btn">إضافة بانر</button>
</form>
</div>

<!-- ================== LIST ================== -->
<h3 class="section-title">البانرات الحالية</h3>

<ul id="bannerList" class="banner-list">
<?php foreach($banners as $b): ?>

<?php $img = "/menu/uploads/Banners/".$b['image']; ?>
<li data-id="<?= $b['id'] ?>">

    <img src="<?= $img ?>" class="banner-img" onerror="this.src='../assets/no-image.png'">

    <div class="banner-info">
        <div class="banner-title"><?= $b['title'] ?: '-' ?></div>

        <div class="small-details">
            <span><?= $b['branch_id'] ? get_branch($b['branch_id'])['name_ar'] : "كل الفروع" ?></span>
            <?php if($b['start_date'] || $b['end_date']): ?>
                <span><?= $b['start_date'] ?> → <?= $b['end_date'] ?: "بدون انتهاء" ?></span>
            <?php else: ?>
                <span>دون قيود تاريخ</span>
            <?php endif; ?>
        </div>

        <span class="status <?= $b['active']?'on':'off' ?>">
            <?= $b['active']?'نشط':'متوقف' ?>
        </span>
    </div>

    <div class="actions">
        <a href="?toggle=<?= $b['id'] ?>" class="btn-sm"><?= $b['active']?'إيقاف':'تفعيل' ?></a>
        <a href="?delete=<?= $b['id'] ?>" class="btn-delete" onclick="return confirm('حذف البانر؟')">حذف</a>
    </div>

</li>
<?php endforeach; ?>
</ul>

</div>

<!-- ================== STYLE ================== -->
<style>
.card{background:#1c1c1c;padding:20px;border-radius:12px;border:1px solid #333;margin-bottom:25px;}
.page-title{margin-bottom:15px;color:#ff7a00;}
.msg{padding:10px;border-radius:8px;margin:10px 0;text-align:center;font-weight:bold}
.msg.success{background:#008f39;color:#fff}
.msg.danger{background:#b00000;color:#fff}

input,select{
    width:100%;padding:10px;border-radius:8px;background:#111;
    border:1px solid #444;color:#fff;margin-bottom:12px;
}
.save-btn{width:100%;background:#ff7a00;padding:12px;border:none;color:#000;
font-weight:bold;border-radius:8px;cursor:pointer}

.section-title{margin:20px 0;color:#fff;font-size:20px}

.banner-list{list-style:none;padding:0;margin-top:10px}
.banner-list li{
    background:#1c1c1c;padding:12px;border-radius:12px;border:1px solid #333;
    display:flex;align-items:center;gap:15px;margin-bottom:12px;cursor:move;
}

.banner-img{width:140px;height:70px;object-fit:cover;border-radius:8px}
.banner-info{flex:1}
.banner-title{font-size:15px;font-weight:bold}
.small-details{font-size:12px;color:#bbb;margin-top:3px}

.status{display:inline-block;padding:4px 10px;border-radius:6px;font-size:12px;margin-top:4px}
.status.on{background:#00c170;color:#000}
.status.off{background:#c70000;color:#fff}

.actions a{margin-left:5px}
.btn-sm{background:#ffbb00;padding:6px 10px;border-radius:6px;color:#000;text-decoration:none;font-size:13px}
.btn-delete{background:#d82626;padding:6px 10px;border-radius:6px;color:#fff;text-decoration:none;font-size:13px}
</style>

<!-- ================== SORT JS ================== -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/Sortable/1.15.0/Sortable.min.js"></script>
<script>
new Sortable(document.getElementById("bannerList"), {
    animation:150,
    onEnd: () => {
        const order = [...document.querySelectorAll("#bannerList li")].map(li => li.dataset.id);
        fetch("banners.php", {
            method:"POST",
            headers:{"Content-Type":"application/x-www-form-urlencoded"},
            body: new URLSearchParams({order})
        });
    }
});
</script>
