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

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

$id = (int)($_GET['id'] ?? 0);
$restaurant = fetch_one("SELECT * FROM restaurants WHERE id = ?", [$id]);

if (!$restaurant) die("المطعم غير موجود");

$success = "";
$error   = "";

/* =========================
   Languages (from DB)
========================= */
$all_languages = fetch_all("SELECT id, name, code FROM languages ORDER BY id ASC");
$current_lang_ids = fetch_all("
    SELECT language_id
    FROM restaurant_languages
    WHERE restaurant_id = ? AND active = 1
", [$id]);
$current_lang_ids = $current_lang_ids ? array_map('intval', array_column($current_lang_ids, 'language_id')) : [];

/* =========================
   Helpers
========================= */
function slugify_folder($s){
    $s = (string)$s;
    $s = strtolower($s);
    $s = preg_replace('/[^a-z0-9]+/', '-', $s);
    $s = trim($s, '-');
    return $s;
}

if ($_SERVER['REQUEST_METHOD'] === "POST") {

    $name = clean($_POST['name'] ?? '');

    // this is the real field in your DB (not slug, not languages)
    $folder_name = clean($_POST['folder_name'] ?? ($restaurant['folder_name'] ?? ''));
    $folder_name = slugify_folder($folder_name);
    if ($folder_name === '') $folder_name = $restaurant['folder_name'];

    $active = isset($_POST['active']) ? 1 : 0;

    $reservations_enabled = isset($_POST['reservations_enabled']) ? 1 : 0;
    $orders_enabled       = isset($_POST['orders_enabled']) ? 1 : 0;
    $reports_enabled      = isset($_POST['reports_enabled']) ? 1 : 0;
    $discounts_enabled    = isset($_POST['discounts_enabled']) ? 1 : 0;

    $selected_lang_ids = $_POST['languages'] ?? [];
    $selected_lang_ids = array_values(array_unique(array_map('intval', $selected_lang_ids)));

    if ($name === '') {
        $error = "اسم المطعم مطلوب.";
    } else {
        try {
            db()->beginTransaction();

            db()->prepare("
                UPDATE restaurants
                SET
                    name=?,
                    folder_name=?,
                    active=?,
                    reservations_enabled=?,
                    orders_enabled=?,
                    reports_enabled=?,
                    discounts_enabled=?
                WHERE id=?
            ")->execute([
                $name,
                $folder_name,
                $active,
                $reservations_enabled,
                $orders_enabled,
                $reports_enabled,
                $discounts_enabled,
                $id
            ]);

            // languages: keep rows but toggle active
            db()->prepare("UPDATE restaurant_languages SET active=0 WHERE restaurant_id=?")->execute([$id]);

            $up = db()->prepare("
                UPDATE restaurant_languages
                SET active=1
                WHERE restaurant_id=? AND language_id=?
            ");
            $ins = db()->prepare("
                INSERT INTO restaurant_languages (restaurant_id, language_id, active)
                VALUES (?, ?, 1)
            ");

            foreach ($selected_lang_ids as $lang_id) {
                if ($lang_id <= 0) continue;

                $up->execute([$id, $lang_id]);
                if ($up->rowCount() === 0) {
                    $ins->execute([$id, $lang_id]);
                }
            }

            db()->commit();

            $success = "تم حفظ التعديلات بنجاح";
            $restaurant = fetch_one("SELECT * FROM restaurants WHERE id = ?", [$id]);

            $current_lang_ids = fetch_all("
                SELECT language_id
                FROM restaurant_languages
                WHERE restaurant_id = ? AND active = 1
            ", [$id]);
            $current_lang_ids = $current_lang_ids ? array_map('intval', array_column($current_lang_ids, 'language_id')) : [];

        } catch (Exception $e) {
            db()->rollBack();
            $error = "خطأ أثناء الحفظ: " . $e->getMessage();
        }
    }
}
?>
<!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{background:#0f0f11;color:#fff;font-family:Tajawal;padding:40px;}
.box{background:#1c1c22;padding:25px;border-radius:12px;width:650px;margin:auto;border:1px solid #2e2e38;}
.box h2{color:#9c6bff;margin:0 0 15px 0;}
input[type="text"]{
    width:100%;padding:10px;margin-top:10px;border-radius:6px;
    border:1px solid #333;background:#222;color:#fff;
}
label{margin-top:12px;display:block;}
.btn{background:#9c6bff;color:#000;padding:12px 20px;border:none;border-radius:8px;margin-top:20px;width:100%;font-weight:bold;cursor:pointer;}
.success{background:#2ecc71;color:#000;padding:10px;border-radius:8px;margin-bottom:12px;font-weight:bold;}
.error{background:#ff4d4d;color:#000;padding:10px;border-radius:8px;margin-bottom:12px;font-weight:bold;}
.checkbox-group{margin:10px 0;padding:12px;background:#222;border-radius:8px;border:1px solid #333;}
.checkbox-group .row{display:flex;flex-wrap:wrap;gap:10px;}
.checkbox-pill{
    display:flex;align-items:center;gap:8px;
    background:#111;border:1px solid #333;border-radius:8px;
    padding:8px 10px;
}
hr{border-color:#333;margin:18px 0;}
small{color:#bbb}
</style>
</head>
<body>

<div class="box">
    <h2>تعديل بيانات المطعم</h2>

    <?php if($success): ?><div class="success"><?= htmlspecialchars($success) ?></div><?php endif; ?>
    <?php if($error): ?><div class="error"><?= htmlspecialchars($error) ?></div><?php endif; ?>

    <form method="post">

        <label>اسم المطعم:</label>
        <input type="text" name="name" required value="<?= htmlspecialchars($restaurant['name'] ?? '') ?>">

        <label>رابط المطعم (Folder Name):</label>
        <input type="text" name="folder_name" required value="<?= htmlspecialchars($restaurant['folder_name'] ?? '') ?>">
        <small>مثال: kilochi-khan (أحرف إنجليزية/أرقام وشرطة فقط)</small>

        <hr>

        <label>الحالة:</label>
        <div class="checkbox-group">
            <label class="checkbox-pill">
                <input type="checkbox" name="active" <?= !empty($restaurant['active']) ? 'checked' : '' ?>>
                المطعم فعال
            </label>
        </div>

        <label>اللغات المفعلة (من جدول languages + restaurant_languages):</label>
        <div class="checkbox-group">
            <div class="row">
                <?php foreach($all_languages as $lng): ?>
                    <?php
                        $lid = (int)$lng['id'];
                        $checked = in_array($lid, $current_lang_ids, true) ? 'checked' : '';
                    ?>
                    <label class="checkbox-pill">
                        <input type="checkbox" name="languages[]" value="<?= $lid ?>" <?= $checked ?>>
                        <?= htmlspecialchars($lng['name']) ?> (<?= htmlspecialchars($lng['code']) ?>)
                    </label>
                <?php endforeach; ?>
            </div>
        </div>

        <label>تفعيل الميزات:</label>
        <div class="checkbox-group">
            <div class="row">
                <label class="checkbox-pill">
                    <input type="checkbox" name="reservations_enabled" <?= !empty($restaurant['reservations_enabled']) ? 'checked' : '' ?>>
                    الحجوزات
                </label>
                <label class="checkbox-pill">
                    <input type="checkbox" name="orders_enabled" <?= !empty($restaurant['orders_enabled']) ? 'checked' : '' ?>>
                    الطلبات
                </label>
                <label class="checkbox-pill">
                    <input type="checkbox" name="reports_enabled" <?= !empty($restaurant['reports_enabled']) ? 'checked' : '' ?>>
                    التقارير
                </label>
                <label class="checkbox-pill">
                    <input type="checkbox" name="discounts_enabled" <?= !empty($restaurant['discounts_enabled']) ? 'checked' : '' ?>>
                    الخصومات
                </label>
            </div>
        </div>

        <button class="btn">حفظ التعديلات</button>

    </form>
</div>

</body>
</html>
