<?php
require_once __DIR__ . "/includes/auth.php";
ensure_super_admin();

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

/*
    ملاحظة: لازم تنفذ SQL أولاً لإضافة account_fee:
    ALTER TABLE restaurants ADD COLUMN account_fee INT NOT NULL DEFAULT 0 AFTER discounts_enabled;
*/

$restaurants = fetch_all("
    SELECT
        r.*,
        (SELECT COUNT(*) FROM branches b WHERE b.restaurant_id = r.id) AS branch_count,
        (
            SELECT GROUP_CONCAT(l.code ORDER BY l.id SEPARATOR ',')
            FROM restaurant_languages rl
            JOIN languages l ON l.id = rl.language_id
            WHERE rl.restaurant_id = r.id AND rl.active = 1
        ) AS langs_codes
    FROM restaurants r
    ORDER BY r.id DESC
");

// لون الأيام المتبقية
function sub_color($days){
    if ($days < 10) return "red";
    if ($days < 20) return "yellow";
    return "green";
}

function flag_badge($v){
    return $v ? '<span class="badge green">مفعل</span>' : '<span class="badge red">متوقف</span>';
}

function lang_badges($codes_csv){
    if(!$codes_csv) return '—';
    $codes = array_filter(array_map('trim', explode(',', $codes_csv)));
    if(!count($codes)) return '—';

    $map = [
        'ar' => 'AR',
        'en' => 'EN',
        'ku' => 'KU'
    ];

    $out = [];
    foreach($codes as $c){
        $label = $map[$c] ?? strtoupper($c);
        $out[] = '<span class="chip">'.htmlspecialchars($label).'</span>';
    }
    return implode(' ', $out);
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8">
<title>إدارة المطاعم</title>
<meta name="viewport" content="width=device-width, initial-scale=1">

<style>
body{
    margin:0;
    padding:0;
    background:#0f0f11;
    font-family:"Tajawal",sans-serif;
    color:#fff;
    display:flex;
}

/* ==== SIDEBAR ==== */
.sidebar{
    width:260px;
    background:#15151a;
    height:100vh;
    position:fixed;
    right:0;
    top:0;
    padding:25px;
    border-left:1px solid #302f3a;
}

.sidebar h3{
    color:#9c6bff;
    font-size:22px;
    margin-bottom:25px;
}

.sidebar a{
    display:block;
    padding:12px 16px;
    background:#1e1d26;
    margin-bottom:10px;
    color:#fff;
    text-decoration:none;
    border-radius:8px;
    border:1px solid #2a2933;
    transition:0.2s;
}
.sidebar a:hover{
    background:#9c6bff;
    color:#000;
}

/* ==== CONTENT ==== */
.content{
    margin-right:300px;
    padding:35px;
    width:100%;
}

.page-title{
    font-size:26px;
    color:#9c6bff;
    margin-bottom:25px;
}

.btn-add{
    padding:12px 20px;
    background:#9c6bff;
    color:#000;
    border:none;
    border-radius:8px;
    font-weight:bold;
    text-decoration:none;
}
.btn-add:hover{ opacity:0.85; }

/* ==== TABLE ==== */
.table-box{
    background:#1b1b22;
    padding:20px;
    border-radius:12px;
    border:1px solid #2a2933;
}

table{
    width:100%;
    border-collapse:collapse;
}

th, td{
    padding:12px;
    border-bottom:1px solid #2a2933;
    vertical-align:top;
}

th{
    background:#26252f;
    color:#9c6bff;
    text-align:right;
    white-space:nowrap;
}

.badge{
    padding:6px 10px;
    border-radius:6px;
    color:#000;
    font-weight:bold;
    display:inline-block;
    white-space:nowrap;
}
.red { background:#ff4f4f; }
.yellow { background:#ffe15d; }
.green { background:#73ff81; }

.btn-sm{
    padding:6px 10px;
    background:#9c6bff;
    color:#000;
    text-decoration:none;
    border-radius:6px;
    font-weight:bold;
    display:inline-block;
    white-space:nowrap;
}
.btn-sm:hover{ opacity:0.85; }

.btn-danger{
    background:#ff4f4f;
    color:#000;
}
.btn-dark{
    background:#333;
    color:#fff;
}

.chip{
    display:inline-block;
    padding:5px 10px;
    border-radius:999px;
    background:#222;
    border:1px solid #333;
    color:#fff;
    font-size:12px;
    margin:2px 4px 2px 0;
}
.small{
    font-size:12px;
    color:#bbb;
}
.fw{font-weight:bold;}
</style>

</head>
<body>

<?php include "includes/sidebar.php"; ?>

<div class="content">

<h2 class="page-title">إدارة المطاعم</h2>

<a href="restaurant_add.php" class="btn-add">+ إضافة مطعم جديد</a>

<br><br>

<div class="table-box">

<table>
    <tr>
        <th>اسم المطعم</th>
        <th>عدد الفروع</th>
        <th>اللغات</th>
        <th>نوع الاشتراك</th>
        <th>المدة المتبقية</th>
        <th>الرسوم</th>
        <th>الحالة</th>
        <th>الميزات</th>
        <th>روابط</th>
        <th>QR</th>
        <th>تحكم</th>
    </tr>

    <?php foreach ($restaurants as $r): ?>
        <?php
            // حساب الأيام المتبقية
            if (!empty($r['subscription_end'])) {
                $days = (int)ceil((strtotime($r['subscription_end']) - time()) / 86400);
                if ($days < 0) $days = 0;
            } else {
                $days = null;
            }

            $folder = $r['folder_name'] ?? '';
            $front_link = $folder ? ("https://meta-qr.com/menu/".$folder."/") : '';
            $manager_link = "https://meta-qr.com/menu/manager/?r=".$r['id'];
        ?>

        <tr>
            <td class="fw"><?= htmlspecialchars($r['name'] ?? '') ?></td>

            <td><?= (int)($r['branch_count'] ?? 0) ?></td>

            <td><?= lang_badges($r['langs_codes'] ?? '') ?></td>

            <td><?= htmlspecialchars($r['subscription_type'] ?? '—') ?></td>

            <td>
                <?php if ($days !== null): ?>
                    <span class="badge <?= sub_color($days) ?>"><?= $days ?> يوم</span>
                <?php else: ?>
                    —
                <?php endif; ?>
            </td>

            <td>
                <?= number_format((int)($r['fees'] ?? 0), 0) ?>
                <div class="small">USD</div>
            </td>

            <td>
                <span class="badge <?= !empty($r['active']) ? 'green' : 'red' ?>">
                    <?= !empty($r['active']) ? "فعال" : "متوقف" ?>
                </span>
            </td>

            <td>
                <div class="small">
                    الحجوزات: <?= flag_badge((int)($r['reservations_enabled'] ?? 0)) ?><br>
                    الطلبات: <?= flag_badge((int)($r['orders_enabled'] ?? 0)) ?><br>
                    التقارير: <?= flag_badge((int)($r['reports_enabled'] ?? 0)) ?><br>
                    الخصومات: <?= flag_badge((int)($r['discounts_enabled'] ?? 0)) ?>
                </div>
            </td>

            <td>
                <button class="btn-sm btn-dark" onclick="copyLink('<?= htmlspecialchars($manager_link, ENT_QUOTES) ?>')">لوحة المدير</button>
                <?php if($front_link): ?>
                    <button class="btn-sm btn-dark" onclick="copyLink('<?= htmlspecialchars($front_link, ENT_QUOTES) ?>')">واجهة المطعم</button>
                <?php else: ?>
                    <span class="small">لا يوجد folder_name</span>
                <?php endif; ?>
            </td>

            <td>
                <a href="restaurant_qr.php?id=<?= (int)$r['id'] ?>" class="btn-sm">QR</a>
            </td>

            <td>
                <a href="restaurant_edit.php?id=<?= (int)$r['id'] ?>" class="btn-sm">تعديل</a>
                <a href="delete_restaurant.php?id=<?= (int)$r['id'] ?>"
                   class="btn-sm btn-danger"
                   onclick="return confirm('تأكيد؟')">حذف</a>
            </td>
        </tr>

    <?php endforeach; ?>

</table>

</div>

</div>

<script>
function copyLink(link){
    navigator.clipboard.writeText(link);
    alert("تم نسخ الرابط:\n" + link);
}
</script>

</body>
</html>
