<?php
require_once 'includes/auth_check.php';

// لغة صفحة الحجوزات تأتي من مبدّل اللغة المشترك في السايدبار.
$pms_reservation_language = strtolower((string)($_SESSION['pms_language'] ?? 'ar'));
if (!in_array($pms_reservation_language, ['ar', 'en', 'fr', 'es'], true)) {
    $pms_reservation_language = 'ar';
}
$pms_reservations_is_ltr = in_array($pms_reservation_language, ['en', 'fr', 'es'], true);
$pms_reservations_dir = $pms_reservations_is_ltr ? 'ltr' : 'rtl';

// هذه قائمة مفاتيح النصوص الأصلية فقط؛ الترجمات نفسها لا تُخزّن في ملفات PHP.
$pms_reservation_sources = [
    'إدارة الحجوزات والتقويم | PMS',
    'إدارة الحجوزات',
    '+ حجز جديد',
    'قائمة الحجوزات',
    'التقويم الذكي للطوابق',
    'تاريخ الدخول:',
    'الكل',
    'حجوزات اليوم',
    'حجوزات هذا الأسبوع',
    'حجوزات هذا الشهر',
    'حدد تاريخ (من - إلى)',
    'من:',
    'إلى:',
    'بحث بالاسم، الهوية، الجوال...',
    'بحث',
    'تحديد الكل',
    '-- اختر إجراء مجمع --',
    'تأكيد ودفع المحددة',
    'استرداد وإلغاء المحددة',
    'إخفاء الحجوزات الملغاة',
    'تنفيذ الإجراء',
    'جاري تحميل الحجوزات...',
    'الشهر الحالي',
    'الشهر القادم',
    'جاري التحميل...',
    'جاري البحث...',
    'يرجى تحديد تاريخ البداية والنهاية.',
    'لا توجد حجوزات مطابقة للبحث أو التاريخ المحدد.',
    'حجز مبدئي',
    'نزيل داخل الغرفة',
    'مبدئي + عربون',
    'حجز مؤكد',
    'حجز مكتمل',
    'حجز ملغي',
    'نقل لغرفة أخرى',
    'الحجز ملغي',
    'تحصيل',
    'تمديد',
    'مدفوع بالكامل ومؤكد',
    'يجب إتمام الدفع وتأكيد الحجز أولاً',
    'غير مدفوع (لا يمكن التسكين)',
    'تسكين مبكر',
    'تسكين',
    'استرداد وإلغاء',
    'مغادرة مبكرة',
    'مغادرة',
    'إخفاء',
    'كاش',
    'نقدي',
    'شبكة',
    'تحويل بنكي',
    'تحويل بنكي مسبق',
    'إلكتروني',
    'غير مسجل',
    'غير مسجلة',
    'بانتظار التخصيص',
    'بدون وجبات',
    'بانتظار',
    'مكتملة الإقامة',
    'تحتاج متابعة',
    'حجز جماعي',
    'عميل',
    'الغرف',
    'غرف',
    'حجوزات',
    'الإقامة',
    'بالغ',
    'طفل',
    'غرفة بإفطار',
    'إجمالي المجموعة:',
    'المدفوع:',
    'المتبقي:',
    'هذه بطاقة جماعية للعرض فقط؛ كل Reservation يبقى مستقلاً داخل المجموعة.',
    'حدث خطأ أثناء جلب البيانات من الخادم.',
    'الخادم لم يرجع JSON صحيحاً.',
    'تعذر قراءة حساب النزيل.',
    'جاري قراءة حساب النزيل...',
    'لا يوجد مبلغ مستحق',
    'حساب النزيل مسدد بالكامل حالياً.',
    'حسنًا',
    'خدمة',
    'رسم إضافي',
    'تحصيل المستحقات فقط',
    'تحصيل الآن بدون مغادرة',
    'تراجع',
    'اختر طريقة التحصيل أولاً.',
    'جاري تحصيل المستحقات...',
    'تعذر تحصيل المستحقات.',
    'تم التحصيل',
    'تعذر التحصيل',
    'حدث خطأ غير متوقع.',
    'تمديد الإقامة',
    'فحص التوفر والحساب',
    'إلغاء',
    'حدد تاريخ الخروج الجديد.',
    'جاري فحص توفر الغرفة وحساب التمديد...',
    'الخادم لم يرجع استجابة صحيحة.',
    'تعذر حساب التمديد.',
    'مراجعة التمديد',
    'سيعاد التحقق من التوفر قبل تنفيذ العملية.',
    'لا يمكن تنفيذ التمديد حاليًا لعدم وجود غرفة متاحة حتى نهاية فترة التمديد.',
    'متابعة التحصيل',
    'إغلاق',
    'اختر غرفة بديلة.',
    'تحصيل التمديد',
    'تأكيد التحصيل والتمديد',
    'رجوع',
    'جاري تنفيذ التمديد وإعادة فحص التوفر...',
    'تعذر تمديد الإقامة.',
    'تم تمديد الإقامة',
    'تم تنفيذ التمديد بنجاح.',
    'تعذر تمديد الإقامة',
    'جاري فحص موعد التسكين وتوفر الغرفة...',
    'تعذر حساب التسكين المبكر.',
    'أقل من دقيقة',
    'الغرفة البديلة المقترحة:',
    'نتيجة البحث:',
    'انتباه: تسكين مبكر',
    'تعذر التسكين المبكر',
    'اختيار الغرفة والمتابعة',
    'فتح شاشة التسكين',
    'يجب اختيار غرفة بديلة متاحة طوال فترة الإقامة.',
    'تحصيل التسكين المبكر',
    'تأكيد التحصيل',
    'اختر طريقة التحصيل.',
    'استرداد فرق الغرفة',
    'متابعة الاسترداد',
    'جاري إعادة التحقق وتثبيت الغرفة...',
    'الخادم لم يرجع استجابة صحيحة للتسكين المبكر.',
    'تعذر تنفيذ التسكين المبكر.',
    'تم تثبيت الغرفة والتحصيل بنجاح.',
    'متابعة التسكين',
    'رسوم إضافية',
    'المغادرة وتحصيل الحساب',
    'تحصيل وإتمام المغادرة',
    'إتمام المغادرة',
    'جاري تسوية حساب النزيل...',
    'تعذر إتمام المغادرة.',
    'تمت المغادرة بنجاح',
    'تعذر إتمام المغادرة',
    'جاري حساب تسوية الخروج المبكر...',
    'تعذر حساب الخروج المبكر.',
    'لا يوجد استرداد',
    'استرداد وإتمام المغادرة',
    'اختر طريقة الاسترداد.',
    'جاري تنفيذ المغادرة المبكرة...',
    'تعذر إتمام المغادرة المبكرة.',
    'تمت المغادرة المبكرة',
    'تمت التسوية بنجاح.',
    'تأكيد الحجز والدفع',
    'يرجى اختيار طريقة الدفع لإتمام العملية!',
    'جاري الحفظ...',
    'تم بنجاح!',
    'تم تأكيد الحجز وتسجيل الدفع بالطريقة المحددة.',
    'خطأ!',
    'حدث خطأ ما.',
    'خطأ في الاتصال بالخادم.',
    'استرداد الأموال وإلغاء الحجز؟',
    'تأكيد الاسترداد والإلغاء',
    'الرجاء كتابة سبب الإلغاء أولاً.',
    'الرجاء اختيار طريقة الاسترداد!',
    'جاري تنفيذ الاسترداد...',
    'تم الاسترداد والإلغاء!',
    'تمت العملية بنجاح وتسجيل الاسترداد في المالية.',
    'إخفاء الحجز الملغي؟',
    'نعم، إخفاء',
    'تم الإخفاء',
    'تم إخفاء الحجز الملغي من قائمة الحجوزات دون حذفه.',
    'تعذر الإخفاء',
    'خطأ',
    'تعذر الاتصال بالخادم.',
    'تنبيه',
    'يرجى تحديد حجز واحد على الأقل من القائمة.',
    'يرجى اختيار الإجراء من القائمة المنسدلة.',
    'الإخفاء متاح للحجوزات الملغاة فقط.',
    'تأكيد ودفع',
    'هل أنت متأكد؟',
    'نعم، نفذ الإجراء',
    'جاري التنفيذ...',
    'اكتملت العملية',
    'نجح:',
    'فشل:',
    'لا توجد غرف لعرضها في هذا الطابق.',
    'الغرفة / اليوم',
    'الطابق',
    'الغرفة',
    'العميل:',
    'الحالة:',
    'سبب التمديد (اختياري)',
    'تحصيلات إضافية غير محصلة:',
    'خدمات:',
    'POS:',
    'رسوم إضافية:',
    'إجمالي التحصيل المطلوب:',
    'فاتورة حجز',
    'الإجمالي:',
    'بيانات العميل',
    'الاسم:',
    'الهاتف:',
    'الهوية:',
    'تفاصيل الإقامة',
    'الغرفة:',
    'الدخول:',
    'الخروج:',
    'الخطة الغذائية:',
    'قيمة الوجبات:',
    'قيمة الحجز:',
    'المدفوع للحجز:',
    'المتبقي من الحجز:',
    'حالة الدفع:',
    'حالة دفع الحجز:',
    'ملغي / غير مدفوع',
    'عربون',
    'مدفوع بالكامل',
    'غير مدفوع',
    'المطلوب:',
    'متبقي من قيمة الحجز',
    'مشتريات POS على الحساب:',
    'إجمالي المستحق للتحصيل',
    'يوجد مبلغ مستحق على النزيل',
    'لا يوجد مبلغ مستحق على النزيل.',
    'لن يتم إنهاء المغادرة قبل تسوية المبلغ المستحق بالكامل.',
    'طريقة التحصيل:',
    'طريقة الاسترداد:',
    'طريقة التحصيل للمبلغ المستحق:',
    'المبلغ المطلوب الآن:',
    'استرداد للنزيل:',
    'مبلغ إضافي للحجز:',
    'مبيعات POS مستحقة:',
    'يجب تحصيلها قبل إتمام المغادرة.',
    'الخروج الأصلي:',
    'الخروج الفعلي:',
    'الليالي المستخدمة:',
    'الليالي غير المستخدمة:',
    'قيمة الليالي غير المستخدمة:',
    'غرامة الخروج المبكر:',
    'الاسترداد يسجل كعملية مستقلة. ومبيعات POS تبقى مرتبطة بالنزيل وتُحصّل بشكل مستقل.',
    'الدفع عند الوصول:',
    'سبب الإلغاء',
    'اكتب سبب الإلغاء بالتفصيل...',
    'سيتم حفظ السبب مع عملية الإلغاء للمراجعة والتحليل لاحقًا.',
    'كيف تم استرداد المبلغ للعميل؟',
    'سيتم إلغاء الحجز رقم',
    'وتحرير الغرفة نهائياً.',
    'وقت الدخول الرسمي:',
    'لا توجد رسوم دخول مبكر ضمن الإعداد الحالي.',
    'رسوم الدخول المبكر الأساسية:',
    'لا يتم تغيير الغرفة ولا حالة الحجز من هذه النافذة إلا بعد التأكيد والتحقق النهائي من التوفر.',
    'سيُحصّل الآن:',
    'سيُحصّل رسم الدخول المبكر:',
    'وسيُسترد فرق الغرفة:',
    'المبلغ المطلوب تحصيله:',
    'سيُسترد للنزيل',
    'لأن الغرفة البديلة أرخص.',
    'لا توجد غرفة بديلة جاهزة ومتاحة طوال فترة إقامة النزيل.',
    'الغرفة الحالية متاحة الآن وجاهزة للتسكين',
    'الغرفة الحالية غير متاحة الآن',
    'بحث النظام عن غرف',
    'النزيل يريد التسكين قبل موعد الدخول الرسمي.',
    'سيتم تنفيذ إجراء',
    'على عدد',
    'حجوزات دفعة واحدة.',
    'الطابق ',
    'غرفة ',
    'ريال',
];
$pms_reservation_translation_map = [];

if ($pms_reservation_language !== 'ar' && isset($pdo) && $pdo instanceof PDO) {
    try {
        $pms_reservation_keys = array_values(array_unique(array_map(
            static fn(string $source): string => hash('sha256', $source),
            $pms_reservation_sources
        )));
        if ($pms_reservation_keys) {
            $placeholders = implode(',', array_fill(0, count($pms_reservation_keys), '?'));
            $translationQuery = $pdo->prepare(
                "SELECT source_text, translation_value
                 FROM Translation
                 WHERE language_code = ?
                   AND translation_key IN ($placeholders)"
            );
            $translationQuery->execute(array_merge([$pms_reservation_language], $pms_reservation_keys));
            foreach ($translationQuery->fetchAll(PDO::FETCH_ASSOC) as $translationRow) {
                $sourceText = (string)($translationRow['source_text'] ?? '');
                $translatedText = (string)($translationRow['translation_value'] ?? '');
                if ($sourceText !== '' && $translatedText !== '') {
                    $pms_reservation_translation_map[$sourceText] = $translatedText;
                }
            }
        }
    } catch (Throwable $translationError) {
        // في حال تعذر تحميل الترجمات، تبقى الصفحة قابلة للعمل بالنص الأصلي.
        error_log('Reservations translation load failed: ' . $translationError->getMessage());
    }
}

// تمرير خريطة الترجمات إلى JavaScript حتى تُترجم القيم القادمة ديناميكيًا من API.
// تُشفّر الخريطة Base64 في الصفحة؛ قيم الترجمات نفسها تبقى محفوظة في جدول Translation.
$pms_reservation_translation_json = json_encode(
    $pms_reservation_translation_map,
    JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE
);
$pms_reservation_translation_b64 = base64_encode($pms_reservation_translation_json !== false ? $pms_reservation_translation_json : '{}');

