<?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";

/* INPUT */
$item_id   = $_GET['id'] ?? null;
$branch_id = $_GET['branch'] ?? null;
$lang      = $_GET['lang'] ?? "ar";
$_SESSION['lang']=$lang;

if(!$item_id || !$branch_id) die("Missing parameters");

/* BRANCH */
$branch = get_branch($branch_id);
if(!$branch) die("Branch Not Found");

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

/* ITEM */
$item = get_item_details($item_id,$branch_id,$restaurant['id']);
if(!$item) die("Item Not Found");

$item_image = $item['image']
    ? "/menu/uploads/Items/{$item['image']}"
    : "/menu/uploads/no-image.png";

$item_link = "https://".$_SERVER['HTTP_HOST']."/menu/{$folder}/item.php?id={$item_id}&branch={$branch_id}&lang={$lang}";
$image_link = "https://".$_SERVER['HTTP_HOST']."{$item_image}";

$primary_color = $restaurant['secondary_color'] ?: "#ff7a00";

/* TRACK VISIT */
try{
    db()->prepare("
        INSERT INTO visits (branch_id,restaurant_id,page,item_id,ip,user_agent,created_at)
        VALUES (?,?,?,?,?,?,NOW())
    ")->execute([
        $branch_id,
        $restaurant['id'],
        'item',
        $item_id,
        $_SERVER['REMOTE_ADDR'] ?? null,
        $_SERVER['HTTP_USER_AGENT'] ?? null
    ]);
}catch(Exception $e){}

?>
<!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><?= $item["name_{$lang}"] ?: $item['name'] ?></title>

<style>
html,body{
    margin:0;
    background:#000;
    color:#fff;
    font-family:'Tajawal',sans-serif;
    overflow-x:hidden;
}

/* HEADER - LIKE TALABAT */
.header-wrap{
    width:100%;
    background:#000;
    display:flex;
    justify-content:center;
    align-items:center;
    padding:0;
}
.header-img{
    width:100%;
    max-width:480px;
    height:auto;
    display:block;
    border-bottom:1px solid #222;
}

/* BACK BUTTON */
.back-btn{
    position:absolute;
    top:15px;
    <?= $lang=='ar'?'right:15px;':'left:15px;' ?>
    width:44px;
    height:44px;
    background:rgba(0,0,0,0.55);
    border-radius:50%;
    border:1px solid rgba(255,255,255,0.2);
    display:flex;
    align-items:center;
    justify-content:center;
    cursor:pointer;
    z-index:50;
}

