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

require_once "../includes/config.php";
require_once "../includes/functions.php";


/* =========================
   AUTO ACTIVATE / DEACTIVATE DISCOUNTS
   (DATE only + DAILY TIME + manual override)
========================= */

/* تفعيل تلقائي */
db()->prepare("
    UPDATE discounts
    SET active = 1
    WHERE manual_disabled = 0
    AND CURDATE() BETWEEN DATE(start_date) AND DATE(end_date)
    AND CURTIME() BETWEEN daily_start_time AND daily_end_time
")->execute();

/* إيقاف تلقائي */
db()->prepare("
    UPDATE discounts
    SET active = 0
    WHERE manual_disabled = 0
    AND (
        CURDATE() < DATE(start_date)
        OR CURDATE() > DATE(end_date)
        OR CURTIME() < daily_start_time
        OR CURTIME() > daily_end_time
    )
")->execute();


/* =========================
    CHECK BRANCH
========================= */
$branch_id = $_GET['branch'] ?? null;
if (!$branch_id) die("Branch ID missing");
$branch = get_branch($branch_id);
if (!$branch) die("Branch Not Found");

/* =========================
    RESTAURANT BY FOLDER
========================= */
$folder = basename(dirname(__FILE__));
$restaurant = get_restaurant_by_folder($folder);
if (!$restaurant) die("Restaurant Not Found");

// اللغة الحالية
$currentLang = $_GET['lang'] ?? 'ar';

// البراميترات الحالية
$params = $_GET;

// دالة توليد رابط مع تبديل اللغة فقط
function langUrl($newLang, $params){
    $params['lang'] = $newLang;
    return '?' . http_build_query($params);
}

// لغات المطعم الفعّالة
$languages = 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'] ?? $restaurant_id]);

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

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

/* =========================
    REGISTER VISIT
========================= */
log_visit($branch_id, $restaurant['id'], "menu", null, null);

/* =========================
    BANNERS + CATEGORIES + ITEMS
========================= */
$banners = get_banners($restaurant['id']);
$categories = get_categories($restaurant['id']);

$menu_items = [];
foreach ($categories as $cat) {
    $menu_items[$cat['id']] = get_items_by_category($cat['id'], $branch_id, $restaurant['id']);
}

/* =======================
    COLORS
======================= */
$primary_color = $restaurant['secondary_color'] ?: "#ff7a00";
?>
<!DOCTYPE html>
<html lang="<?= $lang ?>" dir="<?= $lang=='ar'?'rtl':'ltr' ?>">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

<title><?= $branch["name_{$lang}"] ?: $branch['name'] ?></title>

<style>
:root { --primary: <?= $primary_color ?>; }

body{
    margin:0;
    background:#000;
    color:#fff;
    font-family:'Cairo', Medium;
    overflow-x:hidden;
    scroll-behavior:smooth;
}
a{text-decoration:none;color:inherit}

.back-btn{
    position:relative; /* ← لم يعد عائماً */
    display:inline-block;
    margin:12px; /* هامش عن الحواف */
    background:rgba(0,0,0,0.65);
    padding:10px 14px;
    border-radius:10px;
    border:1px solid rgba(255,255,255,0.15);
    color:#fff;
    font-size:14px;
    cursor:pointer;
}


/* HERO */
.simple-hero{
    min-height: 45svh;
    background:#111;
    display:flex;
    align-items:center;
    justify-content:center;
    position:relative;
}
.simple-hero .overlay{
    position:absolute; top:0; left:0;
    width:100%; height:100%;
    background:#000; opacity:0.45;
}
.simple-hero img.logo{
    width:240px;
    z-index:3;
    animation:fadeIn 1.6s ease;
}
@keyframes fadeIn{
    0%{opacity:0; transform:scale(1.15);}
    100%{opacity:1; transform:scale(1);}
}

/* ===========================
   NEW BANNER FULL-WIDTH SLIDER
=========================== */
.banner-slider{
    width:100%;
    overflow:hidden;
    position:relative;
    padding:10px 0;
}

.banner-track{
    display:flex;
    gap:0;            /* مهم جداً */
    padding:0;        /* مهم جداً */
    transition:transform .45s ease-in-out;
}

.bn-slide{
    flex:0 0 100%;    /* بانر بعرض الشاشة */
    max-width:100%;
    padding:0 14px;   /* مسافة يمين ويسار */
    box-sizing:border-box;
}

.bn-slide .bn-card{
    background:#111;
    border-radius:18px;
    overflow:hidden;
    box-shadow:0 4px 18px rgba(0,0,0,0.5);
}

.bn-slide img{
    width:100%;
    height:38vh;
    border-radius:18px;
    object-fit:cover;
    display:block;
}

/* DOTS */
.banner-dots{
    text-align:center;
    margin-top:10px;
}
.banner-dots span{
    display:inline-block;
    width:8px; height:8px;
    border-radius:50%;
    background:#555;
    margin:0 3px;
    cursor:pointer;
    transition:.25s;
}
.banner-dots span.active{ background:var(--primary); }

/* TABS */
.tabs{
    display:flex; gap:10px;
    overflow-x:auto; white-space:nowrap;
    padding:12px 10px;
    background:#000;
    border-bottom:1px solid #222;
    position:sticky; top:0; z-index:50;
    height:58px;
}
.tabs a{
    padding:10px 18px;
    border:1px solid var(--primary);
    color:var(--primary);
    border-radius:22px;
    font-size:16px; transition:.2s;
    display:inline-block;
}
.tabs a.active{
    background:var(--primary);
    color:#000;
}

/* CATEGORY */
.category-card{
    text-align:center;
    margin:30px 0 18px 0;
}
.category-name{
    margin-top:12px;
    font-family:'Cairo', Bold;
    font-weight:700;                 /* Cairo Medium */
    font-size:30px;
    color:#fff;
    background:rgba(0,0,0,0.7);       /* مستطيل خلف النص */
    padding:10px 18px;
    border-radius:12px;
    text-align:center;
    width:fit-content;
    margin-left:auto;
    margin-right:auto;
}
.category-card img.category-img{
    width:100vw;          /* عرض الشاشة كامل */
    max-width:100%;       /* بدون حد أقصى */
    height:230px;         /* عدّلها إذا بدك أطول */
    border-radius:18px;
    margin:0;
    display:block;
    object-fit:cover;
    box-shadow:0 0 12px rgba(0,0,0,0.6);
}


/* ITEMS GRID */
.items-grid{
    display:grid;
    gap:12px;
    padding:10px;
    grid-template-columns:repeat(1,1fr);
}
@media (min-width:768px){
    .items-grid{ grid-template-columns:repeat(3,1fr); }
}
@media (min-width:992px){
    .items-grid{ grid-template-columns:repeat(4,1fr); }
}

/* ITEMS */
.grid-item{
    background:#1a1a1a;
    border-radius:14px;
    overflow:hidden;
    cursor:pointer; position:relative;
}
.grid-item img{
    width:100%; height:160px; object-fit:cover;
}
.grid-info{ padding:10px; }
.grid-title{ font-size:16px; font-weight:bold; }
.grid-price{ color:var(--primary); font-size:16px; }
.grid-old{ color:#999; text-decoration:line-through; font-size:13px; }

/* LIKE */
.like-count{ position:absolute; top:8px; right:40px; }
.heart{
    position:absolute; top:8px; right:8px;
    cursor:pointer; transition:.2s;
}
.heart.liked{color:var(--primary); transform:scale(1.2); }

/* BOTTOM SHEET */
.bottom-sheet{
    position:fixed;
    bottom:-120vh; /* ← الحل الصحيح */
    left:0; right:0;
    height:99vh;
    background:#111;
    border-radius:22px 22px 0 0;
    box-shadow:0 -4px 18px rgba(0,0,0,0.8);
    padding:15px;
    transition:.45s cubic-bezier(.25,.46,.45,.94);
    z-index:100;
}
.bottom-sheet.active{ bottom:0; }

.sheet-close{
    width:60px; height:6px;
    background:#555; border-radius:4px;
    margin:0 auto 10px auto;
}
.top-bar{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:10px;
    margin-bottom:15px;
}

.back-btn,
.reserve-btn{
    background:var(--primary);
    color:#fff;
    padding:8px 14px;
    border-radius:8px;
    text-decoration:none;
    font-size:14px;
}

.reserve-btn{
    background:var(--primary);
    color:#000;
    font-weight:bold;
}

.lang-switch{
    display:flex;
    gap:6px;
}

.lang-switch a{
    padding:6px 10px;
    border-radius:6px;
    background:var(--primary);
    color:#fff;
    text-decoration:none;
    font-size:13px;
}

.lang-switch a.active{
    background:var(--primary);
    color:#000;
    font-weight:bold;
}
@supports (-webkit-touch-callout: none) {
    .tabs{
        top: calc(env(safe-area-inset-top) + 1px);
    }
}



</style>
</head>

<body>
<div class="top-bar">

    <!-- زر الرجوع -->
    <a class="back-btn" href="../<?= $folder ?>/index.php?lang=<?= $lang ?>">
        ← <?= $lang=="ar" ? "رجوع" : ($lang=="ku" ? "گەڕانەوە" : "Back") ?>
    </a>

   <div class="lang-switch">
    <a href="<?= langUrl('ar', $params) ?>" class="<?= $currentLang=='ar'?'active':'' ?>">AR</a>
    <a href="<?= langUrl('ku', $params) ?>" class="<?= $currentLang=='ku'?'active':'' ?>">KU</a>
    <a href="<?= langUrl('en', $params) ?>" class="<?= $currentLang=='en'?'active':'' ?>">EN</a>
</div>


    <!-- زر الحجز -->
    <?php if (!empty($restaurant['reservations_enabled'])): ?>
    <a class="reserve-btn"
       href="../<?= $folder ?>/reservation.php?lang=<?= $lang ?>">
        <?= $lang=="ar"
            ? "احجز الآن"
            : ($lang=="ku"
                ? "پێشوەخت حجز بکە"
                : "Reserve Now")
        ?>
    </a>
<?php endif; ?>


</div>



<!-- HERO -->
<div class="simple-hero">
    <div class="overlay"></div>
    <?php if($restaurant['logo']): ?>
        <img class="logo" src="../uploads/Logo/<?= $restaurant['logo'] ?>">
    <?php endif; ?>
</div>


<!-- BANNERS SLIDER -->
<?php if(count($banners)): ?>
<div class="banner-slider">
    <div class="banner-track" id="bnTrack">
        <?php foreach($banners as $b): ?>
        <div class="bn-slide">
            <div class="bn-card">
                <img src="../uploads/Banners/<?= $b['image'] ?>" 
                     onerror="this.src='../assets/no-banner.png'">
            </div>
        </div>
        <?php endforeach; ?>
    </div>
</div>

<?php if(count($banners) > 1): ?>
<div class="banner-dots" id="bnDots"></div>
<?php endif; ?>
<?php endif; ?>


<!-- TABS -->
<div class="tabs" id="tabs">
<?php foreach($categories as $cat): ?>
    <a href="#cat<?= $cat['id'] ?>"
       onclick="scrollToCat(event, 'cat<?= $cat['id'] ?>')">
       <?= $cat["name_{$lang}"] ?: $cat['name'] ?>
    </a>
<?php endforeach; ?>
</div>


<!-- CONTENT -->
<?php foreach($categories as $cat): ?>
<?php $cat_items = $menu_items[$cat['id']]; if(!count($cat_items)) continue; ?>

<div id="cat<?= $cat['id'] ?>" class="category-card">
    <?php if($cat['image']): ?>
        <img src="../uploads/Categories/<?= $cat['image'] ?>" class="category-img">
    <?php endif; ?>
    <div class="category-name">
        <?= $cat["name_{$lang}"] ?: $cat['name'] ?>
    </div>
</div>

<div class="items-grid">
<?php foreach($cat_items as $it): ?>
<?php 
$likes = get_item_likes($it['id'], $branch_id); 
$userLiked = user_liked_item($it['id'], $branch_id);
$opt_count = fetch_value("SELECT COUNT(*) FROM item_options WHERE item_id=? AND active=1", [$it['id']]);
?>
<div class="grid-item" onclick="openItem(<?= $it['id'] ?>)">
    <span class="like-count"><?= $likes ?></span>
    <span class="heart <?= $userLiked?'liked':'' ?>" 
        onclick="event.stopPropagation(); toggleLike(<?= $it['id'] ?>)">🤍</span>

    <img src="../uploads/Items/<?= $it['image'] ?>">

    <div class="grid-info">
        <div class="grid-title"><?= $it["name_{$lang}"] ?: $it['name'] ?></div>

        <?php if($it['old_price']): ?>
            <div class="grid-price"><?= $it['final_price'] ?> IQD</div>
            <div class="grid-old"><?= $it['old_price'] ?> IQD</div>
        <?php else: ?>
            <div class="grid-price"><?= $it['final_price'] ?> IQD</div>
        <?php endif; ?>

        <?php if($opt_count > 0): ?>
        <div style="font-size:13px;color:#ffd966;margin-top:4px;">
            + <?= ($lang=='en'?'Add-ons':($lang=='ku'?'زیادەکاری':'إضافات')) ?>
        </div>
        <?php endif; ?>
    </div>
</div>
<?php endforeach; ?>
</div>

<?php endforeach; ?>


<!-- BOTTOM SHEET -->
<div id="sheet" class="bottom-sheet">
    <div class="sheet-close"></div>
    <iframe id="itemFrame" style="width:100%; height:95%; border:0; border-radius:15px;"></iframe>
</div>


<script>
/* ======================
   BANNERS LOGIC
====================== */
<?php if(count($banners) > 1): ?>

let bn_i = 0;
const bnTrack = document.getElementById("bnTrack");
const bnSlides = document.querySelectorAll(".bn-slide");
const dotsBox = document.getElementById("bnDots");

/* DOTS */
bnSlides.forEach((_,i)=>{
    let d = document.createElement("span");
    if(i==0) d.classList.add("active");
    d.onclick = ()=>{ bn_i = i; moveBanner(); };
    dotsBox.appendChild(d);
});
const dots=document.querySelectorAll(".banner-dots span");

function updateDots(){
    dots.forEach((d,i)=>d.classList.toggle("active",i==bn_i));
}
function moveBanner(){
    const slide = bnSlides[bn_i];
    const left = slide.offsetLeft - 12; // padding
    bnTrack.parentElement.scrollTo({ left, behavior:"smooth" });
    updateDots();
}


/* AUTO SLIDE */
setInterval(()=>{
    bn_i = (bn_i + 1) % bnSlides.length;
    moveBanner();
},3500);

/* TOUCH SWIPE */
let sx=0, dx=0;
bnTrack.addEventListener("touchstart", e=>sx=e.touches[0].clientX);
bnTrack.addEventListener("touchmove", e=>dx=e.touches[0].clientX-sx);
bnTrack.addEventListener("touchend", ()=>{
    if(Math.abs(dx)>50){
        bn_i = dx<0 ? (bn_i+1)%bnSlides.length : (bn_i-1+bnSlides.length)%bnSlides.length;
        moveBanner();
    }
    dx=0;
});

<?php endif; ?>


/* ======================
   OPEN ITEM IN SHEET
====================== */
function openItem(id){
    const url =
        "item.php?id="+id+"&branch=<?= $branch_id ?>&lang=<?= $lang ?>";
    document.getElementById("itemFrame").src = url;
    document.getElementById("sheet").classList.add("active");
}


/* ======================
   LIKE
====================== */
function toggleLike(item_id){
    fetch("like.php",{
        method:"POST",
        headers:{"Content-Type":"application/json"},
        body:JSON.stringify({
            item_id:item_id, 
            branch_id:<?= $branch_id ?>
        })
    }).then(r=>r.json()).then(res=>{
        if(res.success) location.reload();
    });
}


/* ACTIVE TAB SCROLL SYNC */
const sections=document.querySelectorAll('.category-card');
const navlinks=document.querySelectorAll('.tabs a');
const tabs=document.getElementById("tabs");

window.addEventListener('scroll',()=>{
    let c="";
    sections.forEach(sec=>{
        if(window.scrollY >= sec.offsetTop-150) c = sec.id;
    });

    navlinks.forEach(a=>{
        a.classList.remove("active");

        if(a.getAttribute("href") == "#" + c){
            a.classList.add("active");

            /* تحريك الشريط فقط – بدون تحريك المنيو */
            tabs.scrollTo({
                left: a.offsetLeft - 80,
                behavior: "smooth"
            });
        }
    });
});


/* ======================
   SCROLL TO CATEGORY
====================== */
function scrollToCat(e, id){
    e.preventDefault();
    const el = document.getElementById(id);
    const offset = 85;
    const y = el.getBoundingClientRect().top + window.pageYOffset - offset;
    window.scrollTo({ top: y, behavior: "smooth" });
}


/* CLOSE BOTTOM SHEET (from item.php) */
function closeSheet(){
    document.getElementById("sheet").classList.remove("active");
}

</script>
<?php
$footer_path = realpath(__DIR__ . '/../includes/footer.php');
if (!$footer_path) {
    $footer_path = realpath(__DIR__ . '/../../includes/footer.php');
}
if (!$footer_path) {
    $footer_path = realpath(__DIR__ . '/../../../includes/footer.php');
}
if ($footer_path) include $footer_path;
?>

</body>
</html>
