<?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 = (int)($_SESSION['restaurant_id'] ?? 0);
if(!$restaurant_id) die("Restaurant session missing");

$restaurant = fetch_one("SELECT * FROM restaurants WHERE id=?", [$restaurant_id]);
if(!$restaurant || !is_array($restaurant)) die("Restaurant Not Found");

// ✅ fallback يمنع التحذير حتى لو العمود مو موجود/مو راجع
$social_mode = $restaurant['social_mode'] ?? 'same';
if(!in_array($social_mode, ['same','custom'])) $social_mode = 'same';

$branches = get_branches($restaurant_id);

/* ===================== ICONS LIST ===================== */
$icons = [
    ["name"=>"Facebook","icon"=>"fa-brands fa-facebook","url"=>"https://facebook.com/"],
    ["name"=>"Instagram","icon"=>"fa-brands fa-instagram","url"=>"https://instagram.com/"],
    ["name"=>"TikTok","icon"=>"fa-brands fa-tiktok","url"=>"https://www.tiktok.com/@username"],
    ["name"=>"Snapchat","icon"=>"fa-brands fa-snapchat","url"=>"https://www.snapchat.com/add/username"],
    ["name"=>"YouTube","icon"=>"fa-brands fa-youtube","url"=>"https://youtube.com/"],
    ["name"=>"Telegram","icon"=>"fa-brands fa-telegram","url"=>"https://t.me/username"],
    ["name"=>"WhatsApp","icon"=>"fa-brands fa-whatsapp","url"=>"PHONE_ONLY"],
];

/* ===================== HELPERS ===================== */
function wa_url($input){
    $input = trim((string)$input);
    // إذا دخل رابط كامل
    if (stripos($input, 'wa.me') !== false) return $input;

    // digits فقط
    $digits = preg_replace('/\D+/', '', $input);
    $digits = ltrim($digits, '0');

    if($digits === '') return '';
    return "https://wa.me/" . $digits;
}

function go_back_after_action(){
    $branch_id = isset($_GET['branch']) ? (int)$_GET['branch'] : 0;
    if($branch_id > 0) {
        header("Location: social.php?branch=".$branch_id);
    } else {
        header("Location: social.php");
    }
    exit;
}

/* =====================
   SORT ORDER (from Sortable)
   يقبل order كـ array أو string
===================== */
if(isset($_POST['order'])){
    $order = $_POST['order'];

    // ممكن يجي "1,2,3" أو array
    if(!is_array($order)){
        $order = explode(",", (string)$order);
    }

    $branch_id = isset($_GET['branch']) ? (int)$_GET['branch'] : 0;

    if($branch_id > 0){
        $upd = db()->prepare("UPDATE branch_social SET ordering=? WHERE id=? AND branch_id=?");
        $pos = 1;
        foreach($order as $sid){
            $sid = (int)$sid;
            if($sid>0) $upd->execute([$pos++, $sid, $branch_id]);
        }
    }else{
        $upd = db()->prepare("UPDATE restaurant_social SET ordering=? WHERE id=? AND restaurant_id=?");
        $pos = 1;
        foreach($order as $sid){
            $sid = (int)$sid;
            if($sid>0) $upd->execute([$pos++, $sid, $restaurant_id]);
        }
    }

    echo "OK";
    exit;
}

/* ===================== SAVE MODE ===================== */
if (isset($_POST["save_mode"])) {
    $new_mode = clean($_POST['social_mode'] ?? 'same');
    if(!in_array($new_mode, ['same','custom'])) $new_mode = 'same';

    // إذا جدولك فعلاً فيه العمود رح يتحدث، وإذا لا: على الأقل الصفحة ما بتنهار بفضل fallback
    db()->prepare("UPDATE restaurants SET social_mode=? WHERE id=?")
       ->execute([$new_mode, $restaurant_id]);

    header("Location: social.php?saved=1"); exit;
}