/* LIKE BUTTON */
.like-btn{
    position:absolute;
    top:15px;
    <?= $lang=='ar'?'left:15px;':'right:15px;' ?>
    width:44px;height:44px;
    background:rgba(0,0,0,0.55);
    border:1px solid rgba(255,255,255,0.2);
    border-radius:50%;
    display:flex;
    align-items:center;
    justify-content:center;
    cursor:pointer;
    z-index:50;
}
.like-btn svg{
    width:26px;height:26px;
    fill:#fff;
}
.like-btn.liked svg{ fill:#ff2a2a; }

/* CONTENT */
.content-box{
    max-width:480px;
    margin:0 auto;
    padding:20px;
    background:#111;
    border-radius:25px 25px 0 0;
    margin-top:-20px;
    position:relative;
    z-index:10;
}

/* TITLE & SHARE */
.item-title-row{
    display:flex;
    align-items:center;
    justify-content:space-between;
}
.item-title{
    font-size:24px;
    font-weight:700;
}

/* SHARE BUTTON (NEXT TO TITLE) */
.share-btn2{
    cursor:pointer;
    padding:6px;
    display:flex;
    align-items:center;
}
.share-btn2 svg{
    width:26px;height:26px;
    fill:#fff;
}

/* PRICE */
.item-price{
    font-size:24px;
    font-weight:bold;
    color:<?= $primary_color ?>;
    margin-top:10px;
}
.old-price{
    color:#888;
    margin:0 8px;
    text-decoration:line-through;
}

/* DESCRIPTION */
.item-desc{
    margin-top:15px;
    font-size:16px;
    color:#ccc;
    line-height:1.7;
}

/* OPTIONS */
.options-header{
    font-size:20px;
    font-weight:600;
    margin-top:28px;
    margin-bottom:10px;
}
.option-box{
    background:#1a1a1a;
    border-radius:14px;
    padding:12px;
    margin-bottom:12px;
    display:flex;
    align-items:center;
}
.option-box img{
    width:85px;
    height:85px;
    border-radius:12px;
    object-fit:cover;
    margin-<?= $lang=='ar'?'left':'right' ?>:12px;
}
.option-title{ flex:1; font-size:16px; }
.option-price{
    color:<?= $primary_color ?>;
    font-weight:bold;
    font-size:16px;
}

/* Large Screens */
@media(min-width:600px){
    .header-img{ border-radius:0 0 18px 18px; }
}
</style>
</head>
<!-- Open Graph -->
<meta property="og:title" content="<?= htmlspecialchars($item["name_$lang"] ?: $item['name']) ?>" />
<meta property="og:description" content="<?= number_format($item['final_price'],0) ?> IQD" />
<meta property="og:image" content="<?= $image_link ?>" />
<meta property="og:url" content="<?= $item_link ?>" />
<meta property="og:type" content="product" />

<!-- Twitter Card (للسوشال) -->
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="<?= htmlspecialchars($item["name_$lang"] ?: $item['name']) ?>" />
<meta name="twitter:description" content="<?= number_format($item['final_price'],0) ?> IQD" />
<meta name="twitter:image" content="<?= $image_link ?>" />

<body>

<!-- HEADER IMAGE CENTERED LIKE TALABAT -->
<div class="header-wrap">
    <img class="header-img" src="<?= $item_image ?>" onerror="this.src='/menu/uploads/no-image.png'">
</div>

<!-- BACK BTN -->
<div class="back-btn" onclick="goBack()">
    <svg viewBox="0 0 24 24">
        <path d="M15 18l-6-6 6-6"/>
    </svg>
</div>

<!-- LIKE BTN -->
<?php $liked = user_liked_item($item['id'],$branch_id); ?>
<div class="like-btn <?= $liked?'liked':'' ?>" onclick="toggleLikeItem(<?= $item['id'] ?>)">
    <svg viewBox="0 0 24 24">
        <path d="M12 21s-6.7-4.35-9.33-8C-1 9.2.5 5.5 3.7 4.2c2.1-.8 4.4.1 5.6 2 1.2-1.9 3.5-2.8 5.6-2 3.2 1.3 4.7 5 2.97 8.8C18.7 16.65 12 21 12 21z"/>
    </svg>
</div>

<!-- CONTENT -->
<div class="content-box">

    <!-- TITLE + SHARE -->
    <div class="item-title-row">
        <div class="item-title"><?= $item["name_{$lang}"] ?: $item['name'] ?></div>

        <div class="share-btn2" onclick="shareItem()">
            <svg viewBox="0 0 24 24">
                <circle cx="6" cy="12" r="3"/>
                <circle cx="18" cy="6" r="3"/>
                <circle cx="18" cy="18" r="3"/>
                <line x1="8.5" y1="10.5" x2="15.5" y2="7.5" stroke="#fff" stroke-width="2" stroke-linecap="round"/>
                <line x1="8.5" y1="13.5" x2="15.5" y2="16.5" stroke="#fff" stroke-width="2" stroke-linecap="round"/>
            </svg>
        </div>
    </div>

    <!-- PRICE -->
    <div class="item-price">
        <?= number_format($item['final_price'],0) ?> IQD
        <?php if($item['old_price']): ?>
        <span class="old-price"><?= number_format($item['old_price'],0) ?> IQD</span>
        <?php endif; ?>
    </div>

    <!-- DESCRIPTION -->
    <div class="item-desc">
        <?= $item["description_{$lang}"] ?: $item['description'] ?>
    </div>

    <!-- OPTIONS -->
    <?php $options=get_item_options($item['id']); if(count($options)): ?>
    <div class="options-header">إضافات</div>
    <?php foreach($options as $op): ?>
        <div class="option-box">
            <img src="../uploads/Options/<?= $op['image'] ?>" onerror="this.src='/menu/uploads/no-image.png'">
            <div class="option-title"><?= $op["name_$lang"] ?: $op['name_ar'] ?></div>
            <div class="option-price"><?= $op['price'] ?> IQD</div>
        </div>
    <?php endforeach; ?>
    <?php endif; ?>

</div>

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

/* SHARE */
function shareItem(){
    const link = "<?= $item_link ?>";

    if(navigator.share){
        navigator.share({
            title: "<?= addslashes($item["name_$lang"] ?: $item['name']) ?>",
            url: link
        });
    } else {
        navigator.clipboard.writeText(link);
        alert("تم نسخ رابط المنتج");
    }
}
function goBack(){
    // الحالة 1: فاتح داخل Bottom Sheet
    if (window.parent && typeof window.parent.closeSheet === "function") {
        window.parent.closeSheet();
        return;
    }

    // الحالة 2: الصفحة مفتوحة مباشرة من رابط المشاركة
    const menuURL = "../<?= $folder ?>/menu.php?branch=<?= $branch_id ?>&lang=<?= $lang ?>";

    // إذا لديه تاريخ رجوع (back) استخدمه
    if (document.referrer && document.referrer.includes("menu.php")) {
        history.back();
    } else {
        window.location.href = menuURL;
    }
}

</script>

</body>
</html>