// تطبيق ترجمات قاعدة البيانات على نصوص HTML وعلى النصوص الثابتة داخل JavaScript.
// هذا يعالج رسائل وقوالب الحجوزات التي تُنشأ بعد تحميل الصفحة، دون ترجمة أسماء النزلاء أو بياناتهم.
if ($pms_reservation_translation_map) {
    uksort($pms_reservation_translation_map, static fn($a, $b): int => strlen($b) <=> strlen($a));
    ob_start(static function (string $output) use ($pms_reservation_translation_map): string {
        $output = preg_replace_callback(
            '~(<title\b[^>]*>)(.*?)(</title>)~is',
            static fn(array $match): string => $match[1] . strtr($match[2], $pms_reservation_translation_map) . $match[3],
            $output,
            1
        ) ?? $output;
        $output = preg_replace_callback(
            '~(<main\b[^>]*>)(.*?)(</main>)~is',
            static fn(array $match): string => $match[1] . strtr($match[2], $pms_reservation_translation_map) . $match[3],
            $output,
            1
        ) ?? $output;
        // السكربتات الخارجية لا تُمس. نعالج السكربتات المضمنة فقط لترجمة نصوص واجهة JavaScript.
        $output = preg_replace_callback(
            '~(<script\b(?![^>]*\bsrc\s*=)[^>]*>)(.*?)(</script>)~is',
            static fn(array $match): string => $match[1] . strtr($match[2], $pms_reservation_translation_map) . $match[3],
            $output
        ) ?? $output;
        return $output;
    });
}
?>
<!DOCTYPE html>
<html lang="<?= htmlspecialchars($pms_reservation_language, ENT_QUOTES, 'UTF-8') ?>" dir="<?= $pms_reservations_dir ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
    <title>إدارة الحجوزات والتقويم | PMS</title>
    <link rel="stylesheet" href="admin_style.css">
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <style>
        .tabs { display: flex; gap: 10px; margin-bottom: 20px; border-bottom: 2px solid #ddd; padding-bottom: 10px; flex-wrap: wrap; }
        .tab-btn { padding: 10px 20px; border: none; background: #f1f5f9; cursor: pointer; font-weight: bold; border-radius: 4px; color: #475569; transition: 0.2s; flex: 1; text-align: center; min-width: 140px;}
        .tab-btn.active { background: #1a73e8; color: white; }
        .tab-content { display: none; }
        .tab-content.active { display: block; }
        .bulk-actions-bar { background: #e0e7ff; padding: 10px 15px; border-radius: 4px; margin-bottom: 15px; display: flex; align-items: center; gap: 15px; border: 1px solid #c7d2fe; flex-wrap: wrap; }
        .res-cb { width: 18px; height: 18px; cursor: pointer; accent-color: #1a73e8; }
        .compact-row { background: white; border: 1px solid #e2e8f0; border-right: 4px solid #ccc; padding: 12px 15px; margin-bottom: 5px; border-radius: 4px; display: flex; justify-content: space-between; align-items: center; cursor: pointer; transition: 0.2s; min-height: 50px; box-sizing: border-box; }
        .compact-row:hover { background: #f8fafc; }
        .res-status-checkedin { border-right-color: #8bc34a; }
        .res-status-definite { border-right-color: #f44336; }
        .res-status-pending { border-right-color: #ff9800; }
        .res-status-completed { border-right-color: #3b82f6; opacity: 0.8; }
        .res-status-cancelled { border-right-color: #94a3b8; opacity: 0.6; background: #f1f5f9; }
        .row-basic-info { display: flex; gap: 15px; align-items: center; font-size: 14px; width: 100%; flex-wrap: wrap; }
        .col-id { width: 80px; font-weight: bold; color: #1a73e8; }
        .col-name { flex: 1.5; font-weight: bold; min-width: 120px; }
        .col-dates { flex: 2; color: #64748b; font-size: 13px; min-width: 150px; }
        .col-room { width: 100px; font-weight: bold; text-align: center; }
        .col-status { width: 120px; text-align: left; }
        .badge { padding: 4px 8px; font-size: 11px; font-weight: bold; border-radius: 3px; color: white; white-space: nowrap; }
        .badge-green { background: #8bc34a; }
        .badge-red { background: #f44336; }
        .badge-orange { background: #ff9800; }
        .badge-blue { background: #3b82f6; }
        .badge-gray { background: #64748b; }
        .btn { padding: 6px 12px; border: none; border-radius: 3px; cursor: pointer; font-size: 12px; font-weight: bold; color: white; transition: 0.2s; text-align: center; }
        .btn:hover { filter: brightness(0.9); }
        .btn-pdf { background: #475569; }
        .btn-transfer { background: #7c3aed; }
        .btn-confirm-pay { background: #059669; }
        .btn-disabled-paid { background: #e2e8f0; color: #64748b; cursor: not-allowed; border: 1px solid #cbd5e1; }
        .btn-checkin { background: #1a73e8 !important; color: white !important; font-weight: bold; box-shadow: 0 2px 4px rgba(26,115,232,0.3); }
        .btn-refund { background: #d97706; }
        .btn-delete { background: #64748b; }
        .btn-hide { background: #64748b; }
        .btn-edit { background: #3b82f6; }
.checkout-due-box{background:#fff7ed;border:1px solid #fdba74;border-radius:10px;padding:14px;text-align:right}.checkout-total-due{font-size:27px;font-weight:900;color:#b91c1c;margin:7px 0}.btn-checkout-account{background:#0f766e !important}

        /* حجز جماعي: عرض موحد وأنيق مع الاحتفاظ بكل الحجوزات الفردية داخله */
        .booking-group-card {
            background: #fff;
            border: 1px solid #e2e8f0;
            border-right: 5px solid #6b4093;
            border-radius: 10px;
            margin-bottom: 12px;
            box-shadow: 0 3px 12px rgba(40,24,55,.06);
            overflow: hidden;
        }
        .booking-group-card:hover { box-shadow: 0 7px 20px rgba(40,24,55,.10); }
        .booking-group-head {
            display: grid;
            grid-template-columns: minmax(220px,1.5fr) minmax(170px,1fr) minmax(150px,1fr) auto;
            gap: 14px;
            align-items: center;
            padding: 15px 16px;
            cursor: pointer;
            background: linear-gradient(180deg,#fff,#faf7fc);
        }
        .booking-group-title { font-weight: 900; color:#2f1d3e; font-size:15px; }
        .booking-group-sub { color:#64748b; font-size:12px; margin-top:4px; }
        .booking-group-stat {
            display:flex; flex-direction:column; gap:4px;
            color:#475569; font-size:12px;
        }
        .booking-group-stat strong { color:#3f2a51; font-size:13px; }
        .booking-group-rooms { display:flex; flex-wrap:wrap; gap:6px; }
        .booking-room-chip {
            display:inline-flex; align-items:center; gap:4px;
            padding:5px 8px; border-radius:999px;
            background:#f1eaf6; color:#5d347d; font-weight:800; font-size:11px;
            border:1px solid #d9c6e5;
        }
        .booking-group-actions { display:flex; align-items:center; gap:8px; }
        .booking-group-toggle {
            width:34px; height:34px; border-radius:50%; border:1px solid #d9c6e5;
            background:#fff; color:#6b4093; cursor:pointer;
            display:flex; align-items:center; justify-content:center;
        }
        .booking-group-body { display:none; border-top:1px solid #ece7f1; padding:10px 12px 14px; }
        .booking-group-body.open { display:block; }
        .booking-child-row {
            background:#fff; border:1px solid #edf0f3; border-radius:8px;
            margin:7px 0; overflow:hidden;
        }
        .booking-child-summary {
            display:flex; align-items:center; gap:12px; justify-content:space-between;
            padding:11px 12px; cursor:pointer;
        }
        .booking-child-left { display:flex; align-items:center; gap:10px; min-width:0; flex-wrap:wrap; }
        .booking-child-id { color:#6b4093; font-weight:900; font-size:12px; }
        .booking-child-room { font-weight:900; color:#334155; }
        .booking-child-meta { color:#64748b; font-size:11px; }
        .booking-group-footer {
            display:flex; justify-content:space-between; align-items:center; gap:10px;
            padding:10px 12px 2px; color:#64748b; font-size:12px; flex-wrap:wrap;
        }
        .booking-group-label {
            display:inline-flex; align-items:center; gap:6px;
            padding:5px 9px; border-radius:999px; background:#f4eef8; color:#6b4093;
            font-weight:900; border:1px solid #d9c6e5;
        }
        @media (max-width: 900px) {
            .booking-group-head { grid-template-columns:1fr; }
            .booking-group-actions { justify-content:space-between; }
        }
        .invoice-details { display: none; background: #fff; border: 1px solid #e2e8f0; border-top: none; padding: 20px; margin-top: -5px; margin-bottom: 15px; border-radius: 0 0 4px 4px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1); }
        .invoice-header { display: flex; justify-content: space-between; border-bottom: 2px dashed #cbd5e1; padding-bottom: 10px; margin-bottom: 15px; flex-wrap: wrap; gap: 10px; }
        .invoice-body { display: flex; gap: 20px; flex-wrap: wrap; }
        .invoice-section { flex: 1; min-width: 200px; background: #f8fafc; padding: 15px; border-radius: 4px; border: 1px solid #e2e8f0; }
        .invoice-actions { margin-top: 15px; padding-top: 15px; border-top: 1px solid #e2e8f0; display: flex; gap: 10px; justify-content: flex-end; flex-wrap: wrap; }
        .calendar-layout { display: flex; gap: 20px; align-items: flex-start; }
        .floor-sidebar { width: 150px; background: white; border: 1px solid #e2e8f0; border-radius: 6px; overflow: hidden; box-shadow: 0 1px 3px rgba(0,0,0,0.05); flex-shrink: 0; }
        .floor-btn { display: block; width: 100%; padding: 15px; border: none; background: transparent; border-bottom: 1px solid #e2e8f0; cursor: pointer; font-weight: bold; font-size: 14px; text-align: center; color: #334155; transition: 0.2s; }
        .floor-btn:hover { background: #f8fafc; }
        .floor-btn.active { background: #1a73e8; color: white; }
        .calendar-container { flex: 1; overflow-x: auto; background: white; padding: 15px; border-radius: 4px; border: 1px solid #e2e8f0; box-shadow: 0 1px 3px rgba(0,0,0,0.05); -webkit-overflow-scrolling: touch; }
        .cal-grid { display: grid; border-collapse: collapse; min-width: 1000px; }
        .cal-header-row { display: grid; grid-template-columns: 100px repeat(30, 1fr); background: #f1f5f9; border-bottom: 2px solid #cbd5e1; font-weight: bold; text-align: center; font-size: 12px; }
        .cal-room-row { display: grid; grid-template-columns: 100px repeat(30, 1fr); border-bottom: 1px solid #e2e8f0; }
        .cal-cell { padding: 8px 2px; text-align: center; border-right: 1px solid #e2e8f0; font-size: 11px; }
        .cal-room-name { font-weight: bold; background: #f8fafc; display: flex; align-items: center; justify-content: center; }
        .day-free { background: #dcfce7; color: #166534; }
        .day-booked { background: #fee2e2; color: #991b1b; font-weight: bold; cursor: pointer; }

        @media (max-width: 768px) {
            .topbar { flex-direction: column; align-items: flex-start; gap: 15px; }
            .topbar div:last-child { width: 100%; }
            .topbar div:last-child a { display: block; text-align: center; }
            .filter-container { flex-direction: column; align-items: stretch !important; }
            .filter-container > div { width: 100%; flex-direction: column; align-items: stretch !important; }
            #date-filter, #search-input, .filter-container button { width: 100% !important; margin-top: 5px; }
            .bulk-actions-bar { flex-direction: column; align-items: stretch; gap: 10px; }
            .bulk-actions-bar select, .bulk-actions-bar button { width: 100%; }
            .bulk-actions-bar span { display: none; } 
            .compact-row { flex-direction: column; align-items: flex-start; gap: 10px; padding: 15px; }
            .row-basic-info { flex-direction: column; align-items: flex-start; gap: 8px; }
            .col-id, .col-name, .col-dates, .col-room, .col-status { width: 100%; text-align: right; }
            .col-room { text-align: right; }
            .invoice-actions { flex-direction: column; }
            .invoice-actions button { width: 100%; }
            .calendar-layout { flex-direction: column; }
            .floor-sidebar { width: 100%; overflow-x: auto; white-space: nowrap; border-radius: 4px; }
            #cal-floor-menu { display: flex; flex-direction: row; }
            .floor-btn { width: auto; flex: 1; padding: 10px 15px; border-bottom: none; border-left: 1px solid #e2e8f0; }
        }


        /* اتجاه محتوى صفحة الحجوزات يتبع اللغة المختارة */
        .pms-reservations-ltr .main-content,
        .pms-reservations-ltr .page-content,
        .pms-reservations-ltr .topbar,
        .pms-reservations-ltr .filter-container,
        .pms-reservations-ltr .bulk-actions-bar,
        .pms-reservations-ltr .calendar-layout {
            direction: ltr;
            text-align: left;
        }
        .pms-reservations-ltr [style*="text-align:right"] {
            text-align: left !important;
        }
        .pms-reservations-ltr .compact-row {
            border-right-width: 1px;
            border-left: 4px solid #ccc;
        }
        .pms-reservations-ltr .res-status-checkedin { border-left-color: #8bc34a; }
        .pms-reservations-ltr .res-status-definite { border-left-color: #f44336; }
        .pms-reservations-ltr .res-status-pending { border-left-color: #ff9800; }
        .pms-reservations-ltr .res-status-completed { border-left-color: #3b82f6; }
        .pms-reservations-ltr .res-status-cancelled { border-left-color: #94a3b8; }
        .pms-reservations-ltr .booking-group-card {
            border-right-width: 1px;
            border-left: 5px solid #6b4093;
        }
        .pms-reservations-ltr .row-basic-info,
        .pms-reservations-ltr .booking-group-head,
        .pms-reservations-ltr .booking-child-left,
        .pms-reservations-ltr .invoice-header,
        .pms-reservations-ltr .invoice-body,
        .pms-reservations-ltr .invoice-actions {
            direction: ltr;
        }
        .pms-reservations-ltr .col-status { text-align: left; }
        .pms-reservations-ltr .cal-cell { border-right: 0; border-left: 1px solid #e2e8f0; }

    </style>
</head>
<body class="<?= $pms_reservations_is_ltr ? 'pms-reservations-ltr' : 'pms-reservations-rtl' ?>" dir="<?= $pms_reservations_dir ?>">

<div class="admin-layout">
    <?php include 'includes/sidebar.php'; ?>

    <div class="sidebar-overlay" id="sidebarOverlay" onclick="toggleSidebar()"></div>

    <main class="main-content" dir="<?= $pms_reservations_dir ?>">
        <header class="topbar">
            <div style="display: flex; align-items: center; gap: 15px;">
                <button class="menu-toggle" onclick="toggleSidebar()">
                    <i class="fa-solid fa-bars"></i>
                </button>
                <strong>إدارة الحجوزات</strong>
            </div>
            <div>
                <a href="create_reservation.php" style="background:#1a73e8; color:white; padding:8px 15px; border-radius:4px; text-decoration:none; font-weight:bold;">+ حجز جديد</a>
            </div>
        </header>

        <div class="page-content">
            <div class="tabs">
                <button class="tab-btn active" onclick="switchTab('list')">📋 قائمة الحجوزات</button>
                <button class="tab-btn" onclick="switchTab('calendar')">📅 التقويم الذكي للطوابق</button>
            </div>

            <div id="tab-list" class="tab-content active">
                <div class="filter-container" style="display: flex; gap: 15px; margin-bottom: 15px; background: #fff; padding: 15px; border-radius: 6px; border: 1px solid #e2e8f0; align-items: center; flex-wrap: wrap; box-shadow: 0 1px 3px rgba(0,0,0,0.05);">
                    <div style="display: flex; gap: 10px; align-items: center;">
                        <label style="font-weight: bold; color: #475569;">تاريخ الدخول:</label>
                        <select id="date-filter" onchange="toggleCustomDates(); fetchReservations();" style="padding: 8px; border: 1px solid #ccc; border-radius: 4px; outline: none; font-weight:bold;">
                            <option value="all">الكل</option>
                            <option value="today">حجوزات اليوم</option>
                            <option value="this_week">حجوزات هذا الأسبوع</option>
                            <option value="this_month">حجوزات هذا الشهر</option>
                            <option value="custom">📅 حدد تاريخ (من - إلى)</option>
                        </select>
                    </div>

                    <div id="custom-date-wrapper" style="display: none; gap: 10px; align-items: center; background: #f8fafc; padding: 10px; border-radius: 4px; border: 1px dashed #cbd5e1; width: 100%;">
                        من: <input type="date" id="date-from" onchange="fetchReservations()" style="padding: 6px; border: 1px solid #ccc; border-radius: 4px; flex: 1;">
                        إلى: <input type="date" id="date-to" onchange="fetchReservations()" style="padding: 6px; border: 1px solid #ccc; border-radius: 4px; flex: 1;">
                    </div>
                    <div style="flex-grow: 1;"></div>
                    <div style="display: flex; gap: 5px; align-items: center;">
                        <input type="text" id="search-input" placeholder="بحث بالاسم، الهوية، الجوال..." onkeyup="if(event.key === 'Enter') fetchReservations()" style="padding: 8px 12px; border: 1px solid #ccc; border-radius: 4px; width: 250px; outline: none; font-family: inherit;">
                        <button onclick="fetchReservations()" style="background: #1a73e8; color: white; border: none; padding: 9px 15px; border-radius: 4px; cursor: pointer; font-weight: bold;">🔍 بحث</button>
                    </div>
                </div>

                <div class="bulk-actions-bar">
                    <label style="display:flex; align-items:center; gap:8px; font-weight:bold; color:#3730a3; cursor:pointer;">
                        <input type="checkbox" id="select-all-cb" class="res-cb" onclick="toggleAllCheckboxes(this)"> تحديد الكل
                    </label>
                    <span style="color:#a5b4fc;">|</span>
                    <select id="bulk-action-select" style="padding:8px; border-radius:4px; border:1px solid #a5b4fc; outline:none; font-weight:bold; font-family: inherit;">
                        <option value="">-- اختر إجراء مجمع --</option>
                        <option value="confirm_and_pay">✅✔️ تأكيد ودفع المحددة</option>
                        <option value="refund_and_cancel">↩️❌ استرداد وإلغاء المحددة</option>
                        <option value="hide_reservation">🙈 إخفاء الحجوزات الملغاة</option>
                    </select>
                    <button onclick="executeBulkAction()" style="background:#4f46e5; color:white; border:none; padding:9px 15px; border-radius:4px; font-weight:bold; cursor:pointer;">تنفيذ الإجراء</button>
                </div>

                <div id="reservations-list">
                    <p style="text-align:center;">جاري تحميل الحجوزات...</p>
                </div>
            </div>

            <div id="tab-calendar" class="tab-content">
                <div style="margin-bottom: 15px;">
                    <select id="cal-month" onchange="generateCalendar()" style="padding:8px; border:1px solid #ccc; border-radius:4px; font-weight:bold; font-family: inherit;">
                        <option value="0">الشهر الحالي</option>
                        <option value="1">الشهر القادم</option>
                    </select>
                </div>
                
                <div class="calendar-layout">
                    <div class="floor-sidebar">
                        <div id="cal-floor-menu">
                            <p style="text-align:center; padding:10px;">جاري التحميل...</p>
                        </div>
                    </div>
                    <div class="calendar-container" id="calendar-wrapper"></div>
                </div>
            </div>
        </div>
    </main>
</div>

<script>
    // تُحمّل الترجمات من جدول Translation عبر PHP؛ لا توجد قيم ترجمة ثابتة هنا.
    const PMS_RESERVATION_TRANSLATIONS = (() => {
        try {
            const encoded = '<?= htmlspecialchars($pms_reservation_translation_b64, ENT_QUOTES, 'UTF-8') ?>';
            const binary = atob(encoded);
            const bytes = Uint8Array.from(binary, character => character.charCodeAt(0));
            return JSON.parse(new TextDecoder('utf-8').decode(bytes));
        } catch (error) {
            console.warn('Could not load reservation translations.', error);
            return {};
        }
    })();

    function pmsReservationTranslate(value) {
        const sourceText = String(value == null ? '' : value);
        return Object.prototype.hasOwnProperty.call(PMS_RESERVATION_TRANSLATIONS, sourceText)
            ? PMS_RESERVATION_TRANSLATIONS[sourceText]
            : sourceText;
    }

    window.escapeHtml = function escapeHtml(value) {
        return String(value == null ? '' : value)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    };

    function toggleSidebar() {
        const sidebar = document.querySelector('.sidebar');
        const overlay = document.getElementById('sidebarOverlay');
        if(sidebar) sidebar.classList.toggle('show-sidebar');
        if(overlay) overlay.classList.toggle('active');
    }

    window.addEventListener('resize', () => {
        if (window.innerWidth > 768) {
            const sidebar = document.querySelector('.sidebar');
            if(sidebar) sidebar.classList.remove('show-sidebar');
            document.getElementById('sidebarOverlay').classList.remove('active');
        }
    });

    let allReservations = [];
    let allRooms = [];
    let currentCalFloor = 'all';

    let autoCollectId = Number(new URLSearchParams(window.location.search).get('collect') || 0);
    let autoCollectStarted = false;

    window.onload = async () => {
        await fetchRooms();
        await fetchReservations();
        buildCalendarFloorMenu();
        if (autoCollectId > 0 && !autoCollectStarted) {
            autoCollectStarted = true;
            setTimeout(() => collectReservationAccount(autoCollectId), 300);
        }
    };

    function switchTab(tabId) {
        document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
        document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
        event.target.classList.add('active');
        document.getElementById('tab-' + tabId).classList.add('active');
        if(tabId === 'calendar') generateCalendar();
    }

    function toggleCustomDates() {
        const filter = document.getElementById('date-filter').value;
        const wrapper = document.getElementById('custom-date-wrapper');
        wrapper.style.display = (filter === 'custom') ? 'flex' : 'none'; 
    }

    async function fetchRooms() {
        try {
            const response = await fetch('../api/admin/get_rooms_grid.php');
            const data = await response.json();
            if(data.status === 'success') allRooms = data.rooms;
        } catch(e) { console.error("Error rooms:", e); }
    }

    async function fetchReservations() {
        const dateFilter = document.getElementById('date-filter').value;
        const dateFrom = document.getElementById('date-from').value;
        const dateTo = document.getElementById('date-to').value;
        const searchVal = document.getElementById('search-input').value;
        const container = document.getElementById('reservations-list');

        container.innerHTML = '<p style="text-align:center;"><i class="fa-solid fa-spinner fa-spin"></i> جاري البحث...</p>';
        document.getElementById('select-all-cb').checked = false;

        const todayObj = new Date();
        const year = todayObj.getFullYear();
        const month = String(todayObj.getMonth() + 1).padStart(2, '0');
        const day = String(todayObj.getDate()).padStart(2, '0');
        const todayStr = `${year}-${month}-${day}`;

        try {
            let url = `../api/admin/get_reservations.php?date_filter=${dateFilter}&search=${encodeURIComponent(searchVal)}`;
            if (dateFilter === 'custom') {
                if(!dateFrom || !dateTo) {
                    container.innerHTML = '<p style="text-align:center; color: #f59e0b;">يرجى تحديد تاريخ البداية والنهاية.</p>';
                    return; 
                }
                url += `&start_date=${dateFrom}&end_date=${dateTo}`;
            }

            const response = await fetch(url);
            const data = await response.json();
            container.innerHTML = '';

            if(data.status === 'success') {
                allReservations = data.reservations;
                
                if(allReservations.length === 0) {
                    container.innerHTML = '<p style="text-align:center; margin-top:20px; font-weight:bold; color: #64748b;">لا توجد حجوزات مطابقة للبحث أو التاريخ المحدد.</p>';
                    return;
                }


                // ============================================================
                // عرض الحجوزات: إذا كان نفس العميل حجز عدة غرف لنفس التواريخ
                // نعرضها كـ "حجز جماعي" واحد، مع إبقاء كل Reservation مستقلة
                // داخل المجموعة حتى تبقى إجراءات الدفع/التسكين/الإلغاء دقيقة.
                // ============================================================

                function normalizeBookingIdentity(res) {
                    const guestId = Number(res.guest_id || 0);
                    if (guestId > 0) return 'guest:' + guestId;

                    const phone = String(res.phone || '').replace(/\s+/g, '').trim();
                    if (phone) return 'phone:' + phone;

                    return 'name:' + String(res.guest_name || '').trim().toLowerCase();
                }

                function sameStay(a, b) {
                    return String(a.check_in || '') === String(b.check_in || '')
                        && String(a.check_out || '') === String(b.check_out || '');
                }

                function canGroupReservations(a, b) {
                    // مجموعة صريحة من الحجز: هذه هي الأولوية القصوى.
                    const explicitA = Number(a.booking_group_id || 0);
                    const explicitB = Number(b.booking_group_id || 0);

                    if (explicitA > 0 || explicitB > 0) {
                        return explicitA > 0 && explicitA === explicitB;
                    }

                    // عند عدم وجود booking_group_id:
                    // نفس الشخص + نفس فترة الإقامة = حجز جماعي واحد في واجهة الإدارة.
                    return sameStay(a, b)
                        && normalizeBookingIdentity(a) === normalizeBookingIdentity(b);
                }

                function getGroupedReservations(items) {
                    const groups = [];
                    const used = new Set();

                    items.forEach((seed, seedIndex) => {
                        if (used.has(seedIndex)) return;

                        const group = [seed];
                        used.add(seedIndex);

                        for (let i = seedIndex + 1; i < items.length; i++) {
                            if (used.has(i)) continue;
                            if (canGroupReservations(seed, items[i])) {
                                group.push(items[i]);
                                used.add(i);
                            }
                        }

                        groups.push(group);
                    });

                    return groups;
                }

                function statusMetaForReservation(res) {
                    let statusClass = 'res-status-pending';
                    let badgeClass = 'badge-orange';
                    let statusText = 'حجز مبدئي';

                    if(res.status === 'checked_in') {
                        statusClass = 'res-status-checkedin';
                        badgeClass = 'badge-green';
                        statusText = 'نزيل داخل الغرفة';
                    } else if(res.status === 'confirmed') {
                        if (res.payment_status === 'deposit') {
                            statusClass = 'res-status-definite';
                            badgeClass = 'badge-orange';
                            statusText = 'مبدئي + عربون';
                        } else {
                            statusClass = 'res-status-definite';
                            badgeClass = 'badge-green';
                            statusText = 'حجز مؤكد';
                        }
                    } else if(res.status === 'pending') {
                        statusClass = 'res-status-pending';
                        badgeClass = 'badge-orange';
                        statusText = 'حجز مبدئي';
                    } else if(res.status === 'completed') {
                        statusClass = 'res-status-completed';
                        badgeClass = 'badge-blue';
                        statusText = 'حجز مكتمل';
                    } else if(res.status === 'cancelled') {
                        statusClass = 'res-status-cancelled';
                        badgeClass = 'badge-gray';
                        statusText = 'حجز ملغي';
                    }

                    return { statusClass, badgeClass, statusText: pmsReservationTranslate(statusText) };
                }

                function buildActionButtons(res) {
                    const meta = statusMetaForReservation(res);
                    let actionBtns = `<button onclick="event.stopPropagation(); downloadPDF(${res.id})" class="btn btn-pdf"><i class="fa-solid fa-file-pdf"></i> PDF</button>`;
                    actionBtns += `<button onclick="event.stopPropagation(); window.location.href='transfer_room.php?reservation_id=${res.id}'" class="btn btn-transfer"><i class="fa-solid fa-exchange-alt"></i> نقل لغرفة أخرى</button>`;

                    const totalPayment = Number(res.booking_total_amount ?? res.total_amount ?? 0);
                    const paidPayment = Number(res.paid_amount || 0);
                    const remainingPayment = Math.max(0, Number(res.remaining_amount ?? (totalPayment - paidPayment)));
                    const accountDue = Math.max(0, Number(res.account_due || remainingPayment));

                    const todayStrLocal = (() => {
                        const d = new Date();
                        return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
                    })();

                    const serviceDueForAction = Number(res.service_due || 0);
                    const extraFeeDueForAction = Number(res.extra_fee_due || 0);
                    const posDueForAction = Number(res.pos_due || 0);
                    const hasAdditionalDue = serviceDueForAction > 0.01 || extraFeeDueForAction > 0.01 || posDueForAction > 0.01;

                    if (res.status === 'cancelled') {
                        actionBtns += `<button class="btn btn-disabled-paid" disabled>🚫 الحجز ملغي</button>`;
                    } else if (accountDue > 0.01) {
                        // التحصيلات الإضافية يجب أن تكون قابلة للتحصيل بشكل مستقل عن قيمة الحجز الأصلي.
                        // يظهر الزر أيضًا للحجز المؤكد عندما تكون الخدمة مضافة وغير محصلة.
                        const collectLabel = hasAdditionalDue && remainingPayment <= 0.01
                            ? `💳 تحصيل ${accountDue.toFixed(2)}`
                            : `💳 تحصيل ${accountDue.toFixed(2)}`;
                        actionBtns += `<button onclick="event.stopPropagation(); collectReservationAccount(${res.id})" class="btn btn-checkout-account">${collectLabel}</button>`;

                        if (res.status === 'checked_in') {
                            actionBtns += `<button onclick="event.stopPropagation(); openStayExtension(${res.id})" class="btn btn-edit">➕ تمديد</button>`;
                        }
                    } else if (res.status === 'checked_in') {
                        actionBtns += `<button onclick="event.stopPropagation(); openStayExtension(${res.id})" class="btn btn-edit">➕ تمديد</button>`;
                    } else if (remainingPayment <= 0.01 && paidPayment > 0) {
                        actionBtns += `<button class="btn btn-disabled-paid" disabled>✅ مدفوع بالكامل ومؤكد</button>`;
                    } else {
                        actionBtns += `<button onclick="event.stopPropagation(); confirmAndPay(${res.id})" class="btn btn-confirm-pay">💳 تحصيل ${remainingPayment.toFixed(2)}</button>`;
                    }

                    if(res.status === 'confirmed') {
                        if (res.payment_status !== 'paid') {
                            actionBtns += `<button class="btn btn-disabled-paid" disabled title="يجب إتمام الدفع وتأكيد الحجز أولاً">⚠️ غير مدفوع (لا يمكن التسكين)</button>`;
                        } else {
                            if (res.check_in > todayStrLocal) {
                                actionBtns += `<button onclick="event.stopPropagation(); openEarlyCheckin(${res.id})" class="btn btn-checkin" style="background:#8b5cf6 !important;">⏳ تسكين مبكر</button>`;
                            } else {
                                actionBtns += `<button onclick="event.stopPropagation(); window.location.href='checkin.php?id=${res.id}'" class="btn btn-checkin">✅ تسكين</button>`;
                            }
                        }
                        actionBtns += `<button onclick="event.stopPropagation(); refundAndCancel(${res.id})" class="btn btn-refund">↩️ استرداد وإلغاء</button>`;
                    } else if(res.status === 'pending') {
                        actionBtns += `<button onclick="event.stopPropagation(); refundAndCancel(${res.id})" class="btn btn-refund">↩️ استرداد وإلغاء</button>`;
                    } else if(res.status === 'checked_in') {
                        if (res.check_out > todayStrLocal) {
                            actionBtns += `<button onclick="event.stopPropagation(); openEarlyDeparture(${res.id})" class="btn btn-blue">🏃 مغادرة مبكرة</button>`;
                        } else {
                            actionBtns += `<button onclick="event.stopPropagation(); openCheckoutAccount(${res.id}, false)" class="btn btn-blue">🛫 مغادرة</button>`;
                        }
                    }

                    if (res.status === 'cancelled') {
                        actionBtns += `<button onclick="event.stopPropagation(); hideReservation(${res.id})" class="btn btn-hide">🙈 إخفاء</button>`;
                    }
                    return { ...meta, actionBtns };
                }

                function buildReservationDetails(res, actionBtns, statusMeta) {
                    const total = Number(res.booking_total_amount ?? res.total_amount ?? 0);
                    const paid = Number(res.paid_amount || 0);
                    const remaining = Math.max(0, Number(res.remaining_amount ?? (total - paid)));
                    const serviceDue = Number(res.service_due || 0);
                    const extraFeeDue = Number(res.extra_fee_due || 0);
                    const posDue = Number(res.pos_due || 0);
                    const accountDue = Number(res.account_due || (remaining + serviceDue + extraFeeDue + posDue));
                    const methodMap = { cash:'💵 كاش', network:'💳 شبكة', card:'💳 شبكة', bank_transfer:'🏦 تحويل بنكي', online:'🌐 إلكتروني' };
                    const method = methodMap[res.payment_method] || '';

                    let paymentSummary = '';
                    if (res.status === 'cancelled') {
                        paymentSummary = `حالة الدفع: <span style="color:#64748b;font-weight:800;">⚪ ملغي / غير مدفوع</span><br>قيمة الحجز: <strong>0.00</strong>`;
                    } else if (paid > 0 && remaining > 0.01) {
                        paymentSummary = `حالة دفع الحجز: <span style="color:#d97706;font-weight:800;">🟡 عربون</span><br>قيمة الحجز: <strong>${total.toFixed(2)}</strong><br>المدفوع للحجز: <strong style="color:#047857;">${paid.toFixed(2)}</strong> ${method ? `(${method})` : ''}<br>المتبقي من الحجز: <strong style="color:#dc2626;">${remaining.toFixed(2)}</strong>`;
                    } else if (paid > 0 && remaining <= 0.01) {
                        paymentSummary = `حالة دفع الحجز: <span style="color:#10b981;font-weight:800;">🟢 مدفوع بالكامل</span><br>قيمة الحجز: <strong>${total.toFixed(2)}</strong><br>المدفوع للحجز: <strong style="color:#047857;">${paid.toFixed(2)}</strong> ${method ? `(${method})` : ''}`;
                    } else {
                        paymentSummary = `حالة دفع الحجز: <span style="color:#ef4444;font-weight:800;">🔴 غير مدفوع</span><br>قيمة الحجز: <strong>${total.toFixed(2)}</strong><br>المتبقي من الحجز: <strong>${remaining.toFixed(2)}</strong>`;
                    }

                    if (res.status !== 'cancelled' && (serviceDue > 0.01 || extraFeeDue > 0.01 || posDue > 0.01)) {
                        paymentSummary += `<div style="margin-top:10px;padding-top:10px;border-top:1px dashed #cbd5e1;">
                            <strong>تحصيلات إضافية غير محصلة:</strong>
                            ${serviceDue > 0.01 ? `<br>🛎️ خدمات: <strong style="color:#b45309">${serviceDue.toFixed(2)} ريال</strong>` : ''}
                            ${posDue > 0.01 ? `<br>🧾 POS: <strong style="color:#b45309">${posDue.toFixed(2)} ريال</strong>` : ''}
                            ${extraFeeDue > 0.01 ? `<br>➕ رسوم إضافية: <strong style="color:#b45309">${extraFeeDue.toFixed(2)} ريال</strong>` : ''}
                            <br><strong style="color:#0f766e">إجمالي التحصيل المطلوب: ${accountDue.toFixed(2)} ريال</strong>
                        </div>`;
                    }

                    return `
                        <div class="invoice-details" id="details-${res.id}">
                            <div id="invoice-content-${res.id}" style="padding:20px;background:white;">
                                <div class="invoice-header">
                                    <h2>فاتورة حجز #BKG-${res.id}</h2>
                                    <div style="text-align:right;">
                                        <strong>الإجمالي: ${total.toFixed(2)}</strong><br>
                                        ${paymentSummary}
                                    </div>
                                </div>
                                <div class="invoice-body">
                                    <div class="invoice-section">
                                        <strong>بيانات العميل</strong><br><br>
                                        الاسم: ${res.guest_name}<br>
                                        الهاتف: <span dir="ltr">${res.phone || 'غير مسجل'}</span><br>
                                        الهوية: ${res.id_number || 'غير مسجلة'}
                                    </div>
                                    <div class="invoice-section">
                                        <strong>تفاصيل الإقامة</strong><br><br>
                                        الغرفة: ${res.room_number || 'بانتظار التخصيص'}<br>
                                        الدخول: ${res.check_in}<br>
                                        الخروج: ${res.check_out}<br>
                                        <div style="margin-top:10px;padding-top:10px;border-top:1px dashed #cbd5e1;">
                                            <strong>الخطة الغذائية:</strong> ${escapeHtml(pmsReservationTranslate(res.meal_plan || 'بدون وجبات'))}<br>
                                            <strong>قيمة الوجبات:</strong> ${Number(res.meal_total || 0).toFixed(2)} ريال
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="invoice-actions">${actionBtns}</div>
                        </div>
                    `;
                }

                function renderSingleReservation(res) {
                    const meta = buildActionButtons(res);
                    const rowHtml = `
                        <div class="compact-row ${meta.statusClass}" onclick="toggleDetails(${res.id})">
                            <div class="row-basic-info">
                                <div style="display:flex;align-items:center;gap:10px;">
                                    <input type="checkbox" class="res-cb checkbox-item" value="${res.id}" onclick="event.stopPropagation()">
                                    <span class="col-id">#BKG-${res.id}</span>
                                </div>
                                <span class="col-name">👤 ${res.guest_name}</span>
                                <span class="col-room">🚪 ${escapeHtml(pmsReservationTranslate('غرفة '))}${escapeHtml(res.room_number || pmsReservationTranslate('بانتظار التخصيص'))}</span>
                                <span class="col-dates">🗓️ ${res.check_in} ➡️ ${res.check_out}</span>
                                <span style="color:#7d4f9f;font-weight:800;font-size:12px;">🍽️ ${escapeHtml(pmsReservationTranslate(res.meal_plan || 'بدون وجبات'))}</span>
                                <span class="col-status"><span class="badge ${meta.badgeClass}">${meta.statusText}</span></span>
                            </div>
                        </div>
                        ${buildReservationDetails(res, meta.actionBtns, meta)}
                    `;
                    container.innerHTML += rowHtml;
                }

                function renderBookingGroup(group, groupIndex) {
                    const first = group[0];
                    const groupKey = 'booking-group-' + groupIndex;
                    const groupIds = group.map(r => Number(r.id));
                    const roomChips = group.map(r =>
                        `<span class="booking-room-chip">🚪 ${escapeHtml(r.room_number || 'بانتظار')}</span>`
                    ).join('');

                    const statuses = group.map(r => statusMetaForReservation(r));
                    const allChecked = group.every(r => r.status === 'checked_in');
                    const somePending = group.some(r => r.status === 'pending');
                    const groupStatusSource = allChecked ? 'مكتملة الإقامة' : (somePending ? 'تحتاج متابعة' : 'حجز جماعي');
                    const groupStatus = pmsReservationTranslate(groupStatusSource);
                    const statusCounts = {};
                    group.forEach(r => { statusCounts[r.status] = (statusCounts[r.status] || 0) + 1; });
                    const totalGroup = group.reduce((sum,r) => sum + Number(r.booking_total_amount ?? r.total_amount ?? 0), 0);
                    const paidGroup = group.reduce((sum,r) => sum + Number(r.paid_amount || 0), 0);
                    const remainingGroup = Math.max(0, totalGroup - paidGroup);
                    const breakfastRooms = group.filter(r => String(r.meal_plan || '').includes('إفطار')).length;

                    const children = group.map(res => {
                        const meta = buildActionButtons(res);
                        return `
                            <div class="booking-child-row">
                                <div class="booking-child-summary ${meta.statusClass}" onclick="toggleDetails(${res.id})">
                                    <div class="booking-child-left">
                                        <input type="checkbox" class="res-cb checkbox-item" value="${res.id}" onclick="event.stopPropagation()">
                                        <span class="booking-child-id">#BKG-${res.id}</span>
                                        <span class="booking-child-room">🚪 ${escapeHtml(res.room_number || 'بانتظار')}</span>
                                        <span class="booking-child-meta">🍽️ ${escapeHtml(pmsReservationTranslate(res.meal_plan || 'بدون وجبات'))}</span>
                                        <span class="badge ${meta.badgeClass}">${meta.statusText}</span>
                                    </div>
                                    <button type="button" class="btn booking-group-toggle" onclick="event.stopPropagation(); toggleBookingGroupRow('child-${res.id}')"><i class="fa-solid fa-chevron-down"></i></button>
                                </div>
                                ${buildReservationDetails(res, meta.actionBtns, meta)}
                            </div>
                        `;
                    }).join('');

                    container.innerHTML += `
                        <div class="booking-group-card" id="${groupKey}">
                            <div class="booking-group-head" onclick="toggleBookingGroup('${groupKey}')">
                                <div>
                                    <div class="booking-group-title">👥 حجز جماعي — ${escapeHtml(first.guest_name || 'عميل')}</div>
                                    <div class="booking-group-sub">${group.length} غرف • ${group.length} حجوزات • ${escapeHtml(first.check_in || '')} → ${escapeHtml(first.check_out || '')}</div>
                                </div>
                                <div class="booking-group-stat">
                                    <span>الغرف</span>
                                    <div class="booking-group-rooms">${roomChips}</div>
                                </div>
                                <div class="booking-group-stat">
                                    <span>الإقامة</span>
                                    <strong>${Number(first.adults || 0)} بالغ • ${Number(first.children || 0)} طفل</strong>
                                    <span>${breakfastRooms}/${group.length} غرفة بإفطار • ${totalGroup.toFixed(2)} ريال</span>
                                </div>
                                <div class="booking-group-actions">
                                    <span class="booking-group-label">${allChecked ? '✅ ' : '👥 '}${groupStatus}</span>
                                    <button type="button" class="booking-group-toggle" onclick="event.stopPropagation(); toggleBookingGroup('${groupKey}')"><i class="fa-solid fa-chevron-down"></i></button>
                                </div>
                            </div>
                            <div class="booking-group-body" id="${groupKey}-body">
                                ${children}
                                <div class="booking-group-footer">
                                    <span>إجمالي المجموعة: <strong>${totalGroup.toFixed(2)} ريال</strong> • المدفوع: ${paidGroup.toFixed(2)} • المتبقي: ${remainingGroup.toFixed(2)}</span>
                                    <span>💡 هذه بطاقة جماعية للعرض فقط؛ كل Reservation يبقى مستقلاً داخل المجموعة.</span>
                                </div>
                            </div>
                        </div>
                    `;
                }

                // نعرض المجموعة فقط عند وجود أكثر من حجز متوافق.
                getGroupedReservations(allReservations).forEach((group, idx) => {
                    if (group.length > 1) renderBookingGroup(group, idx);
                    else renderSingleReservation(group[0]);
                });

            } else {
                container.innerHTML = `<p style="color:red; text-align:center;">${pmsReservationTranslate(data.message)}</p>`;
            }
        } catch(error) { 
            console.error("Error:", error);
            container.innerHTML = '<p style="text-align:center; color:red;">حدث خطأ أثناء جلب البيانات من الخادم.</p>';
        }
    }


    function toggleBookingGroup(groupId) {
        const body = document.getElementById(groupId + '-body');
        if (!body) return;
        body.classList.toggle('open');
    }

    function toggleBookingGroupRow(id) {
        const el = document.getElementById(id);
        if (!el) return;
        const details = el.closest('.booking-child-row')?.querySelector('.invoice-details');
        if (details) details.style.display = details.style.display === 'block' ? 'none' : 'block';
    }

    function toggleDetails(id) {
        const detailsDiv = document.getElementById('details-' + id);
        detailsDiv.style.display = detailsDiv.style.display === 'block' ? 'none' : 'block';
    }

    // ==========================================================
    // 💳 حساب النزيل عند Checkout: الحجز + POS على الحساب
    // ==========================================================
    async function getCheckoutSummary(resId){
        const r=await fetch('../api/admin/process_reservation.php',{
            method:'POST',headers:{'Content-Type':'application/json'},
            body:JSON.stringify({reservation_id:resId,action:'checkout_summary'})
        });
        const raw=await r.text();let d;
        try{d=JSON.parse(raw);}catch(e){
            const a=raw.indexOf('{'),b=raw.lastIndexOf('}');
            if(a>=0&&b>a)d=JSON.parse(raw.slice(a,b+1));else throw new Error('الخادم لم يرجع JSON صحيحاً.');
        }
        if(d.status!=='success')throw new Error(d.message||'تعذر قراءة حساب النزيل.');
        return d.checkout||{};
    }

    async function collectReservationAccount(resId){
        try{
            Swal.fire({title:'جاري قراءة حساب النزيل...',allowOutsideClick:false,didOpen:()=>Swal.showLoading()});
            const a=await getCheckoutSummary(resId);
            Swal.close();

            const bookingTotal=Number(a.booking_total||0);
            const bookingPaid=Number(a.booking_paid||0);
            const bookingDue=Number(a.booking_due||0);
            const serviceDue=Number(a.service_due||0);
            const serviceRequests=Array.isArray(a.service_requests)?a.service_requests:[];
            const posDue=Number(a.pos_due||0);
            const grandDue=Number(a.grand_due||0);
            const posSales=Array.isArray(a.pos_sales)?a.pos_sales:[];
            const extraFeeDue=Number(a.extra_fee_due||0);
            const extraFees=Array.isArray(a.extra_fees)?a.extra_fees:[];

            if(grandDue<=0.01){
                await Swal.fire({
                    icon:'success',
                    title:'لا يوجد مبلغ مستحق',
                    text:'حساب النزيل مسدد بالكامل حالياً.',
                    confirmButtonText:'حسنًا'
                });
                return;
            }

            let reasonsHtml='';
            if(bookingDue>0.01){
                reasonsHtml += `
                    <div style="display:flex;justify-content:space-between;gap:10px;padding:9px 10px;background:#fff;border:1px solid #e2e8f0;border-radius:7px;margin-bottom:7px;">
                        <span>متبقي من قيمة الحجز</span><strong style="color:#b91c1c">${bookingDue.toFixed(2)} ريال</strong>
                    </div>`;
            }

            if(serviceDue>0.01){
                const serviceRows = serviceRequests.length
                    ? serviceRequests.map(s => `
                        <div style="display:flex;justify-content:space-between;gap:10px;padding:8px 10px;background:#fff;border:1px dashed #c4b5fd;border-radius:7px;margin-top:6px;">
                            <span>🛎️ ${escapeHtml(s.service_name || 'خدمة')}</span>
                            <strong style="color:#7c3aed">${Number(s.amount||0).toFixed(2)} ريال</strong>
                        </div>`).join('')
                    : `<div style="color:#6b21a8;font-size:12px;margin-top:7px;">خدمات غير محصلة بقيمة ${serviceDue.toFixed(2)} ريال.</div>`;
                reasonsHtml += `
                    <div style="background:#f5f3ff;border:1px solid #c4b5fd;border-radius:9px;padding:10px;margin-top:8px;">
                        <div style="font-weight:900;color:#6b21a8;">🛎️ خدمات النزيل غير المحصلة — ${serviceDue.toFixed(2)} ريال</div>
                        ${serviceRows}
                    </div>`;
            }

            if(extraFeeDue>0.01){
                const extraRows = extraFees.length
                    ? extraFees.map(f => `
                        <div style="padding:8px 10px;background:#fff;border:1px dashed #fdba74;border-radius:7px;margin-top:6px;">
                            <div><strong>${escapeHtml(f.reason || 'رسم إضافي')}</strong> — ${Number(f.amount||0).toFixed(2)} ريال</div>
                            ${f.details ? `<div style="font-size:10px;color:#64748b;margin-top:3px;">${escapeHtml(f.details)}</div>` : ''}
                        </div>`).join('')
                    : `<div style="color:#92400e;font-size:12px;margin-top:7px;">رسوم إضافية غير محصلة بقيمة ${extraFeeDue.toFixed(2)} ريال.</div>`;
                reasonsHtml += `
                    <div style="background:#fff7ed;border:1px solid #fdba74;border-radius:9px;padding:10px;margin-top:8px;">
                        <div style="font-weight:900;color:#92400e;">➕ رسوم إضافية غير محصلة — ${extraFeeDue.toFixed(2)} ريال</div>
                        ${extraRows}
                    </div>`;
            }

            if(posDue>0.01){
                const posRows = posSales.length
                    ? posSales.map(s => `
                        <div style="display:flex;justify-content:space-between;gap:10px;padding:8px 10px;background:#fff;border:1px dashed #fdba74;border-radius:7px;margin-top:6px;">
                            <span>🧾 ${escapeHtml(s.sale_number || ('POS-'+s.id))}</span>
                            <strong style="color:#b45309">${Number(s.amount||0).toFixed(2)} ريال</strong>
                        </div>`).join('')
                    : `<div style="color:#92400e;font-size:12px;margin-top:7px;">توجد مبيعات POS على الحساب بقيمة ${posDue.toFixed(2)} ريال.</div>`;

                reasonsHtml += `
                    <div style="background:#fff7ed;border:1px solid #fdba74;border-radius:9px;padding:10px;margin-top:8px;">
                        <div style="font-weight:900;color:#92400e;">🧾 مبيعات POS على حساب النزيل — ${posDue.toFixed(2)} ريال</div>
                        ${posRows}
                    </div>`;
            }

            const choice=await Swal.fire({
                title:'تحصيل المستحقات فقط 💳',
                html:`
                    <div style="text-align:right;">
                        <div style="background:#ecfdf5;border:1px solid #86efac;border-radius:9px;padding:12px;margin-bottom:12px;">
                            <div style="font-weight:900;color:#065f46;">التحصيل لا يُنهي إقامة النزيل.</div>
                            <div style="font-size:12px;color:#475569;margin-top:4px;">سيبقى النزيل مسجلاً داخل الغرفة بعد إتمام التحصيل.</div>
                        </div>

                        <div style="background:#ecfdf5;border:1px solid #86efac;border-radius:9px;padding:10px;margin-bottom:10px;">
                            <div>قيمة الحجز الأصلي: <strong>${bookingTotal.toFixed(2)} ريال</strong></div>
                            <div>المدفوع للحجز: <strong>${bookingPaid.toFixed(2)} ريال</strong></div>
                            <div>المتبقي من الحجز: <strong>${bookingDue.toFixed(2)} ريال</strong></div>
                        </div>
                        <div style="font-weight:900;color:#334155;margin-bottom:7px;">سبب المبلغ المستحق:</div>
                        ${reasonsHtml}

                        <div style="margin-top:12px;border-top:1px dashed #cbd5e1;padding-top:10px;">
                            <span style="font-weight:800;">إجمالي المطلوب تحصيله:</span>
                            <div style="font-size:27px;font-weight:900;color:#0f766e;margin-top:4px;">${grandDue.toFixed(2)} ريال</div>
                        </div>

                        <div style="text-align:right;background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;padding:12px;margin-top:12px;">
                            <div style="font-weight:800;margin-bottom:9px;">طريقة التحصيل:</div>
                            <label style="display:flex;gap:9px;align-items:center;margin:9px 0;">
                                <input type="radio" name="reservation_collect_method" value="cash"> 💵 نقدي
                            </label>
                            <label style="display:flex;gap:9px;align-items:center;margin:9px 0;">
                                <input type="radio" name="reservation_collect_method" value="network"> 💳 شبكة
                            </label>
                            <label style="display:flex;gap:9px;align-items:center;margin:9px 0;">
                                <input type="radio" name="reservation_collect_method" value="bank_transfer"> 🏦 تحويل بنكي
                            </label>
                        </div>
                    </div>
                `,
                showCancelButton:true,
                confirmButtonColor:'#0f766e',
                cancelButtonColor:'#94a3b8',
                confirmButtonText:'تحصيل الآن بدون مغادرة',
                cancelButtonText:'تراجع',
                preConfirm:()=>{
                    const m=document.querySelector('input[name="reservation_collect_method"]:checked');
                    if(!m){
                        Swal.showValidationMessage('اختر طريقة التحصيل أولاً.');
                        return false;
                    }
                    return {payment_method:m.value};
                }
            });

            if(!choice.isConfirmed)return;

            Swal.fire({title:'جاري تحصيل المستحقات...',allowOutsideClick:false,didOpen:()=>Swal.showLoading()});
            const r=await fetch('../api/admin/process_reservation.php',{
                method:'POST',
                headers:{'Content-Type':'application/json'},
                body:JSON.stringify({
                    reservation_id:resId,
                    action:'collect_account',
                    payment_method:choice.value.payment_method
                })
            });

            const raw=await r.text();
            let d;
            try{d=JSON.parse(raw);}catch(e){
                const x=raw.indexOf('{'),y=raw.lastIndexOf('}');
                if(x>=0&&y>x)d=JSON.parse(raw.slice(x,y+1));
                else throw new Error('الخادم لم يرجع JSON صحيحاً.');
            }
            if(d.status!=='success')throw new Error(d.message||'تعذر تحصيل المستحقات.');

            await Swal.fire({
                icon:'success',
                title:'تم التحصيل',
                html:`تم تحصيل <strong>${grandDue.toFixed(2)} ريال</strong> بنجاح، دون إنهاء إقامة النزيل.`,
                confirmButtonText:'حسنًا'
            });
            fetchReservations();
        }catch(e){
            Swal.fire('تعذر التحصيل',e.message||'حدث خطأ غير متوقع.','error');
        }
    }

    async function openStayExtension(resId){
        try{
            const today=new Date();
            const minDate=new Date(today.getFullYear(),today.getMonth(),today.getDate()+1);
            const iso=(d)=>`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;

            const input=await Swal.fire({
                title:'➕ تمديد الإقامة',
                html:`<div style="text-align:right;line-height:1.9;">
                    <div>الحجز <strong>#BKG-${resId}</strong></div>
                    <div style="margin-top:8px;">حدد تاريخ الخروج الجديد:</div>
                    <input id="extension_new_date" type="date" min="${iso(minDate)}"
                        style="width:100%;box-sizing:border-box;padding:10px;border:1px solid #cbd5e1;border-radius:8px;font-family:inherit;margin-top:7px;">
                    <input id="extension_reason" type="text" maxlength="255"
                        placeholder="سبب التمديد (اختياري)"
                        style="width:100%;box-sizing:border-box;padding:10px;border:1px solid #cbd5e1;border-radius:8px;font-family:inherit;margin-top:10px;">
                </div>`,
                showCancelButton:true,
                confirmButtonColor:'#0f766e',
                cancelButtonColor:'#94a3b8',
                confirmButtonText:'فحص التوفر والحساب',
                cancelButtonText:'إلغاء',
                preConfirm:()=>{
                    const date=document.getElementById('extension_new_date').value;
                    if(!date){
                        Swal.showValidationMessage('حدد تاريخ الخروج الجديد.');
                        return false;
                    }
                    return {
                        new_check_out:date,
                        reason:document.getElementById('extension_reason').value.trim()
                    };
                }
            });
            if(!input.isConfirmed)return;

            Swal.fire({
                title:'جاري فحص توفر الغرفة وحساب التمديد...',
                allowOutsideClick:false,
                didOpen:()=>Swal.showLoading()
            });

            const response=await fetch('../api/admin/process_reservation.php',{
                method:'POST',
                headers:{'Content-Type':'application/json'},
                body:JSON.stringify({
                    reservation_id:resId,
                    action:'extend_stay_quote',
                    new_check_out:input.value.new_check_out
                })
            });
            const raw=await response.text();
            let data;
            try{data=JSON.parse(raw);}
            catch(e){
                const a=raw.indexOf('{'),b=raw.lastIndexOf('}');
                if(a>=0&&b>a)data=JSON.parse(raw.slice(a,b+1));
                else throw new Error('الخادم لم يرجع استجابة صحيحة.');
            }
            Swal.close();
            if(data.status!=='success')throw new Error(data.message||'تعذر حساب التمديد.');

            const x=data.extension||{};
            const current=x.current_room||{};
            const alternatives=Array.isArray(x.alternatives)?x.alternatives:[];
            const currentAvailable=current.available_for_extension===true;
            const canProceed=currentAvailable || alternatives.length>0;
            let selectedRoomId=currentAvailable?Number(current.room_id||0):Number(alternatives[0]?.room_id||0);

            const money=v=>Number(v||0).toLocaleString('ar-SA',{minimumFractionDigits:2,maximumFractionDigits:2});
            const esc=v=>String(v??'').replace(/[&<>'"]/g,ch=>({'&':'&amp;','<':'&lt;','>':'&gt;',"'":'&#39;','"':'&quot;'}[ch]));

            let roomBlock='';
            if(currentAvailable){
                roomBlock=`
                    <div style="margin-top:12px;background:#ecfdf5;border:1px solid #86efac;border-radius:9px;padding:11px;color:#166534;">
                        ✅ الغرفة الحالية <strong>${esc(current.room_number)}</strong> متاحة للتمديد حتى <strong>${esc(x.new_check_out)}</strong>.
                    </div>`;
            }else{
                const cards=alternatives.length
                    ? alternatives.map((room,idx)=>{
                        const checked=Number(room.room_id)===Number(selectedRoomId);
                        return `<label style="display:block;padding:11px;margin-top:7px;border:1px solid ${checked?'#0f766e':'#e2e8f0'};background:${checked?'#f0fdfa':'#fff'};border-radius:9px;cursor:pointer;">
                            <div style="display:flex;gap:9px;align-items:flex-start;">
                                <input type="radio" name="extension_target_room" value="${Number(room.room_id)}" ${checked?'checked':''} style="margin-top:4px;">
                                <div style="flex:1;">
                                    <div style="font-weight:900;">الغرفة ${esc(room.room_number)} — ${esc(room.room_type_name||'')}</div>
                                    <div style="font-size:11px;color:#64748b;margin-top:3px;">سعر الغرفة: ${money(room.nightly_price)} ريال/ليلة</div>
                                    <div style="font-size:11px;color:#64748b;">قيمة التمديد بهذه الغرفة: ${money(room.extension_reference_price)} ريال</div>
                                    <div style="margin-top:4px;color:#166534;font-weight:800;font-size:11px;">فرق سعر الغرفة لا يُحصّل ولا يُسترد.</div>
                                </div>
                            </div>
                        </label>`;
                    }).join('')
                    : `<div style="margin-top:9px;color:#b91c1c;font-weight:800;">لا توجد غرفة بديلة صالحة ومتاحة الآن حتى نهاية التمديد.</div>`;

                roomBlock=`
                    <div style="margin-top:12px;background:#fff7ed;border:1px solid #fdba74;border-radius:9px;padding:11px;color:#92400e;">
                        <div style="font-weight:900;">⚠️ الغرفة الحالية لا يمكن تمديدها</div>
                        <div style="font-size:11px;margin-top:4px;">يوجد تعارض بعد تاريخ الخروج الحالي. بحث النظام عن غرفة بديلة متاحة الآن وتبقى صالحة حتى نهاية التمديد.</div>
                        ${cards}
                    </div>`;
            }

            const summary=await Swal.fire({
                title:'مراجعة التمديد',
                html:`<div style="text-align:right;line-height:1.9;">
                    <div>من <strong>${esc(x.old_check_out)}</strong> إلى <strong>${esc(x.new_check_out)}</strong></div>
                    <div>عدد الليالي الإضافية: <strong>${Number(x.extension_nights||0)}</strong></div>
                    ${canProceed ? `<div style="margin-top:8px;background:#eef2ff;border:1px solid #c7d2fe;border-radius:9px;padding:11px;color:#3730a3;">
                        <div>المبلغ المستحق للتمديد:</div>
                        <div style="font-size:24px;font-weight:900;">${money(x.extension_total)} ريال</div>
                        <div style="font-size:11px;margin-top:4px;">الحساب وفق سعر الغرفة الأصلية. لا يتم فرض فرق عند الترقية إلى غرفة أغلى ولا يُخصم مبلغ عند الانتقال إلى غرفة أرخص.</div>
                    </div>` : ''}
                    ${roomBlock}
                    <div style="margin-top:10px;color:#64748b;font-size:11px;">
                        ${canProceed ? 'سيعاد التحقق من التوفر قبل تنفيذ العملية.' : 'لا يمكن تنفيذ التمديد حاليًا لعدم وجود غرفة متاحة حتى نهاية فترة التمديد.'}
                    </div>
                </div>`,
                didOpen:()=>{
                    document.querySelectorAll('input[name="extension_target_room"]').forEach(el=>{
                        el.addEventListener('change',()=>{selectedRoomId=Number(el.value);});
                    });
                },
                showCancelButton:true,
                confirmButtonColor:'#0f766e',
                cancelButtonColor:'#94a3b8',
                confirmButtonText:canProceed?'متابعة التحصيل':'إغلاق',
                cancelButtonText:'إلغاء',
                preConfirm:()=>{
                    if(!canProceed)return {blocked:true};
                    if(!currentAvailable && selectedRoomId<=0){
                        Swal.showValidationMessage('اختر غرفة بديلة.');
                        return false;
                    }
                    return true;
                }
            });
            if(!summary.isConfirmed)return;
            if(!canProceed)return;

            const payment=await Swal.fire({
                title:'تحصيل التمديد 💳',
                html:`<div style="text-align:right;">
                    <div style="background:#fff7ed;border:1px solid #fdba74;border-radius:9px;padding:11px;color:#92400e;">
                        المطلوب: <strong>${money(x.extension_total)} ريال</strong>
                    </div>
                    <div style="margin-top:12px;">
                        <label style="display:flex;gap:8px;align-items:center;margin:9px 0;"><input type="radio" name="stay_extension_method" value="cash"> 💵 كاش</label>
                        <label style="display:flex;gap:8px;align-items:center;margin:9px 0;"><input type="radio" name="stay_extension_method" value="network"> 💳 شبكة</label>
                        <label style="display:flex;gap:8px;align-items:center;margin:9px 0;"><input type="radio" name="stay_extension_method" value="bank_transfer"> 🏦 تحويل بنكي</label>
                    </div>
                </div>`,
                showCancelButton:true,
                confirmButtonColor:'#0f766e',
                cancelButtonColor:'#94a3b8',
                confirmButtonText:'تأكيد التحصيل والتمديد',
                cancelButtonText:'رجوع',
                preConfirm:()=>{
                    const m=document.querySelector('input[name="stay_extension_method"]:checked');
                    if(!m){
                        Swal.showValidationMessage('اختر طريقة التحصيل أولاً.');
                        return false;
                    }
                    return m.value;
                }
            });
            if(!payment.isConfirmed)return;

            Swal.fire({
                title:'جاري تنفيذ التمديد وإعادة فحص التوفر...',
                allowOutsideClick:false,
                didOpen:()=>Swal.showLoading()
            });

            const exec=await fetch('../api/admin/process_reservation.php',{
                method:'POST',
                headers:{'Content-Type':'application/json'},
                body:JSON.stringify({
                    reservation_id:resId,
                    action:'extend_stay',
                    new_check_out:input.value.new_check_out,
                    payment_method:payment.value,
                    target_room_id:selectedRoomId,
                    extension_reason:input.value.reason||''
                })
            });

            const execRaw=await exec.text();
            let execData;
            try{execData=JSON.parse(execRaw);}
            catch(e){
                const a=execRaw.indexOf('{'),b=execRaw.lastIndexOf('}');
                if(a>=0&&b>a)execData=JSON.parse(execRaw.slice(a,b+1));
                else throw new Error('الخادم لم يرجع استجابة صحيحة.');
            }
            if(execData.status!=='success')throw new Error(execData.message||'تعذر تمديد الإقامة.');

            await Swal.fire({
                icon:'success',
                title:'تم تمديد الإقامة',
                text:execData.message||'تم تنفيذ التمديد بنجاح.',
                confirmButtonText:'حسنًا'
            });
            fetchReservations();

        }catch(e){
            Swal.close();
            Swal.fire('تعذر تمديد الإقامة',e.message||'حدث خطأ غير متوقع.','error');
        }
    }

async function openEarlyCheckin(resId){
        try{
            Swal.fire({
                title:'جاري فحص موعد التسكين وتوفر الغرفة...',
                allowOutsideClick:false,
                didOpen:()=>Swal.showLoading()
            });

            const response=await fetch('../api/admin/process_reservation.php',{
                method:'POST',
                headers:{'Content-Type':'application/json'},
                body:JSON.stringify({reservation_id:resId,action:'early_checkin_quote'})
            });

            const raw=await response.text();
            let data;
            try{data=JSON.parse(raw);}
            catch(e){
                const a=raw.indexOf('{'),b=raw.lastIndexOf('}');
                if(a>=0&&b>a)data=JSON.parse(raw.slice(a,b+1));
                else throw new Error('الخادم لم يرجع استجابة صحيحة.');
            }

            Swal.close();
            if(data.status!=='success')throw new Error(data.message||'تعذر حساب التسكين المبكر.');

            const fee=data.early_checkin||{};
            const availability=data.room_availability||{};
            const feeAmount=Number(fee.total||0);
            const minutesUntil=Number(fee.minutes_until_checkin||0);
            const alternatives=Array.isArray(availability.alternatives)?availability.alternatives:[];
            const canProceed=availability.current_room_available===true || alternatives.length>0;

            const formatRemaining=(mins)=>{
                const days=Math.floor(mins/1440);
                const hours=Math.floor((mins%1440)/60);
                const minutes=mins%60;
                const parts=[];
                if(days)parts.push(`${days} يوم`);
                if(hours)parts.push(`${hours} ساعة`);
                if(minutes && parts.length<2)parts.push(`${minutes} دقيقة`);
                return parts.join(' و ')||'أقل من دقيقة';
            };

            const money=v=>Number(v||0).toLocaleString('ar-SA',{minimumFractionDigits:2,maximumFractionDigits:2});
            const escLocal=v=>String(v??'').replace(/[&<>'"]/g,ch=>({'&':'&amp;','<':'&lt;','>':'&gt;',"'":'&#39;','"':'&quot;'}[ch]));

            // نختار الغرفة الحالية تلقائيًا إن كانت متاحة، وإلا نعرض البدائل.
            const currentAvailable=availability.current_room_available===true;
            let selectedRoomId=currentAvailable
                ? Number(availability.current_room?.room_id||0)
                : (alternatives.length?Number(alternatives[0].room_id||0):0);

            const selectedAlt=()=>alternatives.find(x=>Number(x.room_id)===Number(selectedRoomId))||null;

            const remaining=minutesUntil>0?formatRemaining(minutesUntil):'';
            const noFee=feeAmount<=0.01;

            let roomSection='';
            if(currentAvailable){
                roomSection=`
                    <div style="margin-top:13px;background:#ecfdf5;border:1px solid #86efac;border-radius:10px;padding:12px;color:#166534;">
                        <div style="font-weight:900;">✅ الغرفة الحالية متاحة الآن وجاهزة للتسكين</div>
                        <div style="margin-top:5px;">الغرفة: <strong>${escLocal(availability.current_room?.room_number||'')}</strong></div>
                        <div style="font-size:11px;margin-top:4px;">تم التحقق من عدم وجود تعارض حتى نهاية إقامة النزيل.</div>
                    </div>`;
            }else{
                const cards=alternatives.length
                    ? alternatives.map((room,idx)=>{
                        const diff=Number(room.difference||0);
                        const diffLabel=diff>0.01
                            ? `<span style="color:#b45309;font-weight:900;">زيادة ${money(diff)} ريال</span>`
                            : diff<-0.01
                            ? `<span style="color:#047857;font-weight:900;">استرداد ${money(Math.abs(diff))} ريال</span>`
                            : `<span style="color:#64748b;font-weight:900;">بدون فرق</span>`;
                        const checked=(Number(room.room_id)===Number(selectedRoomId))?'checked':'';
                        return `
                            <label style="display:block;border:1px solid ${checked?'#0f766e':'#e2e8f0'};background:${checked?'#f0fdfa':'#fff'};border-radius:10px;padding:10px;margin-top:7px;cursor:pointer;">
                                <div style="display:flex;gap:9px;align-items:flex-start;">
                                    <input type="radio" name="early_alt_room" value="${Number(room.room_id)}" ${checked} style="margin-top:4px;">
                                    <div style="flex:1;">
                                        <div style="font-weight:900;">الغرفة ${escLocal(room.room_number)} — ${escLocal(room.room_type_name||'')}</div>
                                        <div style="font-size:11px;color:#64748b;margin-top:3px;">الليلة: ${money(room.room_price)} ريال • إجمالي الإقامة: ${money(room.stay_total)} ريال</div>
                                        <div style="margin-top:4px;">${diffLabel}</div>
                                    </div>
                                </div>
                            </label>`;
                    }).join('')
                    : `<div style="color:#b91c1c;font-weight:800;margin-top:8px;">لا توجد غرفة بديلة جاهزة ومتاحة طوال فترة إقامة النزيل.</div>`;

                roomSection=`
                    <div style="margin-top:13px;background:#fff7ed;border:1px solid #fdba74;border-radius:10px;padding:12px;color:#92400e;">
                        <div style="font-weight:900;">⚠️ الغرفة الحالية غير متاحة الآن</div>
                        <div style="font-size:12px;margin-top:4px;">بحث النظام عن غرف أخرى تكون متاحة الآن وتبقى متاحة حتى نهاية إقامة النزيل.</div>
                        <div style="margin-top:10px;font-weight:900;">${alternatives.length?'الغرفة البديلة المقترحة:':'نتيجة البحث:'}</div>
                        ${cards}
                    </div>`;
            }

            const totalForSelected=()=>{
                const alt=selectedAlt();
                const diff=alt?Number(alt.difference||0):0;
                const pay=Math.max(0,feeAmount+Math.max(0,diff));
                const refund=Math.max(0,-diff);
                return {pay,refund,diff};
            };

            const choice=await Swal.fire({
                icon:canProceed?'warning':'error',
                title:canProceed?'⚠️ انتباه: تسكين مبكر':'تعذر التسكين المبكر',
                html:`<div style="text-align:right;line-height:1.85;">
                    <div>الحجز <strong>#BKG-${resId}</strong></div>
                    <div style="margin-top:6px;">النزيل يريد التسكين قبل موعد الدخول الرسمي.</div>
                    ${remaining?`<div>باقي على بداية الحجز: <strong>${escLocal(remaining)}</strong>.</div>`:''}
                    ${fee.scheduled_at?`<div style="font-size:11px;color:#64748b;">وقت الدخول الرسمي: <strong>${escLocal(String(fee.scheduled_at).slice(0,16))}</strong></div>`:''}
                    ${roomSection}
                    ${canProceed ? (noFee
                        ? `<div style="margin-top:11px;background:#eef2ff;border:1px solid #c7d2fe;border-radius:9px;padding:10px;color:#3730a3;">لا توجد رسوم دخول مبكر ضمن الإعداد الحالي.</div>`
                        : `<div style="margin-top:11px;background:#fff7ed;border:1px solid #fdba74;border-radius:9px;padding:10px;color:#92400e;">رسوم الدخول المبكر الأساسية: <strong>${money(feeAmount)} ريال</strong></div>`) : ''}
                    ${canProceed ? `<div id="early-selection-summary" style="margin-top:10px;background:#f8fafc;border:1px solid #e2e8f0;border-radius:9px;padding:10px;"></div>` : ''}
                    <div style="margin-top:9px;color:#64748b;font-size:11px;">
                        لا يتم تغيير الغرفة ولا حالة الحجز من هذه النافذة إلا بعد التأكيد والتحقق النهائي من التوفر.
                    </div>
                </div>`,
                didOpen:()=>{
                    const update=()=>{
                        if(!canProceed)return;
                        const r=document.querySelector('input[name="early_alt_room"]:checked');
                        if(r)selectedRoomId=Number(r.value);
                        const alt=selectedAlt();
                        const diff=alt?Number(alt.difference||0):0;
                        const pay=Math.max(0,feeAmount+Math.max(0,diff));
                        const refund=Math.max(0,-diff);
                        const box=document.getElementById('early-selection-summary');
                        if(box){
                            if(diff>0.01) box.innerHTML=`سيُحصّل الآن: <strong>${money(pay)} ريال</strong> (رسوم دخول مبكر ${money(feeAmount)} + فرق الغرفة ${money(diff)}).`;
                            else if(diff<-0.01) box.innerHTML=`سيُحصّل رسم الدخول المبكر: <strong>${money(feeAmount)} ريال</strong> وسيُسترد فرق الغرفة: <strong>${money(refund)} ريال</strong>.`;
                            else box.innerHTML=`المبلغ المطلوب الآن: <strong>${money(pay)} ريال</strong>.`;
                        }
                    };
                    document.querySelectorAll('input[name="early_alt_room"]').forEach(el=>el.addEventListener('change',update));
                    update();
                },
                showCancelButton:true,
                confirmButtonColor:'#0f766e',
                cancelButtonColor:'#94a3b8',
                confirmButtonText:!canProceed?'إغلاق':((!currentAvailable&&alternatives.length)?'اختيار الغرفة والمتابعة':(noFee?'فتح شاشة التسكين':`تحصيل ${money(feeAmount)} ريال والمتابعة`)),
                cancelButtonText:'إلغاء',
                preConfirm:()=>{
                    if(!currentAvailable && selectedRoomId<=0){
                        Swal.showValidationMessage('يجب اختيار غرفة بديلة متاحة طوال فترة الإقامة.');
                        return false;
                    }
                    return {target_room_id:selectedRoomId};
                }
            });

            if(!choice.isConfirmed)return;
            if(!canProceed)return;

            const alt=selectedAlt();
            const diff=alt?Number(alt.difference||0):0;
            const payNow=Math.max(0,feeAmount+Math.max(0,diff));
            const refundNow=Math.max(0,-diff);

            let paymentMethod='';
            let refundMethod='';

            if(payNow>0.01){
                const payChoice=await Swal.fire({
                    title:'تحصيل التسكين المبكر',
                    html:`<div style="text-align:right;">
                        <div style="background:#fff7ed;border:1px solid #fdba74;border-radius:9px;padding:11px;color:#92400e;">
                            المبلغ المطلوب تحصيله: <strong>${money(payNow)} ريال</strong>
                        </div>
                        <div style="margin-top:12px;">
                            <label style="display:flex;gap:8px;align-items:center;margin:9px 0;"><input type="radio" name="early_collect_method_final" value="cash"> 💵 كاش</label>
                            <label style="display:flex;gap:8px;align-items:center;margin:9px 0;"><input type="radio" name="early_collect_method_final" value="network"> 💳 شبكة</label>
                            <label style="display:flex;gap:8px;align-items:center;margin:9px 0;"><input type="radio" name="early_collect_method_final" value="bank_transfer"> 🏦 تحويل بنكي</label>
                        </div>
                    </div>`,
                    showCancelButton:true,
                    confirmButtonColor:'#0f766e',
                    cancelButtonColor:'#94a3b8',
                    confirmButtonText:'تأكيد التحصيل',
                    cancelButtonText:'رجوع',
                    preConfirm:()=>{
                        const m=document.querySelector('input[name="early_collect_method_final"]:checked');
                        if(!m){Swal.showValidationMessage('اختر طريقة التحصيل.');return false;}
                        return m.value;
                    }
                });
                if(!payChoice.isConfirmed)return;
                paymentMethod=payChoice.value;
            }

            if(refundNow>0.01){
                const refundChoice=await Swal.fire({
                    title:'استرداد فرق الغرفة',
                    html:`سيُسترد للنزيل <strong>${money(refundNow)} ريال</strong> لأن الغرفة البديلة أرخص.`,
                    icon:'info',
                    showCancelButton:true,
                    confirmButtonColor:'#0f766e',
                    cancelButtonColor:'#94a3b8',
                    confirmButtonText:'متابعة الاسترداد',
                    cancelButtonText:'إلغاء',
                });
                if(!refundChoice.isConfirmed)return;
                // نفس طريقة التحصيل يمكن أن تمثل طريقة رد المبلغ عند التنفيذ.
                refundMethod=paymentMethod||'cash';
            }

            Swal.fire({
                title:'جاري إعادة التحقق وتثبيت الغرفة...',
                allowOutsideClick:false,
                didOpen:()=>Swal.showLoading()
            });

            const pay=await fetch('../api/admin/process_reservation.php',{
                method:'POST',
                headers:{'Content-Type':'application/json'},
                body:JSON.stringify({
                    reservation_id:resId,
                    action:'early_checkin_collect',
                    payment_method:paymentMethod || 'cash',
                    target_room_id:selectedRoomId
                })
            });

            const payRaw=await pay.text();
            let payData;
            try{payData=JSON.parse(payRaw);}
            catch(e){
                const a=payRaw.indexOf('{'),b=payRaw.lastIndexOf('}');
                if(a>=0&&b>a)payData=JSON.parse(payRaw.slice(a,b+1));
                else throw new Error('الخادم لم يرجع استجابة صحيحة للتسكين المبكر.');
            }

            if(payData.status!=='success')throw new Error(payData.message||'تعذر تنفيذ التسكين المبكر.');

            await Swal.fire({
                icon:'success',
                title:'تم',
                text:payData.message||'تم تثبيت الغرفة والتحصيل بنجاح.',
                confirmButtonText:'متابعة التسكين'
            });

            window.location.href=`checkin.php?id=${resId}`;

        }catch(e){
            Swal.close();
            Swal.fire('تعذر التسكين المبكر',e.message||'حدث خطأ غير متوقع.','error');
        }
    }

async function openCheckoutAccount(resId,early=false){
        if(early){
            return openEarlyDeparture(resId);
        }

        try{
            Swal.fire({title:'جاري قراءة حساب النزيل...',allowOutsideClick:false,didOpen:()=>Swal.showLoading()});
            const a=await getCheckoutSummary(resId);
            Swal.close();

            const bookingDue=Number(a.booking_due||0);
            const posDue=Number(a.pos_due||0);
            const grandDue=Number(a.grand_due||0);
            const posCount=Number(a.pos_sales_count||0);
            const posSales=Array.isArray(a.pos_sales)?a.pos_sales:[];
            const extraFees=Array.isArray(a.extra_fees)?a.extra_fees:[];

            const posList=posSales.length ? posSales.map(s=>`
                <div style="display:flex;justify-content:space-between;gap:10px;padding:7px 9px;background:#fff;border:1px dashed #fdba74;border-radius:7px;margin-top:5px;">
                    <span>🧾 ${escapeHtml(s.sale_number || ('POS-'+s.id))}</span>
                    <strong style="color:#b45309">${Number(s.amount||0).toFixed(2)} ريال</strong>
                </div>`).join('') : '';

            const extraList=extraFees.length ? extraFees.map(f=>`
                <div style="display:flex;justify-content:space-between;gap:10px;padding:7px 9px;background:#fff;border:1px dashed #cbd5e1;border-radius:7px;margin-top:5px;">
                    <span>⏱️ ${escapeHtml(f.reason||'رسوم إضافية')}</span>
                    <strong>${Number(f.total_amount||0).toFixed(2)} ريال</strong>
                </div>`).join('') : '';

            const details=grandDue>0.01?`
                <div class="checkout-due-box">
                    <div style="font-weight:900;color:#92400e;">⚠️ يوجد مبلغ مستحق على النزيل</div>
                    <div style="margin-top:8px;">متبقي الحجز: <strong>${bookingDue.toFixed(2)} ريال</strong></div>
                    <div style="margin-top:5px;">مشتريات POS على الحساب: <strong>${posDue.toFixed(2)} ريال</strong>${posCount?` <span style="color:#64748b;">(${posCount} عملية)</span>`:''}</div>
                    ${posList ? `<div style="margin-top:8px;">${posList}</div>` : ''}
                    ${extraList ? `<div style="margin-top:8px;">${extraList}</div>` : ''}
                    <div style="border-top:1px dashed #fdba74;margin-top:10px;padding-top:10px;">إجمالي المستحق للتحصيل</div>
                    <div class="checkout-total-due">${grandDue.toFixed(2)} ريال</div>
                </div>
                <div style="text-align:right;background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;padding:12px;margin-top:14px;">
                    <div style="font-weight:800;margin-bottom:9px;">طريقة التحصيل:</div>
                    <label style="display:flex;gap:9px;align-items:center;margin:9px 0;"><input type="radio" name="checkout_payment_method" value="cash"> 💵 نقدي</label>
                    <label style="display:flex;gap:9px;align-items:center;margin:9px 0;"><input type="radio" name="checkout_payment_method" value="network"> 💳 شبكة</label>
                    <label style="display:flex;gap:9px;align-items:center;margin:9px 0;"><input type="radio" name="checkout_payment_method" value="bank_transfer"> 🏦 تحويل بنكي</label>
                </div>`:
                `<div style="background:#ecfdf5;border:1px solid #86efac;border-radius:8px;padding:14px;text-align:right;">✅ لا يوجد مبلغ مستحق على النزيل.</div>`;

            const choice=await Swal.fire({
                title:'المغادرة وتحصيل الحساب 💳',
                html:`<div style="text-align:right;"><p>الحجز <strong>#BKG-${resId}</strong></p>${details}<p style="color:#64748b;font-size:12px;">لن يتم إنهاء المغادرة قبل تسوية المبلغ المستحق بالكامل.</p></div>`,
                showCancelButton:true,
                confirmButtonColor:'#0f766e',
                cancelButtonColor:'#94a3b8',
                confirmButtonText:grandDue>0.01?'تحصيل وإتمام المغادرة':'إتمام المغادرة',
                cancelButtonText:'تراجع',
                preConfirm:()=>{
                    if(grandDue<=0.01)return {payment_method:''};
                    const m=document.querySelector('input[name="checkout_payment_method"]:checked');
                    if(!m){Swal.showValidationMessage('اختر طريقة التحصيل أولاً.');return false;}
                    return {payment_method:m.value};
                }
            });

            if(!choice.isConfirmed)return;

            Swal.fire({title:'جاري تسوية حساب النزيل...',allowOutsideClick:false,didOpen:()=>Swal.showLoading()});
            const r=await fetch('../api/admin/process_reservation.php',{
                method:'POST',
                headers:{'Content-Type':'application/json'},
                body:JSON.stringify({reservation_id:resId,action:'check_out',payment_method:choice.value.payment_method||''})
            });

            const raw=await r.text();let d;
            try{d=JSON.parse(raw);}catch(e){
                const x=raw.indexOf('{'),y=raw.lastIndexOf('}');
                if(x>=0&&y>x)d=JSON.parse(raw.slice(x,y+1));else throw new Error('الخادم لم يرجع JSON صحيحاً.');
            }
            if(d.status!=='success')throw new Error(d.message||'تعذر إتمام المغادرة.');

            await Swal.fire({icon:'success',title:'تمت المغادرة بنجاح',html:`تمت تسوية حساب النزيل بمبلغ <strong>${grandDue.toFixed(2)} ريال</strong> وتم إنهاء المغادرة.`,confirmButtonText:'حسنًا'});
            fetchReservations();
        }catch(e){
            Swal.fire('تعذر إتمام المغادرة',e.message||'حدث خطأ غير متوقع.','error');
        }
    }

    async function openEarlyDeparture(resId){
        try{
            Swal.fire({title:'جاري حساب تسوية الخروج المبكر...',allowOutsideClick:false,didOpen:()=>Swal.showLoading()});

            const response=await fetch('../api/admin/process_reservation.php',{
                method:'POST',
                headers:{'Content-Type':'application/json'},
                body:JSON.stringify({
                    reservation_id:resId,
                    action:'early_departure_summary',
                    actual_check_out:(new Date()).toISOString().slice(0,10)
                })
            });
            const raw=await response.text();
            let d;
            try{d=JSON.parse(raw);}catch(e){
                const a=raw.indexOf('{'),b=raw.lastIndexOf('}');
                if(a>=0&&b>a)d=JSON.parse(raw.slice(a,b+1));
                else throw new Error('الخادم لم يرجع JSON صحيحاً.');
            }
            Swal.close();
            if(d.status!=='success')throw new Error(d.message||'تعذر حساب الخروج المبكر.');

            const x=d.early_departure||{};
            const refund=Number(x.refund_amount||0);
            const collectBooking=Number(x.collect_amount||0);
            const posDue=Number(x.pos_due||0);
            const collectRequired=Math.max(collectBooking,posDue);

            let resultBox='';
            if(refund>0.01){
                resultBox=`<div style="background:#ecfdf5;border:1px solid #86efac;padding:11px;border-radius:8px;color:#166534;margin-top:10px;">
                    <strong>💰 استرداد للنزيل: ${refund.toFixed(2)} ريال</strong>
                    <div style="font-size:12px;margin-top:4px;">${escapeHtml(x.reason||'')}</div>
                </div>`;
            }else if(collectBooking>0.01){
                resultBox=`<div style="background:#fff7ed;border:1px solid #fdba74;padding:11px;border-radius:8px;color:#92400e;margin-top:10px;">
                    <strong>💳 مبلغ إضافي للحجز: ${collectBooking.toFixed(2)} ريال</strong>
                    <div style="font-size:12px;margin-top:4px;">${escapeHtml(x.reason||'')}</div>
                </div>`;
            }else{
                resultBox=`<div style="background:#f8fafc;border:1px solid #cbd5e1;padding:11px;border-radius:8px;margin-top:10px;">
                    <strong>${escapeHtml(x.reason||'لا يوجد استرداد')}</strong>
                </div>`;
            }

            const posBox=posDue>0.01
                ? `<div style="background:#fff7ed;border:1px solid #fdba74;border-radius:8px;padding:10px;margin-top:9px;color:#92400e;">
                    <strong>🧾 مبيعات POS مستحقة: ${posDue.toFixed(2)} ريال</strong>
                    <div style="font-size:12px;margin-top:4px;">يجب تحصيلها قبل إتمام المغادرة.</div>
                   </div>` : '';

            let methods='';
            if(refund>0.01){
                methods += `<div style="text-align:right;margin-top:11px;"><strong>طريقة الاسترداد:</strong>
                    <label style="display:block;margin:8px 0;"><input type="radio" name="early_refund_method" value="cash"> 💵 كاش</label>
                    <label style="display:block;margin:8px 0;"><input type="radio" name="early_refund_method" value="network"> 💳 شبكة</label>
                    <label style="display:block;margin:8px 0;"><input type="radio" name="early_refund_method" value="bank_transfer"> 🏦 تحويل بنكي</label>
                </div>`;
            }
            if(collectRequired>0.01){
                methods += `<div style="text-align:right;margin-top:11px;"><strong>طريقة التحصيل للمبلغ المستحق:</strong>
                    <label style="display:block;margin:8px 0;"><input type="radio" name="early_collect_method" value="cash"> 💵 كاش</label>
                    <label style="display:block;margin:8px 0;"><input type="radio" name="early_collect_method" value="network"> 💳 شبكة</label>
                    <label style="display:block;margin:8px 0;"><input type="radio" name="early_collect_method" value="bank_transfer"> 🏦 تحويل بنكي</label>
                </div>`;
            }

            const choice=await Swal.fire({
                title:'مغادرة مبكرة 🏃',
                html:`<div style="text-align:right;">
                    <div><strong>الحجز #BKG-${resId}</strong></div>
                    <div style="margin-top:8px;">الخروج الأصلي: <strong>${escapeHtml(x.original_checkout||'')}</strong></div>
                    <div>الخروج الفعلي: <strong>${escapeHtml(x.actual_checkout||'')}</strong></div>
                    <div style="margin-top:8px;">الليالي المستخدمة: <strong>${Number(x.used_nights||0)}</strong></div>
                    <div>الليالي غير المستخدمة: <strong>${Number(x.unused_nights||0)}</strong></div>
                    <div>قيمة الليالي غير المستخدمة: <strong>${Number(x.unused_value||0).toFixed(2)} ريال</strong></div>
                    ${Number(x.penalty||0)>0.01?`<div>غرامة الخروج المبكر: <strong>${Number(x.penalty).toFixed(2)} ريال</strong></div>`:''}
                    ${resultBox}
                    ${posBox}
                    ${methods}
                    <p style="color:#64748b;font-size:11px;margin-top:10px;">الاسترداد يسجل كعملية مستقلة. ومبيعات POS تبقى مرتبطة بالنزيل وتُحصّل بشكل مستقل.</p>
                </div>`,
                showCancelButton:true,
                confirmButtonColor:'#0f766e',
                cancelButtonColor:'#94a3b8',
                confirmButtonText:refund>0.01?'استرداد وإتمام المغادرة':(collectRequired>0.01?'تحصيل وإتمام المغادرة':'إتمام المغادرة'),
                cancelButtonText:'تراجع',
                preConfirm:()=>{
                    let refundMethod='',paymentMethod='';
                    if(refund>0.01){
                        const m=document.querySelector('input[name="early_refund_method"]:checked');
                        if(!m){Swal.showValidationMessage('اختر طريقة الاسترداد.');return false;}
                        refundMethod=m.value;
                    }
                    if(collectRequired>0.01){
                        const m=document.querySelector('input[name="early_collect_method"]:checked');
                        if(!m){Swal.showValidationMessage('اختر طريقة التحصيل.');return false;}
                        paymentMethod=m.value;
                    }
                    return {refund_method:refundMethod,payment_method:paymentMethod};
                }
            });

            if(!choice.isConfirmed)return;

            Swal.fire({title:'جاري تنفيذ المغادرة المبكرة...',allowOutsideClick:false,didOpen:()=>Swal.showLoading()});
            const rr=await fetch('../api/admin/process_reservation.php',{
                method:'POST',
                headers:{'Content-Type':'application/json'},
                body:JSON.stringify({
                    reservation_id:resId,
                    action:'early_check_out',
                    actual_check_out:x.actual_checkout,
                    refund_method:choice.value.refund_method,
                    payment_method:choice.value.payment_method
                })
            });
            const raw2=await rr.text();
            let result;
            try{result=JSON.parse(raw2);}catch(e){
                const a=raw2.indexOf('{'),b=raw2.lastIndexOf('}');
                if(a>=0&&b>a)result=JSON.parse(raw2.slice(a,b+1));
                else throw new Error('الخادم لم يرجع JSON صحيحاً.');
            }
            if(result.status!=='success')throw new Error(result.message||'تعذر إتمام المغادرة المبكرة.');

            await Swal.fire({
                icon:'success',
                title:'تمت المغادرة المبكرة',
                html:escapeHtml(result.message||'تمت التسوية بنجاح.'),
                confirmButtonText:'حسنًا'
            });
            fetchReservations();
        }catch(e){
            Swal.fire('تعذر إتمام المغادرة المبكرة',e.message||'حدث خطأ غير متوقع.','error');
        }
    }

    async function earlyCheckOut(resId){return openCheckoutAccount(resId,true);}

    async function confirmAndPay(resId) {
        const { value: selectedMethod } = await Swal.fire({
            title: 'تأكيد الحجز والدفع 💰',
            html: `
                <p style="text-align:right; font-size:15px;">يرجى تحديد طريقة الدفع للحجز رقم <strong>#BKG-${resId}</strong>:</p>
                <div style="text-align: right; margin-top: 15px; background: #f8fafc; padding: 15px; border-radius: 6px; border: 1px solid #e2e8f0;">
                    <label style="display: flex; align-items: center; gap: 10px; margin-bottom: 15px; cursor: pointer; font-weight: bold; color: #1e40af;">
                        <input type="radio" name="payment_method" value="bank_transfer" style="width: 20px; height: 20px;">
                        🏦 تحويل بنكي مسبق
                    </label>
                    <hr style="border: 0; border-top: 1px dashed #cbd5e1; margin: 15px 0;">
                    <span style="color: #64748b; font-size: 13px; margin-bottom: 10px; display: block;">الدفع عند الوصول:</span>
                    <label style="display: flex; align-items: center; gap: 10px; margin-bottom: 10px; cursor: pointer; font-weight: bold; color: #065f46;">
                        <input type="radio" name="payment_method" value="cash" style="width: 20px; height: 20px;">
                        💵 كاش (نقدي)
                    </label>
                    <label style="display: flex; align-items: center; gap: 10px; cursor: pointer; font-weight: bold; color: #b45309;">
                        <input type="radio" name="payment_method" value="network" style="width: 20px; height: 20px;">
                        💳 شبكة (بطاقة بنكية)
                    </label>
                </div>
            `,
            focusConfirm: false,
            showCancelButton: true,
            confirmButtonColor: '#059669',
            cancelButtonColor: '#94a3b8',
            confirmButtonText: 'تأكيد الحجز وحفظ الدفع',
            cancelButtonText: 'إلغاء',
            preConfirm: () => {
                const method = document.querySelector('input[name="payment_method"]:checked');
                if (!method) { Swal.showValidationMessage('الرجاء اختيار طريقة الدفع لإتمام العملية!'); return false; }
                return method.value;
            }
        });

        if (selectedMethod) {
            Swal.fire({ title: 'جاري الحفظ...', allowOutsideClick: false, didOpen: () => { Swal.showLoading(); }});
            try {
                const response = await fetch('../api/admin/process_reservation.php', {
                    method: 'POST', headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ reservation_id: resId, action: 'confirm_and_pay', payment_method: selectedMethod })
                });
                const data = await response.json();
                if(data.status === 'success') {
                    Swal.fire('تم بنجاح!', 'تم تأكيد الحجز وتسجيل الدفع بالطريقة المحددة.', 'success');
                    fetchReservations();
                } else { Swal.fire('خطأ!', data.message || 'حدث خطأ ما.', 'error'); }
            } catch(e) { Swal.fire('خطأ!', 'خطأ في الاتصال بالخادم.', 'error'); }
        }
    }

    async function refundAndCancel(resId) {
        const { value: formValues } = await Swal.fire({
            title: 'استرداد الأموال وإلغاء الحجز؟',
            html: `
                <p style="text-align:right; font-size:14px; margin-bottom:10px;">سيتم إلغاء الحجز رقم <strong>BKG-${resId}</strong> وتحرير الغرفة نهائياً.</p>
                <div style="text-align:right; margin:12px 0 14px; background:#fff7ed; padding:13px 14px; border-radius:8px; border:1px solid #fed7aa;">
                    <label for="cancel_reason_${resId}" style="display:block; font-weight:900; color:#9a3412; font-size:13px; margin-bottom:7px;">سبب الإلغاء <span style="color:#dc2626;">*</span></label>
                    <textarea id="cancel_reason_${resId}" rows=4 maxlength=500 placeholder="اكتب سبب الإلغاء بالتفصيل..." style="width:100%; resize:vertical; padding:10px 11px; border:1px solid #fdba74; border-radius:7px; outline:none; font-family:inherit; font-size:13px; box-sizing:border-box;"></textarea>
                    <div style="margin-top:5px; color:#9a3412; font-size:11px;">سيتم حفظ السبب مع عملية الإلغاء للمراجعة والتحليل لاحقًا.</div>
                </div>
                <p style="text-align:right; font-size:14px; font-weight:bold; color:#d97706; margin-top:15px;">كيف تم استرداد المبلغ للعميل؟</p>
                
                <div style="text-align: right; margin-top: 10px; background: #f8fafc; padding: 15px; border-radius: 6px; border: 1px solid #e2e8f0;">
                    <label style="display: flex; align-items: center; gap: 10px; margin-bottom: 15px; cursor: pointer; font-weight: bold; color: #065f46;">
                        <input type="radio" name="refund_method" value="cash" style="width: 20px; height: 20px;" checked>
                        💵 كاش (نقدي من الصندوق)
                    </label>
                    <label style="display: flex; align-items: center; gap: 10px; margin-bottom: 15px; cursor: pointer; font-weight: bold; color: #b45309;">
                        <input type="radio" name="refund_method" value="network" style="width: 20px; height: 20px;">
                        💳 شبكة (عكس عملية)
                    </label>
                    <label style="display: flex; align-items: center; gap: 10px; cursor: pointer; font-weight: bold; color: #1e40af;">
                        <input type="radio" name="refund_method" value="bank_transfer" style="width: 20px; height: 20px;">
                        🏦 تحويل بنكي
                    </label>
                </div>
            `,
            icon: 'warning',
            focusConfirm: false,
            showCancelButton: true,
            confirmButtonColor: '#d97706',
            cancelButtonColor: '#94a3b8',
            confirmButtonText: 'تأكيد الاسترداد والإلغاء',
            cancelButtonText: 'تراجع',
            preConfirm: () => {
                const method = document.querySelector('input[name="refund_method"]:checked');
                const reasonEl = document.getElementById(`cancel_reason_${resId}`);
                const reason = (reasonEl?.value || '').trim();
                if (reason.length < 3) {
                    Swal.showValidationMessage('الرجاء كتابة سبب الإلغاء أولاً.');
                    reasonEl?.focus();
                    return false;
                }
                if (!method) {
                    Swal.showValidationMessage('الرجاء اختيار طريقة الاسترداد!');
                    return false;
                }
                return { method: method.value, reason };
            }
        });

        if (formValues) {
            Swal.fire({ title: 'جاري تنفيذ الاسترداد...', allowOutsideClick: false, didOpen: () => { Swal.showLoading(); }});
            try {
                const response = await fetch('../api/admin/process_reservation.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ 
                        reservation_id: resId, 
                        action: 'refund_and_cancel', 
                        refund_method: formValues.method,
                        cancellation_reason: formValues.reason
                    })
                });
                const data = await response.json();
                if(data.status === 'success') {
                    Swal.fire('تم الاسترداد والإلغاء!', 'تمت العملية بنجاح وتسجيل الاسترداد في المالية.', 'success');
                    fetchReservations();
                } else {
                    Swal.fire('خطأ!', data.message || 'حدث خطأ ما.', 'error');
                }
            } catch(e) {
                Swal.fire('خطأ!', 'خطأ في الاتصال بالخادم.', 'error');
            }
        }
    }

    async function hideReservation(resId) {
        const result = await Swal.fire({
            title: 'إخفاء الحجز الملغي؟',
            text: `سيتم إخفاء الحجز BKG-${resId} من قائمة الحجوزات فقط، ولن يتم حذفه من قاعدة البيانات.`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#64748b',
            cancelButtonColor: '#94a3b8',
            confirmButtonText: 'نعم، إخفاء',
            cancelButtonText: 'تراجع'
        });

        if (!result.isConfirmed) return;

        try {
            const response = await fetch('../api/admin/process_reservation.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ reservation_id: resId, action: 'hide_reservation' })
            });
            const data = await response.json();
            if (data.status === 'success') {
                await Swal.fire('تم الإخفاء', 'تم إخفاء الحجز الملغي من قائمة الحجوزات دون حذفه.', 'success');
                fetchReservations();
            } else {
                Swal.fire('تعذر الإخفاء', data.message || 'حدث خطأ ما.', 'error');
            }
        } catch (e) {
            Swal.fire('خطأ', 'تعذر الاتصال بالخادم.', 'error');
        }
    }

    function toggleAllCheckboxes(source) {
        const checkboxes = document.querySelectorAll('.checkbox-item');
        checkboxes.forEach(cb => cb.checked = source.checked);
    }

    async function executeBulkAction() {
        const selected = Array.from(document.querySelectorAll('.checkbox-item:checked')).map(cb => cb.value);
        const action = document.getElementById('bulk-action-select').value;

        if (selected.length === 0) {
            Swal.fire('تنبيه', 'يرجى تحديد حجز واحد على الأقل من القائمة.', 'warning');
            return;
        }
        if (action === '') {
            Swal.fire('تنبيه', 'يرجى اختيار الإجراء من القائمة المنسدلة.', 'warning');
            return;
        }

        // الإخفاء يطبق فقط على الحجوزات الملغاة؛ لا نرسل حجوزات نشطة إلى الخادم لهذا الإجراء.
        if (action === 'hide_reservation') {
            const selectedSet = new Set(selected.map(Number));
            const cancelledOnly = allReservations
                .filter(res => selectedSet.has(Number(res.id)) && res.status === 'cancelled')
                .map(res => String(res.id));
            if (cancelledOnly.length === 0) {
                Swal.fire('تنبيه', 'الإخفاء متاح للحجوزات الملغاة فقط.', 'warning');
                return;
            }
            selected.splice(0, selected.length, ...cancelledOnly);
        }

        let actionText = action === 'confirm_and_pay' ? 'تأكيد ودفع' : (action === 'refund_and_cancel' ? 'استرداد وإلغاء' : 'إخفاء الحجوزات الملغاة');

        Swal.fire({
            title: 'هل أنت متأكد؟',
            text: `سيتم تنفيذ إجراء (${actionText}) على عدد (${selected.length}) حجوزات دفعة واحدة.`,
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#4f46e5',
            cancelButtonColor: '#94a3b8',
            confirmButtonText: 'نعم، نفذ الإجراء',
            cancelButtonText: 'تراجع'
        }).then(async (result) => {
            if (result.isConfirmed) {
                Swal.fire({ title: 'جاري التنفيذ...', allowOutsideClick: false, didOpen: () => { Swal.showLoading(); }});
                
                let successCount = 0;
                let errorCount = 0;

                for (let resId of selected) {
                    try {
                        const response = await fetch('../api/admin/process_reservation.php', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({ reservation_id: resId, action: action })
                        });
                        const data = await response.json();
                        if (data.status === 'success') successCount++;
                        else errorCount++;
                    } catch (e) {
                        errorCount++;
                    }
                }

                Swal.fire(
                    'اكتملت العملية',
                    `نجح: ${successCount} | فشل: ${errorCount}`,
                    errorCount === 0 ? 'success' : 'warning'
                );
                
                fetchReservations();
            }
        });
    }

    function buildCalendarFloorMenu() {
        const menu = document.getElementById('cal-floor-menu');
        const floors = [...new Set(allRooms.map(r => r.floor))].sort((a,b) => a - b);
        let html = `<button class="floor-btn active" onclick="filterCalendarByFloor('all', this)">الكل</button>`;
        floors.forEach(floor => { html += `<button class="floor-btn" onclick="filterCalendarByFloor('${floor}', this)">الطابق ${floor}</button>`; });
        menu.innerHTML = html;
    }

    function filterCalendarByFloor(floor, btnElement) {
        currentCalFloor = floor;
        document.querySelectorAll('.floor-btn').forEach(btn => btn.classList.remove('active'));
        btnElement.classList.add('active');
        generateCalendar();
    }

    function generateCalendar() {
        const container = document.getElementById('calendar-wrapper');
        const monthOffset = parseInt(document.getElementById('cal-month').value);
        let targetDate = new Date();
        targetDate.setMonth(targetDate.getMonth() + monthOffset);
        
        const year = targetDate.getFullYear();
        const month = targetDate.getMonth();
        const daysInMonth = new Date(year, month + 1, 0).getDate();

        let filteredRooms = currentCalFloor === 'all' ? allRooms : allRooms.filter(r => r.floor == currentCalFloor);
        if(filteredRooms.length === 0) {
            container.innerHTML = '<p style="padding:20px; text-align:center;">لا توجد غرف لعرضها في هذا الطابق.</p>';
            return;
        }

        let html = '<div class="cal-grid"><div class="cal-header-row"><div class="cal-cell">الغرفة / اليوم</div>';
        for(let i = 1; i <= daysInMonth; i++) html += `<div class="cal-cell">${i}</div>`;
        html += '</div>';

        FilesRooms: filteredRooms.forEach(room => {
            html += `<div class="cal-room-row"><div class="cal-cell cal-room-name">${escapeHtml(pmsReservationTranslate('غرفة '))}${escapeHtml(room.room_number)}</div>`;
            for(let day = 1; day <= daysInMonth; day++) {
                const d = new Date(year, month, day);
                const cellDateString = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
                
                const booking = allReservations.find(r => r.room_number == room.room_number && r.check_in <= cellDateString && r.check_out > cellDateString && r.status !== 'cancelled');
                
                if(booking) {
                    html += `<div class="cal-cell day-booked" title="العميل: ${booking.guest_name} | الحالة: ${booking.status}">م</div>`;
                } else {
                    html += `<div class="cal-cell day-free">✓</div>`;
                }
            }
            html += '</div>';
        });

        html += '</div>';
        container.innerHTML = html;
    }

    function downloadPDF(id) {
        const element = document.getElementById('invoice-content-' + id);
        html2pdf().from(element).set({
            margin: 10, filename: 'Invoice_BKG_' + id + '.pdf', html2canvas: { scale: 2 }, jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
        }).save();
    }
</script>
</body>
</html>