/* ===================== ADD SOCIAL (GLOBAL) ===================== */
if (isset($_POST['add_social_global']) && $social_mode==='same') {

    $icon = clean($_POST['icon'] ?? '');
    $url  = clean($_POST['url']  ?? '');

    if ($url && str_contains($icon, "whatsapp")) $url = wa_url($url);
    if($url === '') { header("Location: social.php"); exit; }

    db()->prepare("INSERT INTO restaurant_social (restaurant_id, icon, url, active, ordering)
                   VALUES (?,?,?,?,999)")
      ->execute([$restaurant_id, $icon, $url, 1]);

    header("Location: social.php"); exit;
}

/* ===================== ADD SOCIAL (BRANCH) ===================== */
if (isset($_POST['add_social_branch']) && $social_mode==='custom') {

    $icon = clean($_POST['icon'] ?? '');
    $url  = clean($_POST['url']  ?? '');
    $branch_id = (int)($_POST['branch_id'] ?? 0);

    if ($url && str_contains($icon, "whatsapp")) $url = wa_url($url);
    if($url === '' || $branch_id<=0) { header("Location: social.php"); exit; }

    db()->prepare("INSERT INTO branch_social (branch_id, icon, url, active, ordering)
                   VALUES (?,?,?,?,999)")
      ->execute([$branch_id, $icon, $url, 1]);

    header("Location: social.php?branch=$branch_id"); exit;
}

/* ===================== TOGGLE / DELETE ===================== */
if (isset($_GET['toggle'])) {
    $id = (int)$_GET['toggle'];
    $type = $_GET['type'] ?? 'global';

    if($type === "branch"){
        // تأكد أنه ضمن الفرع المختار (إن وجد)
        $branch_id = isset($_GET['branch']) ? (int)$_GET['branch'] : 0;
        if($branch_id>0){
            db()->prepare("UPDATE branch_social SET active = NOT active WHERE id=? AND branch_id=?")
              ->execute([$id, $branch_id]);
        }else{
            db()->prepare("UPDATE branch_social SET active = NOT active WHERE id=?")
              ->execute([$id]);
        }
    }else{
        db()->prepare("UPDATE restaurant_social SET active = NOT active WHERE id=? AND restaurant_id=?")
          ->execute([$id, $restaurant_id]);
    }

    go_back_after_action();
}

if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $type = $_GET['type'] ?? 'global';

    if($type === "branch"){
        $branch_id = isset($_GET['branch']) ? (int)$_GET['branch'] : 0;
        if($branch_id>0){
            db()->prepare("DELETE FROM branch_social WHERE id=? AND branch_id=?")
              ->execute([$id, $branch_id]);
        }else{
            db()->prepare("DELETE FROM branch_social WHERE id=?")
              ->execute([$id]);
        }
    }else{
        db()->prepare("DELETE FROM restaurant_social WHERE id=? AND restaurant_id=?")
          ->execute([$id, $restaurant_id]);
    }

    go_back_after_action();
}

include "includes/header.php";
?>

<div class="content">

<h2 class="page-title">إعدادات مواقع التواصل</h2>

<?php if(isset($_GET['saved'])) echo '<div class="msg success">تم الحفظ</div>'; ?>

<!-- ======= SELECT MODE ======= -->
<div class="card">
<form method="post">
    <label>نمط السوشال</label>
    <select name="social_mode">
        <option value="same" <?= $social_mode==='same'?'selected':'' ?>>نفس الروابط لكل الفروع</option>
        <option value="custom" <?= $social_mode==='custom'?'selected':'' ?>>لكل فرع روابط خاصة</option>
    </select>
    <button name="save_mode" class="save-btn">حفظ</button>
</form>
</div>

<?php if($social_mode==='same'): ?>
<!-- ===================== GLOBAL ===================== -->

<div class="card">
<form method="post">
    <h3>روابط لجميع الفروع</h3>

    <label>المنصة</label>
    <select name="icon" id="icon_select" onchange="previewIcon()" required>
        <option disabled selected>اختر منصة</option>
        <?php foreach($icons as $i): ?>
        <option value="<?= $i['icon'] ?>" data-pre="<?= $i['url'] ?>"><?= $i['name'] ?></option>
        <?php endforeach; ?>
    </select>

    <label>الرابط / الرقم</label>
    <input type="text" name="url" id="input_url" placeholder="سيتم تحديد الشكل تلقائياً" required>

    <div class="icon-preview" id="previewBox"><i class="fa-brands fa-facebook"></i></div>

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

<ul id="socialList" class="social-list">
<?php foreach(fetch_all("SELECT * FROM restaurant_social WHERE restaurant_id=? ORDER BY ordering", [$restaurant_id]) as $s): ?>
<li data-id="<?= (int)$s['id'] ?>">
    <i class="<?= $s['icon'] ?>"></i>
    <span><?= htmlspecialchars($s['url'] ?? '') ?></span>
    <div class="actions">
        <a href="?toggle=<?= (int)$s['id'] ?>&type=global" class="btn-sm"><?= ((int)$s['active']) ? 'إيقاف':'تفعيل' ?></a>
        <a href="?delete=<?= (int)$s['id'] ?>&type=global" class="btn-delete" onclick="return confirm('حذف؟')">حذف</a>
    </div>
</li>
<?php endforeach; ?>
</ul>

<?php else: ?>
<!-- ===================== CUSTOM BRANCH ===================== -->

<h3>روابط كل فرع</h3>

<select onchange="location='social.php?branch='+this.value" class="branch-select">
    <option disabled <?= !isset($_GET['branch'])?'selected':'' ?>>اختر فرعًا</option>
    <?php foreach($branches as $b): ?>
    <option value="<?= (int)$b['id'] ?>" <?= (isset($_GET['branch']) && (int)$_GET['branch']==(int)$b['id'])?'selected':'' ?>>
        <?= htmlspecialchars($b['name_ar'] ?? $b['name'] ?? '') ?>
    </option>
    <?php endforeach; ?>
</select>

<?php if(isset($_GET['branch'])): $branch_id=(int)$_GET['branch']; ?>

<div class="card">
<form method="post">
    <input type="hidden" name="branch_id" value="<?= $branch_id ?>">

    <label>المنصة</label>
    <select name="icon" id="icon_select" onchange="previewIcon()" required>
        <option disabled selected>اختر منصة</option>
        <?php foreach($icons as $i): ?>
        <option value="<?= $i['icon'] ?>" data-pre="<?= $i['url'] ?>"><?= $i['name'] ?></option>
        <?php endforeach; ?>
    </select>

    <label>الرابط / الرقم</label>
    <input type="text" name="url" id="input_url" placeholder="سيتم تحديد الشكل تلقائياً" required>

    <div class="icon-preview" id="previewBox"><i class="fa-brands fa-facebook"></i></div>

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

<ul id="socialList" class="social-list">
<?php foreach(fetch_all("SELECT * FROM branch_social WHERE branch_id=? ORDER BY ordering", [$branch_id]) as $s): ?>
<li data-id="<?= (int)$s['id'] ?>">
    <i class="<?= $s['icon'] ?>"></i>
    <span><?= htmlspecialchars($s['url'] ?? '') ?></span>
    <div class="actions">
        <a href="?branch=<?= $branch_id ?>&toggle=<?= (int)$s['id'] ?>&type=branch" class="btn-sm"><?= ((int)$s['active']) ? 'إيقاف':'تفعيل' ?></a>
        <a href="?branch=<?= $branch_id ?>&delete=<?= (int)$s['id'] ?>&type=branch" class="btn-delete" onclick="return confirm('حذف؟')">حذف</a>
    </div>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>

<?php endif; ?>
</div>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css">

<style>
.card{background:#1c1c1c;padding:20px;border-radius:12px;border:1px solid #333;margin-bottom:25px;}
.page-title{margin-bottom:15px;color:#ff7a00;}
.msg.success{background:#008f39;padding:10px;border-radius:8px;color:#fff;margin:10px 0;text-align:center}
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;border-radius:8px;font-weight:bold;cursor:pointer}
.social-list{list-style:none;padding:0;margin-top:20px}
.social-list li{background:#1e1e1e;padding:10px;border-radius:10px;display:flex;align-items:center;gap:15px;margin-bottom:10px;cursor:move}
.social-list li i{font-size:22px;color:#ffbb00}
.branch-select{padding:10px;border-radius:8px;background:#111;border:1px solid #444;color:#fff;margin-bottom:15px}
.actions{margin-right:auto}
.btn-sm{background:#ffc107;padding:6px 10px;border-radius:6px;color:#000;text-decoration:none}
.btn-delete{background:#b00000;padding:6px 10px;border-radius:6px;color:#fff;text-decoration:none}
.icon-preview{text-align:center;padding:10px;font-size:30px;margin-bottom:10px;color:#ff7a00}
</style>

<script src="https://cdnjs.cloudflare.com/ajax/libs/Sortable/1.15.0/Sortable.min.js"></script>
<script>
// PREVIEW + ADD PREFIX
function previewIcon(){
    let s = document.getElementById("icon_select");
    let icon = s.value;
    let pre = s.options[s.selectedIndex].getAttribute("data-pre");
    document.getElementById("previewBox").innerHTML = `<i class="${icon}"></i>`;
    document.getElementById("input_url").placeholder = (pre==="PHONE_ONLY") ? "رقم بدون +" : pre;
}

// SORT ORDER
const list = document.getElementById("socialList");
if(list){
    new Sortable(list, {
        animation:150,
        onEnd: () => {
            const order = [...document.querySelectorAll("#socialList li")].map(li => li.dataset.id);
            const params = new URLSearchParams();
            order.forEach(id => params.append("order[]", id));

            // إذا نحن بفرع، نخلي الباك اند يعرف من خلال ?branch=...
            const url = new URL(window.location.href);

            fetch(url.toString(), {
                method:"POST",
                headers:{"Content-Type":"application/x-www-form-urlencoded"},
                body: params.toString()
            }).catch(()=>{});
        }
    });
}
</script>
