<?php
// app/layout.php
if (session_status() === PHP_SESSION_NONE) session_start();
require_once __DIR__ . '/helpers.php';

function render_layout(string $title, string $breadcrumb, callable $bodyFn): void {
  $appName = "Arqaamy ERP";
  $sub = "من أي مكان";
  $userName = $_SESSION['user_name'] ?? '';
  $companyName = $_SESSION['company_name'] ?? '';
  $flashToasts = flash_get_all();
  require_once __DIR__ . '/db.php';
  require_once __DIR__ . '/db_tools.php';
  $pdoLayout = db();
  ensure_company_profile_columns($pdoLayout);
  ensure_user_profile_columns($pdoLayout);
  $companyId = (int)($_SESSION['company_id'] ?? 0);
  $userId = (int)($_SESSION['user_id'] ?? 0);
  $companyStmt = $pdoLayout->prepare("SELECT name, logo_path FROM companies WHERE id=? LIMIT 1");
  $companyStmt->execute([$companyId]);
  $layoutCompany = $companyStmt->fetch(PDO::FETCH_ASSOC) ?: [];
  $userStmt = $pdoLayout->prepare("SELECT name, email, avatar_path, theme_mode FROM users WHERE id=? AND company_id=? LIMIT 1");
  $userStmt->execute([$userId, $companyId]);
  $layoutUser = $userStmt->fetch(PDO::FETCH_ASSOC) ?: [];
  $companyLogo = trim((string)($layoutCompany['logo_path'] ?? '')) ?: url('/assets/img/favicon.png');
  $userAvatar = trim((string)($layoutUser['avatar_path'] ?? '')) ?: $companyLogo;
  $userEmail = (string)($layoutUser['email'] ?? '');
  $themeMode = (string)($_SESSION['theme_mode'] ?? ($layoutUser['theme_mode'] ?? 'light'));
  if ($themeMode !== 'dark') { $themeMode = 'light'; }
  $_SESSION['theme_mode'] = $themeMode;

  // Sidebar active state
  $uriPath = parse_url($_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH) ?: '';
  $uriPath = rtrim($uriPath, '/');
  if ($uriPath === '') $uriPath = '/index.php';

  $is = function(string $needle) use ($uriPath): bool {
    return str_starts_with($uriPath, $needle);
  };

  $secAccounts = $is('/accounts') || $is('/cash') || $is('/journal') || $path === '/hr/advances.php';
  $secHR       = $is('/hr') && $path !== '/hr/advances.php';
  $secReports  = $is('/reports');
  $secUsers    = $is('/users/index.php') || $is('/users/create.php');
  $secFleet    = $is('/fleet');
    $secCustomers = $is('/tourism/customers.php') || $is('/tourism/services.php') || $is('/tourism/customer_ledger.php');
  $secHotels   = $is('/hotel');
  $secSettings = $is('/settings/database.php') || $is('/settings/backup_logs.php') || $is('/settings/audit_logs.php');

  $smartNav = [
    ['title'=>'لوحة التحكم','url'=>url('/index.php'),'keywords'=>['الرئيسية','داشبورد','dashboard','home']],
    ['title'=>'الشركة','url'=>url('/settings/company.php'),'keywords'=>['الشركة','بيانات الشركة','company']],
    ['title'=>'الملف التعريفي للمستخدم','url'=>url('/users/profile.php'),'keywords'=>['المستخدم','الملف التعريفي','البروفايل','profile']],
    ['title'=>'إدارة المستخدمين','url'=>url('/users/index.php'),'keywords'=>['المستخدمين','users','اضافة مستخدم','صلاحيات']],
    ['title'=>'شجرة الحسابات','url'=>url('/accounts/index.php'),'keywords'=>['الحسابات','شجرة الحسابات','دليل الحسابات']],
    ['title'=>'إنشاء حساب','url'=>url('/accounts/create.php'),'keywords'=>['إضافة حساب','فتح حساب','حساب جديد']],
    ['title'=>'الوارد والمنصرف','url'=>url('/cash/index.php'),'keywords'=>['تسجيل','الوارد','المنصرف','قبض','صرف','cash']],
    ['title'=>'إضافة حركة وارد/منصرف','url'=>url('/cash/create.php'),'keywords'=>['تسجيل وارد','تسجيل منصرف','حركة مالية']],
    ['title'=>'القيود اليومية والترحيل','url'=>url('/journal/daily_posting.php'),'keywords'=>['القيود','الترحيل','قيود يومية']],
    ['title'=>'دفتر اليومية','url'=>url('/journal/index.php'),'keywords'=>['دفتر اليومية','اليومية']],
    ['title'=>'الموظفون','url'=>url('/hr/employees.php'),'keywords'=>['الموظفين','الموظف','hr']],
    ['title'=>'العهد','url'=>url('/hr/advances.php'),'keywords'=>['العهد','عهدة','سلف']],
    ['title'=>'الحضور والانصراف','url'=>url('/hr/attendance.php'),'keywords'=>['الحضور','الانصراف','الدوام']],
    ['title'=>'الرواتب','url'=>url('/hr/payroll.php'),'keywords'=>['الرواتب','المرتب']],
    ['title'=>'سريال أوامر التشغيل','url'=>url('/fleet/order_serials.php'),'keywords'=>['سريال اوامر التشغيل','اوامر التشغيل','fleet']],
    ['title'=>'تسجيل المركبات','url'=>url('/fleet/vehicles.php'),'keywords'=>['تسجيل المركبات','المركبات','السيارات','اضافة سيارة','إضافة سيارة','vehicles']],
    ['title'=>'أنواع السيارات','url'=>url('/fleet/vehicle_types.php'),'keywords'=>['انواع السيارات','أنواع السيارات','ماركات السيارات','موديلات السيارات','فئات السيارات']],
    ['title'=>'تأجير السيارات','url'=>url('/fleet/rentals.php'),'keywords'=>['تاجير السيارات','تأجير السيارات','عقود الايجار','rentals']],
    ['title'=>'حسابات السيارات','url'=>url('/accounts/vehicle_accounts.php'),'keywords'=>['حسابات السيارات','تحصيلات السيارات','تحصيل الليموزين','تحصيل التأجير']],
    ['title'=>'الفنادق','url'=>url('/hotel/hotels.php'),'keywords'=>['الفنادق','فندق']],
    ['title'=>'الغرف','url'=>url('/hotel/rooms.php'),'keywords'=>['الغرف','غرفة']],
    ['title'=>'طلبات الحجز','url'=>url('/hotel/bookings.php'),'keywords'=>['الحجز','حجوزات','طلب حجز']],
    ['title'=>'تحصيلات الفنادق','url'=>url('/hotel/receipts.php'),'keywords'=>['تحصيلات','سداد الحجز']],
    ['title'=>'تقارير الفنادق','url'=>url('/hotel/reports.php'),'keywords'=>['تقارير الفنادق','تقارير الحجز']],
    ['title'=>'العملاء','url'=>url('/tourism/customers.php'),'keywords'=>['العملاء','عميل']],
    ['title'=>'الخدمات','url'=>url('/tourism/services.php'),'keywords'=>['الخدمات','الخدمة']],
    ['title'=>'الحجوزات السياحية','url'=>url('/tourism/bookings.php'),'keywords'=>['الحجوزات السياحية','حجز']],
    ['title'=>'الفواتير','url'=>url('/tourism/invoices.php'),'keywords'=>['الفواتير','فاتورة']],
    ['title'=>'إنشاء فاتورة','url'=>url('/tourism/invoice_create.php'),'keywords'=>['إنشاء فاتورة','فاتورة جديدة']],
    ['title'=>'إنشاء دفعة','url'=>url('/tourism/payment_create.php'),'keywords'=>['دفعة','سداد','تحصيل دفعة']],
    ['title'=>'ميزان المراجعة','url'=>url('/reports/trial_balance.php'),'keywords'=>['ميزان المراجعة']],
    ['title'=>'الأستاذ العام','url'=>url('/reports/general_ledger.php'),'keywords'=>['الأستاذ العام','دفتر الأستاذ']],
    ['title'=>'قائمة الدخل','url'=>url('/reports/pl.php'),'keywords'=>['قائمة الدخل','الأرباح والخسائر']],
    ['title'=>'الميزانية العمومية','url'=>url('/reports/balance_sheet.php'),'keywords'=>['الميزانية العمومية']],
    ['title'=>'التدفق النقدي','url'=>url('/reports/cash_flow.php'),'keywords'=>['التدفق النقدي']],
    ['title'=>'إدارة البيانات','url'=>url('/settings/database.php'),'keywords'=>['إدارة البيانات','النسخ الاحتياطي','استعادة النسخ']],
    ['title'=>'سجل العمليات','url'=>url('/settings/audit_logs.php'),'keywords'=>['سجل العمليات','audit']],
    ['title'=>'سجل النسخ الاحتياطي','url'=>url('/settings/backup_logs.php'),'keywords'=>['سجل النسخ','backup logs']],
  ];


  $linkClass = function(string $href) use ($uriPath): string {
    $h = rtrim($href,'/');
    if ($h==='') $h='/';
    $active = ($uriPath === $h) || ($h !== '/' && preg_match('#^'.preg_quote($h,'#').'(/|$)#',$uriPath));
    return $active ? 'slink active' : 'slink';
  };

  $favoritesEnabled = false;
  $favoriteRows = [];
  $favoriteMap = [];
  try {
    $favTableStmt = $pdoLayout->query("SELECT 1 FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = 'user_favorites' LIMIT 1");
    $favoritesEnabled = (bool)($favTableStmt ? $favTableStmt->fetchColumn() : false);
    if ($favoritesEnabled && $userId > 0) {
      $favoriteStmt = $pdoLayout->prepare("SELECT page_url, page_title FROM user_favorites WHERE user_id=? ORDER BY id DESC");
      $favoriteStmt->execute([$userId]);
      $favoriteRows = $favoriteStmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
      foreach ($favoriteRows as $favoriteRow) {
        $favKey = rtrim(parse_url((string)($favoriteRow['page_url'] ?? ''), PHP_URL_PATH) ?: (string)($favoriteRow['page_url'] ?? ''), '/');
        if ($favKey !== '') {
          $favoriteMap[$favKey] = (string)($favoriteRow['page_title'] ?? '');
        }
      }
    }
  } catch (Throwable $e) {
    $favoritesEnabled = false;
    $favoriteRows = [];
    $favoriteMap = [];
  }

  ?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<meta name="viewport" id="appViewportMeta" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title><?= h($title) ?> - <?= h($appName) ?></title>
<link rel="icon" type="image/png" href="<?= h(url('/assets/img/favicon.png')) ?>">
<link rel="apple-touch-icon" href="<?= h(url('/assets/img/favicon.png')) ?>">

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.rtl.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">

<!-- Bootstrap Select (selectpicker) -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.14.0-beta3/dist/css/bootstrap-select.min.css" rel="stylesheet">

<style>
:root{
  --sidebar-w: 300px;
  --sidebar-collapsed: 92px;
  --brand-h: 70px;

  --main-color:#0f172a;
  --text-light:#e2e8f0;
  --text-muted: rgba(226,232,240,.65);

  --logo-box: 44px;
  --logo-box-collapsed: 54px;
  --logo-font: 22px;
  --logo-font-collapsed: 26px;
  --logo-bg: rgba(255,255,255,.10);
}
body{ background:#f6f7fb; color:#0f172a; transition:background-color .2s ease,color .2s ease; }
.app{ min-height:100vh; display:flex; }

.overlay{ position:fixed; inset:0; background:rgba(2,6,23,.45); display:none; z-index:9998; }
.overlay.show{ display:block; }

.sidebar{
  width:var(--sidebar-w);
  background:var(--main-color);
  color:var(--text-light);
  height:100vh;
  position:sticky;
  top:0;
  overflow-y:auto;
  overflow-x:hidden;
  transition: width .2s ease, transform .25s ease;
  flex:0 0 auto;
  z-index:9999;
}
.sidebar .brand{
  position:sticky;
  top:0;
  z-index:4;
  background:var(--main-color);
}
.sidebar .brand{
  height:var(--brand-h);
  padding:0 16px;
  border-bottom:1px solid rgba(226,232,240,.08);
  display:flex;
  align-items:center;
  gap:12px;
}
.brand .logo-box{
  width: var(--logo-box);
  height: var(--logo-box);
  border-radius: 14px;
  display:grid;
  place-items:center;
  background: var(--logo-bg);
  flex: 0 0 auto;
}
.brand .logo-box img{width:100%;height:100%;object-fit:cover;border-radius:inherit;display:block}
.brand .brand-name-wrap{ min-width:0; }
.brand .brand-text{
  font-weight: 800;
  letter-spacing: .2px;
  font-size: 16px;
  line-height: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.brand .brand-sub{
  font-size: 12px;
  color: var(--text-muted);
  margin-top: 2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.sidebar-search-wrap{
  position:sticky;
  top:var(--brand-h);
  z-index:4;
  background:var(--main-color);
  padding:10px 14px 12px;
  border-bottom:1px solid rgba(226,232,240,.08);
}
.sidebar-search{
  position:relative;
}
.sidebar-search-input{
  width:100%;
  height:42px;
  border-radius:12px;
  border:1px solid rgba(226,232,240,.18);
  background:rgba(255,255,255,.08);
  color:var(--text-light);
  padding:0 42px 0 14px;
  outline:none;
}
.sidebar-search-input::placeholder{ color:rgba(226,232,240,.6); }
.sidebar-search-icon{
  position:absolute;
  right:14px;
  top:50%;
  transform:translateY(-50%);
  color:rgba(226,232,240,.65);
  pointer-events:none;
}

.slink{
  color:var(--text-light)!important;
  text-decoration:none;
  display:flex;
  align-items:center;
  gap:10px;
  padding:10px 14px;
  border-radius:12px;
}
.slink:hover{ background:rgba(148,163,184,.15); }
.slink.active{ background:rgba(148,163,184,.22); border:1px solid rgba(226,232,240,.18); }
.submenu .slink.active{ background:rgba(148,163,184,.18); }
.sicon{ width:34px; text-align:center; flex:0 0 auto; }
.slabel{ flex:1; min-width:0; }

.nav-title{ padding:14px 18px 6px; font-size:12px; opacity:.7; }

.accordion.sidebar-acc{
  --bs-accordion-bg: transparent;
  --bs-accordion-border-color: transparent;
  --bs-accordion-btn-bg: transparent;
  --bs-accordion-active-bg: transparent;
  --bs-accordion-btn-focus-box-shadow: none;
  --bs-accordion-btn-color: var(--text-light);
  --bs-accordion-active-color: #fff;
}
.accordion.sidebar-acc .accordion-item{ background:transparent; border:0; }
.accordion-button{ padding:10px 14px; border-radius:12px; background: transparent; }
.accordion-button:hover{ background:rgba(148,163,184,.15); }
.accordion-button::after{ filter:invert(1); opacity:.85; }
.accordion-body{ padding: 6px 8px; }

.submenu{ display:grid; gap:6px; }
.submenu .slink{ background:rgba(148,163,184,.08); font-size:13px; padding:8px 12px; }
.submenu .sicon{ width:28px; }
.sidebar-link-row{display:flex;align-items:center;gap:6px;}
.sidebar-link-row .slink{flex:1;min-width:0;}
.sidebar-fav-btn{width:30px;height:30px;border:0;border-radius:10px;background:transparent;color:rgba(226,232,240,.58);display:inline-flex;align-items:center;justify-content:center;flex:0 0 auto;transition:.15s ease;}
.sidebar-fav-btn:hover{background:rgba(148,163,184,.15);color:#fbbf24;}
.sidebar-fav-btn.active{color:#fbbf24;background:rgba(251,191,36,.12);}
.sidebar-filter-hidden{display:none!important;}

.content{ flex:1; min-width:0; padding-top:calc(var(--brand-h) + 20px); padding-inline:18px; padding-bottom:18px; }

.topbar{
  position:fixed;
  top:0;
  right:var(--sidebar-w);
  left:0;
  height:var(--brand-h);
  background:var(--main-color);
  border-bottom:1px solid rgba(226,232,240,.08);
  display:flex;
  align-items:center;
  justify-content:space-between;
  padding:0 16px;
  z-index:9990;
}
.topbar .btn{ border-color:rgba(226,232,240,.25)!important; color:var(--text-light)!important; }
.topbar .btn:hover{ background:rgba(226,232,240,.15)!important; }
.topbar .input-group-text, .topbar .form-control{
  background:rgba(255,255,255,.08)!important;
  border-color:rgba(226,232,240,.2)!important;
  color:var(--text-light)!important;
}
.topbar .form-control::placeholder{ color:rgba(226,232,240,.6)!important; }

.cardx{ background:#fff; border-radius:16px; box-shadow:0 10px 30px rgba(2,6,23,.06); border:0; }

body.sidebar-collapsed .sidebar{ width:var(--sidebar-collapsed); }
body.sidebar-collapsed .slabel, body.sidebar-collapsed .nav-title, body.sidebar-collapsed .accordion-button::after{ display:none!important; }
body.sidebar-collapsed .slink, body.sidebar-collapsed .accordion-button{ justify-content:center; }
body.sidebar-collapsed .topbar{ right:var(--sidebar-collapsed); }
body.sidebar-collapsed .brand{ justify-content:center; gap:0; }
body.sidebar-collapsed .brand .brand-name-wrap{ display:none !important; }
body.sidebar-collapsed .brand .logo-box{ width: var(--logo-box-collapsed); height: var(--logo-box-collapsed); border-radius: 16px; }


.picker-with-action{display:flex;gap:10px;align-items:end}
.picker-with-action .bootstrap-select,.picker-with-action .form-select,.picker-with-action .form-control{flex:1;min-width:0}
.picker-action-btn{
  flex:0 0 auto;
  width:44px;
  height:44px;
  min-width:44px;
  padding:0;
  display:grid;
  place-items:center;
  border-radius:14px;
  border-color:#cbd5e1;
  color:#0f172a;
  background:#fff;
}
.picker-action-btn:hover{background:#f8fafc;border-color:#94a3b8;color:#0f172a}
.ajax-quick-form .form-label{font-weight:700;margin-bottom:.45rem}
.ajax-quick-feedback{display:none}

/* ERP form system */
.form-label{
  font-weight:800;
  margin-bottom:.45rem;
  font-size:.95rem;
  color:#0f172a;
}
.form-control,.form-select,textarea.form-control{
  min-height:44px;
  border-radius:14px;
  border:1px solid #d6deea;
  background:#fff;
  box-shadow:none!important;
  padding:.62rem .9rem;
  color:#0f172a;
}
textarea.form-control{min-height:94px}
.form-control::placeholder{color:#94a3b8}
.form-control:focus,.form-select:focus{
  border-color:#94a3b8;
  background:#fff;
  box-shadow:0 0 0 .18rem rgba(15,23,42,.08)!important;
}
.card.cardx{
  border:1px solid #e9eef5;
  border-radius:22px;
  box-shadow:0 16px 45px rgba(15,23,42,.05);
}
.cardx .text-secondary.small{color:#64748b!important}
.btn{
  border-radius:14px;
  font-weight:700;
}
.btn.btn-dark{
  background:#0f172a;
  border-color:#0f172a;
}
.btn.btn-dark:hover{background:#111c33;border-color:#111c33}

/* Bootstrap-select cleanup */
.bootstrap-select,
.bootstrap-select.form-select{
  width:100%!important;
  padding:0!important;
  border:0!important;
  background:transparent!important;
  min-height:auto!important;
  box-shadow:none!important;
}
.bootstrap-select > .dropdown-toggle,
.bootstrap-select > .dropdown-toggle.form-select{
  position:relative;
  min-height:44px;
  border:1px solid #d6deea!important;
  border-radius:14px!important;
  background:#fff!important;
  color:#0f172a!important;
  padding:.62rem 1rem .62rem 2.6rem!important;
  box-shadow:none!important;
  transition:border-color .18s ease, box-shadow .18s ease, background-color .18s ease;
  background-image:none!important;
}
.bootstrap-select > .dropdown-toggle:hover,
.bootstrap-select > .dropdown-toggle.form-select:hover{background:#fff!important;border-color:#c0cad8!important}
.bootstrap-select > .dropdown-toggle:focus,
.bootstrap-select > .dropdown-toggle.show,
.bootstrap-select > .dropdown-toggle.form-select:focus,
.bootstrap-select > .dropdown-toggle.form-select.show{
  border-color:#94a3b8!important;
  box-shadow:0 0 0 .18rem rgba(15,23,42,.08)!important;
  outline:0!important;
}
.bootstrap-select > .dropdown-toggle .filter-option{padding:0!important}
.bootstrap-select > .dropdown-toggle .filter-option-inner-inner{
  overflow:hidden;
  text-overflow:ellipsis;
  white-space:nowrap;
  font-size:.98rem;
  text-align:right;
  line-height:1.5;
}
.bootstrap-select .dropdown-toggle .caret,
.bootstrap-select .dropdown-toggle .bs-caret{display:none!important}
.bootstrap-select > .dropdown-toggle::after{
  content:'\F282';
  font-family:'bootstrap-icons';
  border:0!important;
  position:absolute;
  left:14px;
  top:50%;
  transform:translateY(-50%);
  font-size:15px;
  color:#475569;
  margin:0!important;
  line-height:1;
}
.bootstrap-select.show > .dropdown-toggle::after{content:'\F286'}
.bootstrap-select .dropdown-menu{
  border:1px solid #d6deea;
  border-radius:18px;
  box-shadow:0 20px 50px rgba(15,23,42,.14);
  padding:8px;
  margin-top:8px!important;
  overflow:hidden;
  background:#fff;
  max-width:100%;
}
.modal .bootstrap-select .dropdown-menu{
  z-index:1065;
}
.modal .bootstrap-select .dropdown-menu .inner{
  max-height:240px!important;
}
.bootstrap-select .bs-searchbox{padding:6px 6px 10px}
.bootstrap-select .bs-searchbox .form-control{
  min-height:40px;
  border-radius:12px;
  border:1px solid #d6deea;
  box-shadow:none!important;
}
.bootstrap-select .dropdown-menu .inner{max-height:280px!important}
.bootstrap-select .dropdown-menu li a,
.bootstrap-select .dropdown-menu .dropdown-item{
  border-radius:12px;
  padding:.72rem .85rem;
  color:#0f172a;
  font-size:.97rem;
}
.bootstrap-select .dropdown-menu li.selected a,
.bootstrap-select .dropdown-menu .dropdown-item.active,
.bootstrap-select .dropdown-menu .dropdown-item:active{
  background:#eaf0f7!important;
  color:#0f172a!important;
}
.bootstrap-select .dropdown-menu li a:hover,
.bootstrap-select .dropdown-menu .dropdown-item:hover{background:#f8fafc}
.bootstrap-select > select.bs-select-hidden,
.bootstrap-select > select.selectpicker{
  left:auto!important;
  width:.5px!important;
  height:.5px!important;
}
.form-check-input{width:1.15rem;height:1.15rem;border-color:#cbd5e1;box-shadow:none!important}
.form-check-input:checked{background-color:#0f172a;border-color:#0f172a}
.form-check-input:focus{box-shadow:0 0 0 .18rem rgba(15,23,42,.08)!important}
.modal{z-index:20010}
.modal-backdrop{z-index:20000}
.modal-dialog{margin:1rem auto}
.modal.modal-erp .modal-dialog{margin-top:max(1rem, calc(var(--brand-h) + 18px))}
.modal-content{border:0;border-radius:24px;box-shadow:0 25px 60px rgba(15,23,42,.18)}
.modal-header,.modal-footer{padding:1rem 1.25rem}
.modal-body{padding:1.1rem 1.25rem 1.25rem;max-height:calc(100vh - 220px);overflow:auto}
.modal-header{border-bottom:1px solid #eef2f7}
.modal-footer{border-top:1px solid #eef2f7}
.toast-container{z-index:11000}
.toast-stack{display:grid;gap:10px}
.toast.erp-toast{border:0;border-radius:16px;box-shadow:0 20px 50px rgba(15,23,42,.14);min-width:320px;max-width:min(420px,calc(100vw - 24px));overflow:hidden}
.toast.erp-toast .toast-body{font-weight:700}
.toast.erp-toast .toast-progress{height:3px;background:rgba(255,255,255,.18)}
.toast.erp-toast.toast-success{background:#166534;color:#fff}
.toast.erp-toast.toast-danger{background:#b91c1c;color:#fff}
.toast.erp-toast.toast-warning{background:#b45309;color:#fff}
.toast.erp-toast.toast-info{background:#0369a1;color:#fff}
.toast.erp-toast.toast-primary{background:#4338ca;color:#fff}
.toast.erp-toast.toast-secondary{background:#475569;color:#fff}

/* File preview inside modals */
.modal-file-preview{
  margin-top:.6rem;
  border:1px solid #e2e8f0;
  border-radius:16px;
  background:#f8fafc;
  padding:.65rem .75rem;
  display:flex;
  align-items:center;
  gap:.75rem;
  min-width:0;
}
.modal-file-preview.is-empty{display:none!important}
.modal-file-preview-thumb{
  width:64px;
  height:64px;
  border-radius:14px;
  overflow:hidden;
  background:#fff;
  border:1px solid #e2e8f0;
  flex:0 0 auto;
  display:flex;
  align-items:center;
  justify-content:center;
}
.modal-file-preview-thumb img{width:100%;height:100%;object-fit:contain;display:block}
.modal-file-preview-thumb .bi{font-size:1.5rem;color:#64748b}
.modal-file-preview-body{min-width:0;flex:1 1 auto}
.modal-file-preview-name{font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.modal-file-preview-meta{font-size:.82rem;color:#64748b}
.modal-file-preview-actions{display:flex;gap:.45rem;flex-wrap:wrap}
.modal-file-preview-actions .btn{min-height:36px;padding:.35rem .75rem;border-radius:12px}
.erp-image-viewer-modal{z-index:21060!important}
.erp-image-viewer-modal .modal-dialog{max-width:min(980px, calc(100vw - 1rem))}
.modal-backdrop.erp-image-viewer-backdrop{z-index:21050!important}
.erp-image-viewer-wrap{
  position:relative;
  height:min(76vh, 760px);
  background:#0f172a;
  border-radius:18px;
  overflow:hidden;
  touch-action:none;
  overscroll-behavior:contain;
  -ms-touch-action:none;
  user-select:none;
  -webkit-user-select:none;
}
.erp-image-viewer-stage{position:absolute;inset:0;cursor:grab;touch-action:none;-ms-touch-action:none;overscroll-behavior:contain}
.erp-image-viewer-stage.is-dragging{cursor:grabbing}
.erp-image-viewer-stage img{
  position:absolute;
  top:50%;left:50%;
  max-width:none;
  max-height:none;
  transform-origin:center center;
  will-change:transform;
}
.erp-image-viewer-hint{font-size:.82rem;color:#64748b}
html.erp-image-viewer-lock, body.erp-image-viewer-lock{touch-action:none;overscroll-behavior:none;-ms-content-zooming:none}
@media (max-width:767.98px){
  .modal-file-preview{padding:.55rem .6rem;gap:.6rem}
  .modal-file-preview-thumb{width:54px;height:54px;border-radius:12px}
  .erp-image-viewer-wrap{height:min(68vh, 560px)}
}

/* Compact inline fields inside modals */
.modal.modal-erp .modal-dialog{max-width:min(860px, calc(100vw - 1.2rem))}
.modal-inline-grid{--label-w:clamp(74px, 24%, 170px)}
.modal-inline-grid > [class*="col-"]{
  display:grid;
  grid-template-columns:minmax(0,var(--label-w)) minmax(0,1fr);
  align-items:center;
  column-gap:.8rem;
  row-gap:.35rem;
}
.modal-inline-grid > [class*="col-"] > .form-label{
  margin:0;
  white-space:nowrap;
  overflow:hidden;
  text-overflow:ellipsis;
  max-width:100%;
}
.modal-inline-grid > [class*="col-"] > .form-control,
.modal-inline-grid > [class*="col-"] > .form-select,
.modal-inline-grid > [class*="col-"] > .bootstrap-select,
.modal-inline-grid > [class*="col-"] > .picker-with-action,
.modal-inline-grid > [class*="col-"] > .input-group,
.modal-inline-grid > [class*="col-"] > .datepick,
.modal-inline-grid > [class*="col-"] > .text-secondary.small,
.modal-inline-grid > [class*="col-"] > .small,
.modal-inline-grid > [class*="col-"] > .logo-preview{
  min-width:0;
}
.modal-inline-grid > [class*="col-"] > .text-secondary.small,
.modal-inline-grid > [class*="col-"] > .small,
.modal-inline-grid > [class*="col-"] > .logo-preview{
  grid-column:2;
}
.modal-inline-grid .picker-with-action{width:100%}
.modal-inline-grid .bootstrap-select > .dropdown-toggle .filter-option-inner-inner{
  white-space:nowrap;
  overflow-x:auto;
  overflow-y:hidden;
  text-overflow:clip;
  scrollbar-width:thin;
}
.modal-inline-grid .bootstrap-select .dropdown-menu{
  max-width:100%;
  min-width:100%!important;
}
.modal-inline-grid .bootstrap-select .dropdown-menu .inner{
  max-width:100%;
  overflow:auto;
}
.modal-inline-grid .bootstrap-select .dropdown-menu .dropdown-item{
  display:block;
  width:max-content;
  min-width:100%;
  white-space:nowrap;
}
@media (max-width:767.98px){
  .modal-inline-grid > [class*="col-"]{grid-template-columns:1fr;align-items:stretch;}
  .modal-inline-grid > [class*="col-"] > .form-label{margin-bottom:.2rem;white-space:normal;}
  .modal-inline-grid > [class*="col-"] > .text-secondary.small,
  .modal-inline-grid > [class*="col-"] > .small,
  .modal-inline-grid > [class*="col-"] > .logo-preview{grid-column:auto;}
}

.topbar .user-trigger{border:1px solid rgba(226,232,240,.18)!important;border-radius:16px;padding:.35rem .55rem!important;background:rgba(255,255,255,.06)!important}
.topbar .user-trigger img{width:38px;height:38px;border-radius:50%;object-fit:cover;border:1px solid rgba(255,255,255,.18)}
.topbar .dropdown-menu{border:1px solid #e5e7eb;border-radius:16px;box-shadow:0 10px 30px rgba(0,0,0,.12);padding:12px;min-width:280px;max-width:280px;background:#fff}

.topbar .topbar-start,.topbar .topbar-end{display:flex;align-items:center;gap:.55rem}

.topbar .topbar-search{flex:1;display:flex;justify-content:center;min-width:0;padding-inline:14px}
.topbar .smart-search{position:relative;width:min(420px, 100%)}
.topbar .smart-search-input{
  width:100%;
  height:46px;
  border:1px solid rgba(226,232,240,.18);
  border-radius:14px;
  background:rgba(255,255,255,.07);
  color:var(--text-light);
  padding:.7rem 2.7rem .7rem .95rem;
  outline:none;
}
.topbar .smart-search-input::placeholder{color:rgba(226,232,240,.62)}
.topbar .smart-search-input:focus{
  border-color:rgba(226,232,240,.32);
  box-shadow:0 0 0 .18rem rgba(226,232,240,.08);
}
.topbar .smart-search-icon{
  position:absolute;
  left:12px;
  top:50%;
  transform:translateY(-50%);
  color:rgba(226,232,240,.7);
  pointer-events:none;
}
.topbar .smart-search-panel{
  position:absolute;
  top:calc(100% + 8px);
  right:0;
  width:100%;
  background:#fff;
  border:1px solid #e2e8f0;
  border-radius:16px;
  box-shadow:0 18px 45px rgba(15,23,42,.14);
  padding:.45rem;
  display:none;
  z-index:10020;
}
.topbar .smart-search-panel.show{display:block}
.topbar .smart-search-empty{padding:.8rem .9rem;color:#64748b;font-size:.92rem}
.topbar .smart-search-item{
  display:flex;
  align-items:center;
  justify-content:space-between;
  gap:1rem;
  padding:.75rem .85rem;
  border-radius:12px;
  color:#111827;
  text-decoration:none;
}
.topbar .smart-search-item:hover,
.topbar .smart-search-item.active{background:#f8fafc}
.topbar .smart-search-item .meta{min-width:0}
.topbar .smart-search-item .title{font-weight:800}
.topbar .smart-search-item .hint{
  font-size:.78rem;
  color:#64748b;
  margin-top:2px;
  white-space:nowrap;
  overflow:hidden;
  text-overflow:ellipsis;
}
.topbar .smart-search-item .go{color:#94a3b8}
.topbar .topbar-end{margin-inline-start:auto}
.topbar .company-trigger{min-height:44px;border:none!important;border-radius:12px;padding:0!important;background:transparent!important;color:var(--text-light)!important;box-shadow:none!important}
.topbar .company-trigger img{width:38px;height:38px;border-radius:50%;object-fit:cover;border:1px solid rgba(255,255,255,.18);background:#fff}
.topbar .dropdown-profile-grid{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:6px;text-align:center}
.topbar .dropdown-profile-grid .menu-card-logo{width:60px;height:60px;border-radius:16px;object-fit:cover;border:1px solid #dbe3ef;background:#fff;padding:4px}
.topbar .dropdown-profile-grid .menu-card-avatar{width:32px;height:32px;border-radius:10px;object-fit:cover;border:1px solid #e2e8f0;background:#fff}
.sidebar .special-link{background:rgba(148,163,184,.08);border:1px solid rgba(226,232,240,.08)}
.sidebar .special-link .sicon img{width:22px;height:22px;border-radius:8px;object-fit:cover;background:#fff;border:1px solid rgba(255,255,255,.14)}
.sidebar .special-link .slabel{display:flex;flex-direction:column;gap:2px;line-height:1.25}
.sidebar .special-link .slabel small{color:var(--text-muted);font-size:11px}
.sidebar .special-link .value-line{font-weight:800;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
body.sidebar-collapsed .sidebar .special-link .sicon img{width:28px;height:28px}
.topbar .dropdown-item{border-radius:10px;padding:8px 10px;font-weight:700;color:#1f2937;font-size:14px}
.topbar .dropdown-item:hover{background:#f8fafc}
.topbar .menu-card-logo{width:88px;height:88px;border-radius:24px;object-fit:cover;border:1px solid #dbe3ef;background:#fff;padding:6px}
.topbar .dropdown-header-card{padding:0 0 10px}
.topbar .dropdown-header-card .company-chip{display:inline-flex;align-items:center;gap:.4rem;padding:.35rem .7rem;border-radius:999px;background:#eef2ff;color:#3730a3;font-size:.84rem;font-weight:700}

.topbar .dropdown-item{border-radius:10px;padding:8px 10px;font-weight:700;color:#1f2937;font-size:14px}
.topbar .dropdown-item i{font-size:1rem;opacity:.9}
.topbar .dropdown-item:hover{background:#f8fafc}
.topbar .dropdown-divider{margin:.4rem 0}
.topbar .company-trigger{min-height:44px;border:none!important;border-radius:12px;padding:0!important;background:transparent!important;color:var(--text-light)!important;box-shadow:none!important}
.topbar .company-trigger::after{display:none!important}

.topbar .dropdown-company-name{font-weight:700;font-size:18px;line-height:1.2;color:#111827}
.topbar .dropdown-company-label{font-size:13px;color:#6b7280;margin-bottom:2px}
.topbar .dropdown-user-row{display:flex;align-items:center;gap:8px;justify-content:center}
.topbar .dropdown-user-row .user-meta{text-align:right}
.topbar .dropdown-user-row .user-name{font-weight:600;font-size:14px;color:#111827}
.topbar .dropdown-user-row .user-email{font-size:12px;color:#6b7280;font-weight:500}





/* Light mode for sidebar + topbar */
body:not(.dark-mode) .sidebar,
body:not(.dark-mode) .sidebar .brand,
body:not(.dark-mode) .sidebar-search-wrap{
  background:linear-gradient(180deg,#3f60c7 0%,#3554b5 100%)!important;
  border-color:#324da1!important;
}
body:not(.dark-mode) .topbar{
  background:linear-gradient(180deg,#5478e2 0%,#486ddb 100%)!important;
  border-color:#3c5ec4!important;
  box-shadow:0 10px 30px rgba(72,109,219,.18);
}
body:not(.dark-mode) .sidebar{
  box-shadow:0 12px 32px rgba(50,77,161,.22);
}
body:not(.dark-mode) .sidebar .brand-text,
body:not(.dark-mode) .sidebar .slink,
body:not(.dark-mode) .sidebar .accordion-button,
body:not(.dark-mode) .topbar,
body:not(.dark-mode) .topbar .company-trigger,
body:not(.dark-mode) .topbar .btn{
  color:#ffffff!important;
}
body:not(.dark-mode) .sidebar .brand-sub,
body:not(.dark-mode) .sidebar .nav-title,
body:not(.dark-mode) .sidebar .special-link .slabel small,
body:not(.dark-mode) .topbar .smart-search-empty,
body:not(.dark-mode) .topbar .smart-search-item .hint,
body:not(.dark-mode) .sidebar-search-icon{
  color:rgba(234,240,255,.82)!important;
}
body:not(.dark-mode) .sidebar .accordion-button::after{
  filter:brightness(0) invert(1);
  opacity:.8;
}
body:not(.dark-mode) .sidebar .slink:hover,
body:not(.dark-mode) .sidebar .accordion-button:hover,
body:not(.dark-mode) .sidebar-fav-btn:hover{
  background:rgba(255,255,255,.12)!important;
}
body:not(.dark-mode) .sidebar .slink.active,
body:not(.dark-mode) .sidebar .submenu .slink.active{
  background:#2f4fb0!important;
  border:1px solid rgba(255,255,255,.16)!important;
  box-shadow:inset 0 0 0 1px rgba(255,255,255,.08);
}
body:not(.dark-mode) .sidebar .submenu .slink,
body:not(.dark-mode) .sidebar .special-link{
  background:rgba(255,255,255,.06)!important;
  border-color:rgba(255,255,255,.08)!important;
}
body:not(.dark-mode) .sidebar-search-input,
body:not(.dark-mode) .topbar .smart-search-input,
body:not(.dark-mode) .topbar .input-group-text,
body:not(.dark-mode) .topbar .form-control,
body:not(.dark-mode) .topbar .user-trigger{
  background:rgba(255,255,255,.14)!important;
  border-color:rgba(255,255,255,.18)!important;
  color:#ffffff!important;
}
body:not(.dark-mode) .sidebar-search-input::placeholder,
body:not(.dark-mode) .topbar .smart-search-input::placeholder{
  color:rgba(234,240,255,.72)!important;
}
body:not(.dark-mode){
  --main-color:#5f8fc7;
  --text-light:#f8fbff;
  --text-muted:rgba(248,251,255,.76);
  --logo-bg:rgba(255,255,255,.18);
}
body:not(.dark-mode) .sidebar,
body:not(.dark-mode) .sidebar .brand,
body:not(.dark-mode) .sidebar-search-wrap,
body:not(.dark-mode) .topbar{
  background:linear-gradient(180deg,#6b9ad0 0%,#5f8fc7 52%,#5789c3 100%)!important;
}
body:not(.dark-mode) .sidebar,
body:not(.dark-mode) .sidebar .brand,
body:not(.dark-mode) .sidebar-search-wrap{
  border-color:rgba(255,255,255,.14)!important;
}
body:not(.dark-mode) .topbar{
  border-bottom-color:rgba(255,255,255,.16)!important;
  box-shadow:0 10px 30px rgba(86,137,195,.16);
}
body:not(.dark-mode) .topbar .btn{
  border-color:rgba(255,255,255,.22)!important;
}
body:not(.dark-mode) .topbar .btn:hover{
  background:rgba(255,255,255,.16)!important;
}
body:not(.dark-mode) .topbar .user-trigger img,
body:not(.dark-mode) .topbar .company-trigger img{
  border-color:rgba(255,255,255,.22)!important;
}
body:not(.dark-mode) .sidebar-search-input,
body:not(.dark-mode) .topbar .input-group-text,
body:not(.dark-mode) .topbar .form-control,
body:not(.dark-mode) .topbar .smart-search-input,
body:not(.dark-mode) .topbar .user-trigger{
  background:rgba(255,255,255,.14)!important;
  border-color:rgba(255,255,255,.18)!important;
}
body:not(.dark-mode) .sidebar .slink:hover,
body:not(.dark-mode) .sidebar .accordion-button:hover,
body:not(.dark-mode) .sidebar-fav-btn:hover{
  background:rgba(255,255,255,.12)!important;
}
body:not(.dark-mode) .sidebar .slink.active,
body:not(.dark-mode) .sidebar .submenu .slink.active{
  background:rgba(255,255,255,.18)!important;
  border-color:rgba(255,255,255,.18)!important;
}
body:not(.dark-mode) .sidebar .submenu .slink{
  background:rgba(255,255,255,.08)!important;
}

/* Dark mode */
body.dark-mode{
  background:#0b1220;
  color:#e5e7eb;
}
body.dark-mode .content{background:transparent;color:#e5e7eb;}
body.dark-mode .sidebar,
body.dark-mode .sidebar .brand,
body.dark-mode .sidebar-search-wrap{
  background:#111827!important;
  border-color:#334155!important;
}
body.dark-mode .topbar{
  background:#111827!important;
  border-bottom-color:#334155!important;
}
body.dark-mode .sidebar .slink:hover,
body.dark-mode .sidebar .accordion-button:hover,
body.dark-mode .sidebar-fav-btn:hover{
  background:rgba(148,163,184,.16)!important;
}
body.dark-mode .sidebar .slink.active,
body.dark-mode .sidebar .submenu .slink.active{
  background:#1e293b!important;
  border-color:#475569!important;
}
body.dark-mode .sidebar .submenu .slink{
  background:rgba(148,163,184,.08)!important;
}
body.dark-mode .sidebar-search-input{
  background:#0f172a!important;
  border-color:#334155!important;
  color:#e5e7eb!important;
}
body.dark-mode .sidebar-search-input::placeholder,
body.dark-mode .sidebar-search-icon{
  color:#94a3b8!important;
}
body.dark-mode .topbar .btn{
  border-color:#334155!important;
  color:#e5e7eb!important;
}
body.dark-mode .topbar .btn:hover{
  background:#1e293b!important;
}
body.dark-mode .topbar .input-group-text,
body.dark-mode .topbar .form-control,
body.dark-mode .topbar .user-trigger{
  background:#0f172a!important;
  border-color:#334155!important;
  color:#e5e7eb!important;
}
body.dark-mode .cardx,
body.dark-mode .card.cardx,
body.dark-mode .card,
body.dark-mode .modal-content,
body.dark-mode .topbar .dropdown-menu,
body.dark-mode .topbar .smart-search-panel,
body.dark-mode .bootstrap-select .dropdown-menu,
body.dark-mode .table-responsive,
body.dark-mode .list-group-item,
body.dark-mode .modal-file-preview-thumb{
  background:#111827!important;
  color:#e5e7eb!important;
  border-color:#334155!important;
}
body.dark-mode .table,
body.dark-mode .table > :not(caption) > * > *,
body.dark-mode table,
body.dark-mode thead,
body.dark-mode tbody,
body.dark-mode tr,
body.dark-mode td,
body.dark-mode th,
body.dark-mode .dropdown-item,
body.dark-mode .topbar .smart-search-item,
body.dark-mode .topbar .smart-search-item .title,
body.dark-mode .dropdown-company-name,
body.dark-mode .topbar .dropdown-user-row .user-name,
body.dark-mode .modal-title,
body.dark-mode .form-label,
body.dark-mode .nav-tabs .nav-link,
body.dark-mode .page-link,
body.dark-mode .breadcrumb,
body.dark-mode .text-dark{
  color:#e5e7eb!important;
}
body.dark-mode .text-secondary,
body.dark-mode .text-muted,
body.dark-mode .small,
body.dark-mode .topbar .smart-search-empty,
body.dark-mode .topbar .smart-search-item .hint,
body.dark-mode .topbar .dropdown-user-row .user-email,
body.dark-mode .dropdown-company-label,
body.dark-mode .modal-file-preview-meta,
body.dark-mode .erp-image-viewer-hint{
  color:#94a3b8!important;
}
body.dark-mode .form-control,
body.dark-mode .form-select,
body.dark-mode textarea.form-control,
body.dark-mode .input-group-text,
body.dark-mode .bootstrap-select > .dropdown-toggle,
body.dark-mode .bootstrap-select > .dropdown-toggle.form-select,
body.dark-mode .topbar .smart-search-input{
  background:#0f172a!important;
  color:#e5e7eb!important;
  border-color:#334155!important;
}
body.dark-mode .form-control::placeholder,
body.dark-mode .topbar .smart-search-input::placeholder,
body.dark-mode .bootstrap-select > .dropdown-toggle .filter-option-inner-inner{
  color:#94a3b8!important;
}
body.dark-mode .form-control:focus,
body.dark-mode .form-select:focus,
body.dark-mode .bootstrap-select > .dropdown-toggle:focus,
body.dark-mode .bootstrap-select > .dropdown-toggle.show,
body.dark-mode .bootstrap-select > .dropdown-toggle.form-select:focus,
body.dark-mode .bootstrap-select > .dropdown-toggle.form-select.show,
body.dark-mode .topbar .smart-search-input:focus{
  background:#0f172a!important;
  border-color:#475569!important;
  box-shadow:0 0 0 .18rem rgba(148,163,184,.15)!important;
}
body.dark-mode .bootstrap-select .dropdown-menu li a,
body.dark-mode .bootstrap-select .dropdown-menu .dropdown-item,
body.dark-mode .dropdown-item,
body.dark-mode .topbar .smart-search-item{
  color:#e5e7eb!important;
}
body.dark-mode .bootstrap-select .dropdown-menu li.selected a,
body.dark-mode .bootstrap-select .dropdown-menu .dropdown-item.active,
body.dark-mode .bootstrap-select .dropdown-menu .dropdown-item:active,
body.dark-mode .topbar .smart-search-item:hover,
body.dark-mode .topbar .smart-search-item.active,
body.dark-mode .dropdown-item:hover,
body.dark-mode .page-link:hover,
body.dark-mode .nav-tabs .nav-link:hover{
  background:#1e293b!important;
  color:#fff!important;
}
body.dark-mode .btn-outline-secondary,
body.dark-mode .btn-light,
body.dark-mode .btn-outline-dark{
  background:#0f172a!important;
  color:#e5e7eb!important;
  border-color:#334155!important;
}
body.dark-mode .btn-outline-secondary:hover,
body.dark-mode .btn-light:hover,
body.dark-mode .btn-outline-dark:hover{
  background:#1e293b!important;
  color:#fff!important;
  border-color:#475569!important;
}
body.dark-mode .alert-secondary,
body.dark-mode .alert-light{
  background:#111827!important;
  color:#e5e7eb!important;
  border-color:#334155!important;
}
body.dark-mode .table{--bs-table-bg:transparent;--bs-table-striped-bg:#0f172a;--bs-table-hover-bg:#172033;--bs-table-border-color:#334155;}
body.dark-mode .table-light,
body.dark-mode .table > thead{
  --bs-table-bg:#0f172a;
  color:#e5e7eb!important;
}
body.dark-mode .modal-header,
body.dark-mode .modal-footer,
body.dark-mode hr,
body.dark-mode .dropdown-divider,
body.dark-mode .accordion-item,
body.dark-mode .list-group-item,
body.dark-mode .page-link,
body.dark-mode .nav-tabs,
body.dark-mode .nav-tabs .nav-link,
body.dark-mode .border,
body.dark-mode .border-top,
body.dark-mode .border-bottom,
body.dark-mode .border-start,
body.dark-mode .border-end{
  border-color:#334155!important;
}
body.dark-mode .page-link,
body.dark-mode .nav-tabs .nav-link{
  background:#111827!important;
}
body.dark-mode .nav-tabs .nav-link.active,
body.dark-mode .page-item.active .page-link{
  background:#1e293b!important;
  border-color:#475569!important;
  color:#fff!important;
}
body.dark-mode .modal-file-preview{
  background:#0f172a!important;
  border-color:#334155!important;
}
body.dark-mode .modal-file-preview-thumb{background:#0b1220!important;}
body.dark-mode .picker-action-btn{
  background:#0f172a;
  color:#e5e7eb;
  border-color:#334155;
}
body.dark-mode .picker-action-btn:hover{background:#1e293b;border-color:#475569;color:#fff}
body.dark-mode .topbar .dropdown-header-card .company-chip{background:#1e293b!important;color:#c7d2fe!important}
body.dark-mode .topbar .company-trigger img,
body.dark-mode .topbar .user-trigger img,
body.dark-mode .topbar .dropdown-profile-grid .menu-card-logo,
body.dark-mode .topbar .dropdown-profile-grid .menu-card-avatar,
body.dark-mode .sidebar .special-link .sicon img{background:#fff}
body.dark-mode .btn-close{filter:invert(1) grayscale(1)}

@media (max-width:991px){
  .sidebar{
    position:fixed;
    right:0;
    width:min(76vw, 280px);
    max-width:280px;
    transform:translateX(110%);
    box-shadow:0 18px 45px rgba(2,6,23,.22);
  }
  .sidebar .brand{padding:0 12px;gap:10px}
  .sidebar-search-wrap{padding:10px 10px 12px}
  .slink{padding:9px 12px}
  .accordion-button{padding:11px 12px}
  .sidebar.show{ transform:translateX(0); }
  .modal.modal-erp .modal-dialog{margin:calc(var(--brand-h) + 10px) .6rem .6rem}
  .modal-body{max-height:calc(100vh - 190px)}
  .topbar{
    right:0;
    left:0;
    width:auto;
    padding-inline:12px;
  }
  .topbar .company-trigger .company-name-mini{display:none}
  .topbar .topbar-search{padding-inline:8px}
  .topbar .smart-search{max-width:100%}
  .content{
    padding-top:calc(var(--brand-h) + 16px);
    padding-inline:12px;
  }
}
</style>

<script>
function erpToastTypeFromText(text, fallbackType){
  const t = (text || '').toString().toLowerCase();

  if (/(حذف|delete|deleted|remove|removed|cancel|canceled|cancelled|الغاء|إلغاء|عكس|reverse|rollback)/.test(t)) return 'danger';
  if (/(خطا|خطأ|error|failed|failure|invalid|cannot|not found|exception|تعذر|فشل|مرفوض|غير صالح)/.test(t)) return 'danger';
  if (/(تحذير|warning|alert|تنبيه|duplicate|already exists|مكرر)/.test(t)) return 'warning';
  if (/(تعديل|update|updated|edit|edited|change|changed|حفظ|save|saved|رفع|upload|uploaded|استعاده|استعادة|restore|restored)/.test(t)) return 'info';
  if (/(انشاء|إنشاء|create|created|new|اضاف|إضاف|added|insert|inserted|فتح|register|registered|add)/.test(t)) return 'primary';
  if (/(ترحيل|post|posted|اعتماد|approve|approved|تأكيد|confirm|confirmed|success|successful|نجح|تم)/.test(t)) return 'success';

  return fallbackType || 'secondary';
}
</script>

</head>
<body class="<?= $themeMode === 'dark' ? 'dark-mode' : '' ?>">
<div class="overlay" id="overlay"></div>
<div class="app">

  <aside class="sidebar" id="sidebar">
    <div class="brand">
      <div class="logo-box" title="<?= h($appName) ?>">
        <img src="<?= h(url('/assets/img/favicon.png')) ?>" alt="<?= h($appName) ?>">
      </div>
      <div class="brand-name-wrap">
        <div class="brand-text"><?= h($appName) ?></div>
        <div class="brand-sub"><?= h($sub) ?></div>
      </div>
    </div>

    <div class="sidebar-search-wrap">
      <div class="sidebar-search">
        <input type="text" id="sidebarSearchInput" class="sidebar-search-input" placeholder="ابحث داخل القائمة...">
        <i class="bi bi-search sidebar-search-icon"></i>
      </div>
    </div>

    <div class="px-3 pt-3">
      <a class="<?= $linkClass('/index.php') ?> sidebar-home-link" href="<?= url('/index.php') ?>">
        <span class="sicon"><i class="bi bi-speedometer2"></i></span>
        <span class="slabel">لوحة التحكم</span>
      </a>
    </div>

    <div class="nav-title">الأقسام</div>

    <div class="px-3 pb-3">
      <div class="accordion sidebar-acc" id="sidebarAccordion">

        <?php if ($favoritesEnabled): ?>
        <div class="accordion-item">
          <h2 class="accordion-header" id="h-favorites">
            <button class="accordion-button collapsed" data-bs-toggle="collapse" data-bs-target="#favoritesSec" aria-expanded="false">
              <span class="sicon"><i class="bi bi-star-fill"></i></span>
              <span class="slabel">المفضلة</span>
            </button>
          </h2>
          <div id="favoritesSec" class="accordion-collapse collapse" data-bs-parent="#sidebarAccordion">
            <div class="accordion-body">
              <div class="submenu">
                <?php foreach ($favoriteRows as $favoriteRow): ?>
                  <?php $favoriteUrl = (string)($favoriteRow['page_url'] ?? ''); if ($favoriteUrl === '') continue; ?>
                  <div class="sidebar-link-row favorite-link-row" data-favorite-url="<?= h(rtrim(parse_url($favoriteUrl, PHP_URL_PATH) ?: $favoriteUrl, '/') ?: '/') ?>">
                    <a class="<?= $linkClass($favoriteUrl) ?>" href="<?= h(url($favoriteUrl)) ?>">
                      <span class="sicon"><i class="bi bi-star"></i></span>
                      <span class="slabel"><?= h((string)($favoriteRow['page_title'] ?? 'صفحة مفضلة')) ?></span>
                    </a>
                    <button type="button" class="sidebar-fav-btn active sidebar-fav-btn-favorite" data-page-url="<?= h(rtrim(parse_url($favoriteUrl, PHP_URL_PATH) ?: $favoriteUrl, '/') ?: '/') ?>" aria-label="إزالة من المفضلة" title="إزالة من المفضلة">
                      <i class="bi bi-star-fill"></i>
                    </button>
                  </div>
                <?php endforeach; ?>
              </div>
            </div>
          </div>
        </div>
        <?php endif; ?>

        <div class="accordion-item">
          <h2 class="accordion-header" id="h-accounts">
            <button class="accordion-button <?= $secAccounts ? '' : 'collapsed' ?>" data-bs-toggle="collapse" data-bs-target="#accounts" aria-expanded="<?= $secAccounts ? 'true' : 'false' ?>">
              <span class="sicon"><i class="bi bi-cash-coin"></i></span>
              <span class="slabel">الحسابات</span>
            </button>
          </h2>
          <div id="accounts" class="accordion-collapse collapse <?= $secAccounts ? 'show' : '' ?>" data-bs-parent="#sidebarAccordion">
            <div class="accordion-body">
              <div class="submenu">
                <a class="<?= $linkClass('/accounts/index.php') ?>" href="<?= url('/accounts/index.php') ?>"><span class="sicon"><i class="bi bi-diagram-3"></i></span><span class="slabel">شجرة الحسابات</span></a>
                <a class="<?= $linkClass('/cash/index.php') ?>" href="<?= url('/cash/index.php') ?>"><span class="sicon"><i class="bi bi-wallet2"></i></span><span class="slabel">الوارد والمنصرف</span></a>
                <a class="<?= $linkClass('/journal/index.php') ?>" href="<?= url('/journal/index.php') ?>"><span class="sicon"><i class="bi bi-journal-text"></i></span><span class="slabel">القيود اليومية</span></a>
                <a class="slink" href="<?= url('/journal/daily_posting.php') ?>"><span class="sicon"><i class="bi bi-check2-circle"></i></span><span class="slabel">ترحيل قيود اليوم</span></a>
                <a class="<?= $linkClass('/hr/advances.php') ?>" href="<?= url('/hr/advances.php') ?>"><span class="sicon"><i class="bi bi-wallet2"></i></span><span class="slabel">عهد الموظفين</span></a>
                <a class="<?= $linkClass('/accounts/vehicle_accounts.php') ?>" href="<?= url('/accounts/vehicle_accounts.php') ?>"><span class="sicon"><i class="bi bi-cash-stack"></i></span><span class="slabel">حسابات السيارات</span></a>
              </div>
            </div>
          </div>
        </div>
        
        <div class="accordion-item">
          <h2 class="accordion-header" id="h-reports">
            <button class="accordion-button <?= $secReports ? '' : 'collapsed' ?>" data-bs-toggle="collapse" data-bs-target="#reports" aria-expanded="<?= $secReports ? 'true' : 'false' ?>">
              <span class="sicon"><i class="bi bi-bar-chart"></i></span>
              <span class="slabel">التقارير</span>
            </button>
          </h2>
          <div id="reports" class="accordion-collapse collapse <?= $secReports ? 'show' : '' ?>" data-bs-parent="#sidebarAccordion">
            <div class="accordion-body">
              <div class="submenu">
                <a class="<?= $linkClass('/reports/trial_balance.php') ?>" href="<?= url('/reports/trial_balance.php') ?>"><span class="sicon"><i class="bi bi-clipboard-data"></i></span><span class="slabel">ميزان المراجعة</span></a>
                <a class="<?= $linkClass('/reports/general_ledger.php') ?>" href="<?= url('/reports/general_ledger.php') ?>"><span class="sicon"><i class="bi bi-journals"></i></span><span class="slabel">دفتر الأستاذ</span></a>
                <a class="<?= $linkClass('/reports/pl.php') ?>" href="<?= url('/reports/pl.php') ?>"><span class="sicon"><i class="bi bi-graph-up"></i></span><span class="slabel">الأرباح والخسائر</span></a>
                <a class="<?= $linkClass('/reports/balance_sheet.php') ?>" href="<?= url('/reports/balance_sheet.php') ?>"><span class="sicon"><i class="bi bi-bank"></i></span><span class="slabel">المركز المالي</span></a>
                <a class="<?= $linkClass('/reports/cash_flow.php') ?>" href="<?= url('/reports/cash_flow.php') ?>"><span class="sicon"><i class="bi bi-cash-stack"></i></span><span class="slabel">التدفقات النقدية</span></a>
                <a class="<?= $linkClass('/reports/employee_advances.php') ?>" href="<?= url('/reports/employee_advances.php') ?>"><span class="sicon"><i class="bi bi-clipboard-data"></i></span><span class="slabel">تقرير العهد</span></a>
              </div>
            </div>
          </div>
        </div>
        
        <div class="accordion-item">
          <h2 class="accordion-header" id="h-hr">
            <button class="accordion-button <?= $secHR ? '' : 'collapsed' ?>" data-bs-toggle="collapse" data-bs-target="#hr" aria-expanded="<?= $secHR ? 'true' : 'false' ?>">
              <span class="sicon"><i class="bi bi-person-badge"></i></span>
              <span class="slabel">الموارد البشرية</span>
            </button>
          </h2>
          <div id="hr" class="accordion-collapse collapse <?= $secHR ? 'show' : '' ?>" data-bs-parent="#sidebarAccordion">
            <div class="accordion-body">
              <div class="submenu">
                <a class="<?= $linkClass('/hr/employees.php') ?>" href="<?= url('/hr/employees.php') ?>"><span class="sicon"><i class="bi bi-people"></i></span><span class="slabel">الموظفين</span></a>
                <a class="<?= $linkClass('/hr/attendance.php') ?>" href="<?= url('/hr/attendance.php') ?>"><span class="sicon"><i class="bi bi-calendar-check"></i></span><span class="slabel">الحضور والانصراف</span></a>
                <a class="<?= $linkClass('/hr/missions.php') ?>" href="<?= url('/hr/missions.php') ?>"><span class="sicon"><i class="bi bi-geo"></i></span><span class="slabel">المأموريات</span></a>
                <a class="<?= $linkClass('/hr/payroll.php') ?>" href="<?= url('/hr/payroll.php') ?>"><span class="sicon"><i class="bi bi-wallet2"></i></span><span class="slabel">الرواتب</span></a>
              </div>
            </div>
          </div>
        </div>
        

        <div class="accordion-item">
          <h2 class="accordion-header" id="h-fleet">
            <button class="accordion-button <?= $secFleet ? '' : 'collapsed' ?>" data-bs-toggle="collapse" data-bs-target="#fleetSec" aria-expanded="<?= $secFleet ? 'true' : 'false' ?>">
              <span class="sicon"><i class="bi bi-car-front"></i></span>
              <span class="slabel">إدارة السيارات</span>
            </button>
          </h2>
          <div id="fleetSec" class="accordion-collapse collapse <?= $secFleet ? 'show' : '' ?>" data-bs-parent="#sidebarAccordion">
            <div class="accordion-body">
              <div class="submenu">
                <a class="<?= $linkClass('/fleet/order_serials.php') ?>" href="<?= url('/fleet/order_serials.php') ?>"><span class="sicon"><i class="bi bi-list-ol"></i></span><span class="slabel">سريال أوامر التشغيل</span></a>
                    <a class="<?= $linkClass('/fleet/vehicles.php') ?>" href="<?= url('/fleet/vehicles.php') ?>"><span class="sicon"><i class="bi bi-car-front"></i></span><span class="slabel">تسجيل المركبات</span></a>
                    <a class="<?= $linkClass('/fleet/vehicle_types.php') ?>" href="<?= url('/fleet/vehicle_types.php') ?>"><span class="sicon"><i class="bi bi-tags"></i></span><span class="slabel">أنواع السيارات</span></a>
                    <a class="<?= $linkClass('/fleet/rentals.php') ?>" href="<?= url('/fleet/rentals.php') ?>"><span class="sicon"><i class="bi bi-car-front"></i></span><span class="slabel">تأجير السيارات</span></a>
                    <a class="<?= $linkClass('/fleet/locations.php') ?>" href="<?= url('/fleet/locations.php') ?>"><span class="sicon"><i class="bi bi-geo-alt"></i></span><span class="slabel">مناطق الليموزين</span></a>
                    <a class="<?= $linkClass('/fleet/limo_trips.php') ?>" href="<?= url('/fleet/limo_trips.php') ?>"><span class="sicon"><i class="bi bi-car-front-fill"></i></span><span class="slabel">تشغيل الليموزين</span></a>
                    <a class="<?= $linkClass('/fleet/trip_pricing.php') ?>" href="<?= url('/fleet/trip_pricing.php') ?>"><span class="sicon"><i class="bi bi-cash-coin"></i></span><span class="slabel">تسعير الرحلات</span></a>
                    <a class="<?= $linkClass('/fleet/rental_pricing.php') ?>" href="<?= url('/fleet/rental_pricing.php') ?>"><span class="sicon"><i class="bi bi-tags"></i></span><span class="slabel">تسعير التأجير</span></a>
              </div>
            </div>
          </div>
        </div>

        <div class="accordion-item">
          <h2 class="accordion-header" id="h-customers">
            <button class="accordion-button <?= ($secCustomers) ? '' : 'collapsed' ?>" data-bs-toggle="collapse" data-bs-target="#customers" aria-expanded="<?= ($secCustomers) ? 'true' : 'false' ?>">
              <span class="sicon"><i class="bi bi-person-vcard"></i></span>
              <span class="slabel">إدارة العملاء</span>
            </button>
          </h2>
          <div id="customers" class="accordion-collapse collapse <?= ($secCustomers) ? 'show' : '' ?>" data-bs-parent="#sidebarAccordion">
            <div class="accordion-body">
              <div class="submenu">
                <a class="<?= $linkClass('/tourism/customers.php') ?>" href="<?= url('/tourism/customers.php') ?>"><span class="sicon"><i class="bi bi-people"></i></span><span class="slabel">تسجيل العملاء</span></a>
                <a class="<?= $linkClass('/tourism/services.php') ?>" href="<?= url('/tourism/services.php') ?>"><span class="sicon"><i class="bi bi-briefcase"></i></span><span class="slabel">خدمات العملاء</span></a>
                <a class="<?= $linkClass('/tourism/customer_ledger.php') ?>" href="<?= url('/tourism/customer_ledger.php') ?>"><span class="sicon"><i class="bi bi-receipt"></i></span><span class="slabel">كشف حساب العميل</span></a>
              </div>
            </div>
          </div>
        </div>
<div class="accordion-item">
          <h2 class="accordion-header" id="h-hotels">
            <button class="accordion-button <?= ($secHotels) ? '' : 'collapsed' ?>" data-bs-toggle="collapse" data-bs-target="#hotelsSec" aria-expanded="<?= ($secHotels) ? 'true' : 'false' ?>">
              <span class="sicon"><i class="bi bi-buildings"></i></span>
              <span class="slabel">حجوزات الفنادق</span>
            </button>
          </h2>
          <div id="hotelsSec" class="accordion-collapse collapse <?= ($secHotels) ? 'show' : '' ?>" data-bs-parent="#sidebarAccordion">
            <div class="accordion-body">
              <div class="submenu">
                <a class="<?= $linkClass('/hotel/hotels.php') ?>" href="<?= url('/hotel/hotels.php') ?>"><span class="sicon"><i class="bi bi-building"></i></span><span class="slabel">تسجيل الفنادق</span></a>
                <a class="<?= $linkClass('/hotel/rooms.php') ?>" href="<?= url('/hotel/rooms.php') ?>"><span class="sicon"><i class="bi bi-door-open"></i></span><span class="slabel">تسجيل الغرف</span></a>
                <a class="<?= $linkClass('/hotel/bookings.php') ?>" href="<?= url('/hotel/bookings.php') ?>"><span class="sicon"><i class="bi bi-journal-richtext"></i></span><span class="slabel">طلبات الحجز</span></a>
                <a class="<?= $linkClass('/hotel/receipts.php') ?>" href="<?= url('/hotel/receipts.php') ?>"><span class="sicon"><i class="bi bi-cash-coin"></i></span><span class="slabel">التحصيلات</span></a>
                <a class="<?= $linkClass('/hotel/reports.php') ?>" href="<?= url('/hotel/reports.php') ?>"><span class="sicon"><i class="bi bi-bar-chart-line"></i></span><span class="slabel">تقارير الحجوزات</span></a>
              </div>
            </div>
          </div>
        </div>

        <div class="accordion-item">
          <h2 class="accordion-header" id="h-users">
            <button class="accordion-button <?= $secUsers ? '' : 'collapsed' ?>" data-bs-toggle="collapse" data-bs-target="#users" aria-expanded="<?= $secUsers ? 'true' : 'false' ?>">
              <span class="sicon"><i class="bi bi-people"></i></span>
              <span class="slabel">إدارة المستخدمين</span>
            </button>
          </h2>
          <div id="users" class="accordion-collapse collapse <?= $secUsers ? 'show' : '' ?>" data-bs-parent="#sidebarAccordion">
            <div class="accordion-body">
              <div class="submenu">
                <a class="<?= $linkClass('/users/index.php') ?>" href="<?= url('/users/index.php') ?>"><span class="sicon"><i class="bi bi-person"></i></span><span class="slabel">المستخدمين</span></a>
              </div>
            </div>
          </div>
        </div>

        <div class="accordion-item">
          <h2 class="accordion-header" id="h-settings">
            <button class="accordion-button <?= $secSettings ? '' : 'collapsed' ?>" data-bs-toggle="collapse" data-bs-target="#settings" aria-expanded="<?= $secSettings ? 'true' : 'false' ?>">
              <span class="sicon"><i class="bi bi-gear"></i></span>
              <span class="slabel">الإعدادات</span>
            </button>
          </h2>
          <div id="settings" class="accordion-collapse collapse <?= $secSettings ? 'show' : '' ?>" data-bs-parent="#sidebarAccordion">
            <div class="accordion-body">
              <div class="submenu">
                <a class="<?= $linkClass('/settings/database.php') ?>" href="<?= url('/settings/database.php') ?>"><span class="sicon"><i class="bi bi-hdd-stack"></i></span><span class="slabel">إدارة قاعدة البيانات</span></a>
                <a class="<?= $linkClass('/settings/backup_logs.php') ?>" href="<?= url('/settings/backup_logs.php') ?>"><span class="sicon"><i class="bi bi-clock-history"></i></span><span class="slabel">سجل النسخ الاحتياطي</span></a>
                <a class="<?= $linkClass('/settings/audit_logs.php') ?>" href="<?= url('/settings/audit_logs.php') ?>"><span class="sicon"><i class="bi bi-shield-check"></i></span><span class="slabel">سجل العمليات</span></a>
              </div>
            </div>
          </div>
        </div>

      </div>
    </div>
  </aside>

  <main class="content">
    <div class="topbar">
      <div class="topbar-start">
        <button class="btn d-lg-none" id="btnMenu" type="button" aria-label="Open menu"><i class="bi bi-list"></i></button>
        <button class="btn d-none d-lg-inline-flex" id="btnCollapse" type="button" aria-label="Collapse sidebar"><i class="bi bi-layout-sidebar-inset"></i></button>
      </div>

      <div class="flex-grow-1"></div>

      <div class="topbar-end">
        <button class="btn theme-toggle-btn" id="themeToggleBtn" type="button" aria-label="تبديل وضع الألوان" title="<?= $themeMode === 'dark' ? 'الوضع الفاتح' : 'الوضع الداكن' ?>">
          <i class="bi <?= $themeMode === 'dark' ? 'bi-sun-fill' : 'bi-moon-stars-fill' ?>"></i>
        </button>
        <div class="dropdown">
          <button class="btn company-trigger d-flex align-items-center gap-2" data-bs-toggle="dropdown" type="button" aria-expanded="false">
            <img src="<?= h($companyLogo) ?>" alt="<?= h($companyName) ?>">
            <span class="company-name-mini d-none d-md-inline"><?= h($companyName ?: 'الشركة الحالية') ?></span>
          </button>
          <div class="dropdown-menu">
            <div class="dropdown-header-card">
              <div class="dropdown-profile-grid">
                <img src="<?= h($companyLogo) ?>" alt="<?= h($companyName) ?>" class="menu-card-logo">
                <div class="dropdown-company-name"><?= h($companyName) ?></div>
                <div class="dropdown-company-label">الشركة الحالية</div>
                <div class="dropdown-user-row">
                  <img src="<?= h($userAvatar) ?>" alt="<?= h($userName) ?>" class="menu-card-avatar">
                  <div class="user-meta">
                    <div class="user-name"><?= h($userName) ?></div>
                    <div class="user-email"><?= h($userEmail) ?></div>
                  </div>
                </div>
              </div>
            </div>
            <div class="dropdown-divider my-2"></div>
            <a class="dropdown-item d-flex align-items-center gap-2" href="<?= url('/settings/company.php') ?>"><i class="bi bi-buildings"></i><span>بيانات الشركة الحالية</span></a>
            <a class="dropdown-item d-flex align-items-center gap-2" href="<?= url('/users/profile.php') ?>"><i class="bi bi-person"></i><span>الملف التعريفي للمستخدم</span></a>
            <a class="dropdown-item d-flex align-items-center gap-2 text-danger" href="<?= url('/auth/logout.php') ?>"><i class="bi bi-box-arrow-right"></i><span>تسجيل الخروج</span></a>
          </div>
        </div>
      </div>
    </div>

    <div class="container-fluid">
      <div class="d-flex justify-content-end mb-2">
        <?php if (function_exists('page_actions')) page_actions(); ?>
      </div>

      <?php $bodyFn(); ?>

    </div>
  </main>
</div>

<div class="modal fade" id="ajaxQuickModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">
      <form id="ajaxQuickForm" class="ajax-quick-form">
        <div class="modal-header">
          <h5 class="modal-title" id="ajaxQuickModalTitle">إضافة عنصر</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <div class="alert alert-danger ajax-quick-feedback" id="ajaxQuickFeedback"></div>
          <div class="row g-2" id="ajaxQuickFields"></div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">إلغاء</button>
          <button type="submit" class="btn btn-dark" id="ajaxQuickSubmitBtn">حفظ</button>
        </div>
      </form>
    </div>
  </div>
</div>

<div class="toast-container position-fixed top-0 start-0 p-3">
  <div id="erpToastStack" class="toast-stack"></div>
</div>

<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.14.0-beta3/dist/js/bootstrap-select.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>
<script>
const sidebar = document.getElementById('sidebar');
const overlay = document.getElementById('overlay');
const btnMenu = document.getElementById('btnMenu');
const btnCollapse = document.getElementById('btnCollapse');
const themeToggleBtn = document.getElementById('themeToggleBtn');

function applyThemeMode(mode){
  const isDark = mode === 'dark';
  document.body.classList.toggle('dark-mode', isDark);
  if(themeToggleBtn){
    themeToggleBtn.innerHTML = `<i class="bi ${isDark ? 'bi-sun-fill' : 'bi-moon-stars-fill'}"></i>`;
    themeToggleBtn.setAttribute('title', isDark ? 'الوضع الفاتح' : 'الوضع الداكن');
    themeToggleBtn.setAttribute('aria-label', isDark ? 'تفعيل الوضع الفاتح' : 'تفعيل الوضع الداكن');
  }
}

if(themeToggleBtn){
  themeToggleBtn.addEventListener('click', async () => {
    try{
      const res = await fetch('<?= url('/app/toggle_theme.php') ?>', {
        method:'POST',
        headers:{'X-Requested-With':'XMLHttpRequest'}
      });
      const data = await res.json();
      if(data && data.ok){
        applyThemeMode(data.mode === 'dark' ? 'dark' : 'light');
      }
    }catch(e){
      console.error(e);
    }
  });
}
function isMobile(){ return window.matchMedia("(max-width:991px)").matches; }
function openSidebar(){ sidebar.classList.add('show'); overlay.classList.add('show'); document.body.style.overflow="hidden"; }
function closeSidebar(){ sidebar.classList.remove('show'); overlay.classList.remove('show'); document.body.style.overflow=""; }
btnMenu?.addEventListener('click', ()=>{ if(isMobile()){ sidebar.classList.contains('show') ? closeSidebar():openSidebar(); } });
overlay?.addEventListener('click', closeSidebar);
document.addEventListener('keydown',(e)=>{ if(e.key==="Escape") closeSidebar(); });
btnCollapse?.addEventListener('click', ()=>{ if(!isMobile()) document.body.classList.toggle('sidebar-collapsed'); });

// Init selectpicker
function initSelectPickers(scope){
  if(!window.jQuery) return;
  const $scope = scope ? $(scope) : $(document);
  $scope.find('.selectpicker').each(function(){
    const opts = {
      styleBase: '',
      liveSearchNormalize: true,
      noneSelectedText: 'اختر...',
      noneResultsText: 'لا توجد نتائج {0}',
      selectAllText: 'تحديد الكل',
      deselectAllText: 'إلغاء التحديد',
      dropupAuto: false,
      size: 6,
      liveSearchPlaceholder: 'ابحث هنا'
    };
    if($(this).data('selectpicker')){
      $(this).selectpicker('destroy');
    }
    $(this).selectpicker(opts);
  });
}
if (window.jQuery) {
  $(function(){
    initSelectPickers(document);

    $(document).on('shown.bs.select', '.selectpicker', function(){
      const parent = $(this).parent('.bootstrap-select');
      const search = parent.find('.bs-searchbox input');
      setTimeout(() => search.trigger('focus'), 10);
    });

    $(document).on('changed.bs.select', '.selectpicker', function(){
      const inst = $(this).data('selectpicker');
      if(inst && inst.$button){ inst.$button.trigger('blur'); }
      setTimeout(() => {
        const parent = $(this).parent('.bootstrap-select');
        parent.find('button.dropdown-toggle').dropdown('hide');
      }, 60);
    });

    $(document).on('shown.bs.modal', '.modal', function(){
      initSelectPickers(this);
    });

    $(document).on('changed.bs.select', '#aq_parent_id, #aq_type', function(){
      loadQuickAccountPreview();
    });
  });
}

const erpToastStack = document.getElementById('erpToastStack');
function inferToastType(message, type = 'success'){
  if(['danger','warning','info','success','primary','secondary'].includes(type)) return type;
  const text = String(message || '').trim();
  if(type && type !== 'success') return ['danger','warning','info','primary','secondary'].includes(type) ? type : 'success';
  if(/حذف|ملغ|إزالة/.test(text)) return 'danger';
  if(/إلغاء الترحيل|الغاء الترحيل|فك الترحيل|unpost/i.test(text)) return 'warning';
  if(/ترحيل|مرحلة|posted/i.test(text)) return 'primary';
  if(/تعديل|تحديث|edited|updated/i.test(text)) return 'info';
  if(/تحويل/.test(text)) return 'secondary';
  if(/تسوية/.test(text)) return 'info';
  return 'success';
}
function showErpToast(message, type = 'success'){
  if(!erpToastStack || !message) return;
  const safeType = inferToastType(message, type);
  const wrapper = document.createElement('div');
  wrapper.className = `toast erp-toast toast-${safeType}`;
  wrapper.setAttribute('role','status');
  wrapper.setAttribute('aria-live','polite');
  wrapper.setAttribute('aria-atomic','true');
  wrapper.innerHTML = `
    <div class="d-flex align-items-start">
      <div class="toast-body">${message}</div>
      <button type="button" class="btn-close btn-close-white me-2 mt-2" data-bs-dismiss="toast" aria-label="Close"></button>
    </div>
    <div class="toast-progress"></div>`;
  erpToastStack.appendChild(wrapper);
  const toast = new bootstrap.Toast(wrapper, {delay: 3200});
  wrapper.addEventListener('hidden.bs.toast', () => wrapper.remove());
  toast.show();
}

document.addEventListener('DOMContentLoaded', function(){
  document.querySelectorAll('.alert.alert-success, .alert.alert-danger, .alert.alert-warning, .alert.alert-info').forEach(function(el){
    const type = el.classList.contains('alert-danger') ? 'danger'
      : el.classList.contains('alert-warning') ? 'warning'
      : el.classList.contains('alert-info') ? 'info'
      : 'success';
    const msg = (el.textContent || '').trim();
    if(msg){ showErpToast(msg, type); }
    el.remove();
  });
  const params = new URLSearchParams(window.location.search);
  if(params.get('msg')){
    showErpToast(params.get('msg'), params.get('msg_type') || 'success');
  }
  if(params.get('err')){
    showErpToast(params.get('err'), 'danger');
  }
  <?php foreach ($flashToasts as $toast): ?>
  showErpToast(<?= json_encode((string)($toast['message'] ?? '')) ?>, <?= json_encode((string)($toast['type'] ?? 'success')) ?>);
  <?php endforeach; ?>
});

// Date selectpicker -> hidden YYYY-MM-DD
function pad2(n){ return (n<10?'0':'') + n; }
function syncDateGroup(groupEl){
  const groupName = groupEl.getAttribute('data-date-group');
  const y = groupEl.querySelector(`[name="${groupName}_y"]`)?.value;
  const m = groupEl.querySelector(`[name="${groupName}_m"]`)?.value;
  const d = groupEl.querySelector(`[name="${groupName}_d"]`)?.value;
  const hidden = document.getElementById(groupName);
  if(hidden && y && m && d){ hidden.value = `${y}-${pad2(parseInt(m,10))}-${pad2(parseInt(d,10))}`; }
}

document.querySelectorAll('[data-date-group]').forEach(groupEl => {
  groupEl.addEventListener('change', ()=> syncDateGroup(groupEl));
  // initial sync
  syncDateGroup(groupEl);
});
</script>

<script>
(function(){
  function formatBytes(bytes){
    const n = Number(bytes || 0);
    if(!n) return '';
    if(n < 1024) return n + ' B';
    if(n < 1024 * 1024) return (n / 1024).toFixed(1).replace(/\.0$/, '') + ' KB';
    return (n / 1024 / 1024).toFixed(1).replace(/\.0$/, '') + ' MB';
  }
  function getFileKind(file){
    const name = String((file && file.name) || '').toLowerCase();
    const type = String((file && file.type) || '').toLowerCase();
    if(type.indexOf('image/') === 0 || /\.(jpg|jpeg|png|webp|gif|svg)$/.test(name)) return 'image';
    if(type === 'application/pdf' || /\.pdf$/.test(name)) return 'pdf';
    return 'file';
  }
  function ensurePreviewBox(input){
    if(!input || !input.closest('.modal')) return null;
    if(!input.id){ input.id = 'file_' + Math.random().toString(36).slice(2,10); }
    const parent = input.parentElement || input;
    let box = parent.querySelector('.modal-file-preview[data-for="' + input.id + '"]');
    if(box) return box;
    box = document.createElement('div');
    box.className = 'modal-file-preview is-empty';
    box.setAttribute('data-for', input.id);
    box.innerHTML = '<div class="modal-file-preview-thumb"><span class="bi bi-paperclip"></span></div>' +
      '<div class="modal-file-preview-body"><div class="modal-file-preview-name">لا توجد معاينة</div><div class="modal-file-preview-meta"></div></div>' +
      '<div class="modal-file-preview-actions"><button type="button" class="btn btn-sm btn-outline-secondary d-none js-preview-open"><i class="bi bi-arrows-fullscreen"></i> معاينة</button></div>';
    input.insertAdjacentElement('afterend', box);
    return box;
  }
  function clearPreviewBox(box){
    if(!box) return;
    const imgEl = box.querySelector('img');
    if(imgEl && imgEl.dataset.objectUrl){ URL.revokeObjectURL(imgEl.dataset.objectUrl); }
    box.classList.add('is-empty');
    box.querySelector('.modal-file-preview-thumb').innerHTML = '<span class="bi bi-paperclip"></span>';
    box.querySelector('.modal-file-preview-name').textContent = 'لا توجد معاينة';
    box.querySelector('.modal-file-preview-meta').textContent = '';
    const btn = box.querySelector('.js-preview-open');
    btn.classList.add('d-none');
    btn.removeAttribute('data-preview-src');
    btn.removeAttribute('data-preview-title');
  }
  function updateFilePreview(input){
    const box = ensurePreviewBox(input);
    if(!box) return;
    const file = input.files && input.files[0] ? input.files[0] : null;
    if(!file){ clearPreviewBox(box); return; }
    const kind = getFileKind(file);
    const thumb = box.querySelector('.modal-file-preview-thumb');
    const meta = [kind === 'image' ? 'صورة' : (kind === 'pdf' ? 'PDF' : 'ملف'), formatBytes(file.size)].filter(Boolean).join(' • ');
    const btn = box.querySelector('.js-preview-open');
    box.classList.remove('is-empty');
    box.querySelector('.modal-file-preview-name').textContent = file.name || 'ملف مرفق';
    box.querySelector('.modal-file-preview-meta').textContent = meta;
    btn.classList.add('d-none');
    btn.removeAttribute('data-preview-src');
    btn.removeAttribute('data-preview-title');
    const oldImg = thumb.querySelector('img');
    if(oldImg && oldImg.dataset.objectUrl){ URL.revokeObjectURL(oldImg.dataset.objectUrl); }
    if(kind === 'image'){
      const src = URL.createObjectURL(file);
      thumb.innerHTML = '<img alt="preview">';
      const imgEl = thumb.querySelector('img');
      imgEl.src = src;
      imgEl.dataset.objectUrl = src;
      btn.classList.remove('d-none');
      btn.setAttribute('data-preview-src', src);
      btn.setAttribute('data-preview-title', file.name || 'معاينة الصورة');
    } else if(kind === 'pdf'){
      thumb.innerHTML = '<span class="bi bi-file-earmark-pdf"></span>';
    } else {
      thumb.innerHTML = '<span class="bi bi-file-earmark"></span>';
    }
  }
  function setupModalFilePreviews(scope){
    (scope || document).querySelectorAll('.modal input[type="file"]').forEach(function(input){
      ensurePreviewBox(input);
      if(!input.dataset.previewBound){
        input.addEventListener('change', function(){ updateFilePreview(input); });
        input.dataset.previewBound = '1';
      }
      updateFilePreview(input);
    });
  }

  const modalEl = document.getElementById('erpImageViewerModal');
  const stage = document.getElementById('erpImageViewerStage');
  const img = document.getElementById('erpImageViewerImg');
  const titleEl = document.getElementById('erpImageViewerTitle');
  const viewportMeta = document.getElementById('appViewportMeta');
  const defaultViewportContent = viewportMeta ? (viewportMeta.getAttribute('content') || 'width=device-width, initial-scale=1, viewport-fit=cover') : '';
  const lockedViewportContent = 'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover';
  const state = {scale:1, x:0, y:0, dragging:false, startX:0, startY:0, startScale:1, startDistance:0, pinchCenter:null, pointers:new Map(), gestureActive:false, touchMode:false, touchStartDistance:0, touchStartScale:1, touchCenter:null};
  function getViewer(){
    if(!modalEl || !window.bootstrap) return null;
    return bootstrap.Modal.getOrCreateInstance(modalEl);
  }
  function applyTransform(){ if(img){ img.style.transform = 'translate(calc(-50% + ' + state.x + 'px), calc(-50% + ' + state.y + 'px)) scale(' + state.scale + ')'; } }
  function lockPageZoom(){ if(viewportMeta) viewportMeta.setAttribute('content', lockedViewportContent); document.documentElement.classList.add('erp-image-viewer-lock'); document.body.classList.add('erp-image-viewer-lock'); }
  function unlockPageZoom(){ if(viewportMeta) viewportMeta.setAttribute('content', defaultViewportContent); document.documentElement.classList.remove('erp-image-viewer-lock'); document.body.classList.remove('erp-image-viewer-lock'); }
  function resetViewer(){ state.scale = 1; state.x = 0; state.y = 0; state.dragging = false; state.gestureActive = false; state.pointers = new Map(); state.touchMode = false; state.touchStartDistance = 0; state.touchStartScale = 1; state.touchCenter = null; applyTransform(); }
  function setScale(next, center){
    const prev = state.scale;
    state.scale = Math.max(1, Math.min(6, next));
    if(center && stage){
      const rect = stage.getBoundingClientRect();
      const cx = center.x - rect.left - rect.width / 2;
      const cy = center.y - rect.top - rect.height / 2;
      const ratio = state.scale / prev;
      state.x = cx - (cx - state.x) * ratio;
      state.y = cy - (cy - state.y) * ratio;
    }
    applyTransform();
  }
  window.openErpImageViewer = function(src, title){
    const viewer = getViewer();
    if(!viewer || !src) return;
    img.src = src;
    titleEl.textContent = title || 'معاينة الصورة';
    resetViewer();
    lockPageZoom();
    viewer.show();
    setTimeout(function(){
      const backdrops = document.querySelectorAll('.modal-backdrop');
      const lastBackdrop = backdrops[backdrops.length - 1];
      if(lastBackdrop){ lastBackdrop.classList.add('erp-image-viewer-backdrop'); }
      if(modalEl){ modalEl.style.zIndex = '21060'; }
    }, 10);
  };
  const zoomInBtn = document.getElementById('erpImageZoomIn');
  const zoomOutBtn = document.getElementById('erpImageZoomOut');
  const resetBtn = document.getElementById('erpImageReset');
  if(zoomInBtn) zoomInBtn.addEventListener('click', function(){ setScale(state.scale + 0.25); });
  if(zoomOutBtn) zoomOutBtn.addEventListener('click', function(){ setScale(state.scale - 0.25); });
  if(resetBtn) resetBtn.addEventListener('click', resetViewer);
  if(stage){
    const getPointerDistance = function(){
      const vals = Array.from(state.pointers.values());
      if(vals.length < 2) return 0;
      return Math.hypot(vals[0].x - vals[1].x, vals[0].y - vals[1].y);
    };
    const getPointerCenter = function(){
      const vals = Array.from(state.pointers.values());
      if(vals.length < 2) return null;
      return {x:(vals[0].x + vals[1].x) / 2, y:(vals[0].y + vals[1].y) / 2};
    };
    const stopNativeGesture = function(e){
      if(modalEl && modalEl.classList.contains('show')) e.preventDefault();
    };
    ['gesturestart', 'gesturechange', 'gestureend'].forEach(function(name){
      stage.addEventListener(name, stopNativeGesture, {passive:false});
      document.addEventListener(name, stopNativeGesture, {passive:false});
    });
    stage.addEventListener('wheel', function(e){ e.preventDefault(); setScale(state.scale + (e.deltaY < 0 ? 0.18 : -0.18), {x:e.clientX, y:e.clientY}); }, {passive:false});
    stage.addEventListener('dblclick', function(e){
      e.preventDefault();
      setScale(state.scale > 1.2 ? 1 : 2, {x:e.clientX, y:e.clientY});
      if(state.scale === 1){ state.x = 0; state.y = 0; applyTransform(); }
    });
    stage.addEventListener('pointerdown', function(e){
      e.preventDefault();
      state.pointers.set(e.pointerId, {x:e.clientX, y:e.clientY});
      if(stage.setPointerCapture) stage.setPointerCapture(e.pointerId);
      if(state.pointers.size === 1){
        state.dragging = true;
        state.startX = e.clientX - state.x;
        state.startY = e.clientY - state.y;
        stage.classList.add('is-dragging');
      } else if(state.pointers.size === 2){
        state.dragging = false;
        stage.classList.remove('is-dragging');
        state.gestureActive = true;
        state.startDistance = getPointerDistance() || 1;
        state.startScale = state.scale;
        state.pinchCenter = getPointerCenter();
      }
    });
    stage.addEventListener('pointermove', function(e){
      if(!state.pointers.has(e.pointerId)) return;
      e.preventDefault();
      state.pointers.set(e.pointerId, {x:e.clientX, y:e.clientY});
      if(state.pointers.size >= 2){
        const dist = getPointerDistance() || state.startDistance || 1;
        const center = getPointerCenter() || state.pinchCenter || {x:e.clientX, y:e.clientY};
        const ratio = dist / (state.startDistance || dist || 1);
        setScale(state.startScale * ratio, center);
        return;
      }
      if(!state.dragging) return;
      state.x = e.clientX - state.startX;
      state.y = e.clientY - state.startY;
      applyTransform();
    });
    const endPointer = function(e){
      if(e) e.preventDefault();
      if(e && state.pointers.has(e.pointerId)) state.pointers.delete(e.pointerId);
      if(e && stage.releasePointerCapture){ try{ stage.releasePointerCapture(e.pointerId); }catch(_err){} }
      if(state.pointers.size === 1){
        const only = Array.from(state.pointers.values())[0];
        state.dragging = true;
        state.startX = only.x - state.x;
        state.startY = only.y - state.y;
        stage.classList.add('is-dragging');
      } else {
        state.dragging = false;
        stage.classList.remove('is-dragging');
      }
      if(state.pointers.size < 2){
        state.gestureActive = false;
        state.startDistance = 0;
        state.startScale = state.scale;
        state.pinchCenter = null;
      }
    };
    stage.addEventListener('pointerup', endPointer);
    stage.addEventListener('pointercancel', endPointer);
    stage.addEventListener('pointerleave', function(e){ if(e.pointerType === 'mouse') endPointer(e); });
    const getTouchDistance = function(touches){
      if(!touches || touches.length < 2) return 0;
      const a = touches[0], b = touches[1];
      return Math.hypot(a.clientX - b.clientX, a.clientY - b.clientY);
    };
    const getTouchCenter = function(touches){
      if(!touches || touches.length < 2) return null;
      const a = touches[0], b = touches[1];
      return {x:(a.clientX + b.clientX) / 2, y:(a.clientY + b.clientY) / 2};
    };
    stage.addEventListener('touchstart', function(e){
      if(!(modalEl && modalEl.classList.contains('show'))) return;
      if(e.touches.length === 1){
        const t = e.touches[0];
        state.touchMode = true;
        state.dragging = true;
        state.startX = t.clientX - state.x;
        state.startY = t.clientY - state.y;
        stage.classList.add('is-dragging');
      } else if(e.touches.length >= 2){
        state.touchMode = true;
        state.dragging = false;
        stage.classList.remove('is-dragging');
        state.touchStartDistance = getTouchDistance(e.touches) || 1;
        state.touchStartScale = state.scale;
        state.touchCenter = getTouchCenter(e.touches);
      }
      e.preventDefault();
    }, {passive:false});
    stage.addEventListener('touchmove', function(e){
      if(!(modalEl && modalEl.classList.contains('show'))) return;
      if(e.touches.length >= 2){
        const dist = getTouchDistance(e.touches) || state.touchStartDistance || 1;
        const center = getTouchCenter(e.touches) || state.touchCenter;
        const ratio = dist / (state.touchStartDistance || dist || 1);
        setScale(state.touchStartScale * ratio, center);
      } else if(e.touches.length === 1 && state.dragging){
        const t = e.touches[0];
        state.x = t.clientX - state.startX;
        state.y = t.clientY - state.startY;
        applyTransform();
      }
      e.preventDefault();
    }, {passive:false});
    stage.addEventListener('touchend', function(e){
      if(!(modalEl && modalEl.classList.contains('show'))) return;
      if(e.touches.length === 1){
        const t = e.touches[0];
        state.dragging = true;
        state.startX = t.clientX - state.x;
        state.startY = t.clientY - state.y;
        stage.classList.add('is-dragging');
      } else {
        state.dragging = false;
        stage.classList.remove('is-dragging');
      }
      if(e.touches.length < 2){
        state.touchStartDistance = 0;
        state.touchStartScale = state.scale;
        state.touchCenter = null;
      }
      if(e.touches.length === 0){
        state.touchMode = false;
      }
      e.preventDefault();
    }, {passive:false});
    stage.addEventListener('touchcancel', function(){
      state.dragging = false;
      state.touchMode = false;
      stage.classList.remove('is-dragging');
    }, {passive:false});
  }
  if(modalEl){
    modalEl.addEventListener('shown.bs.modal', function(){
      const backdrops = document.querySelectorAll('.modal-backdrop');
      const lastBackdrop = backdrops[backdrops.length - 1];
      if(lastBackdrop){ lastBackdrop.classList.add('erp-image-viewer-backdrop'); }
      modalEl.style.zIndex = '21060';
    });
    modalEl.addEventListener('hidden.bs.modal', function(){
      resetViewer();
      img.src = '';
      modalEl.style.zIndex = '';
      document.querySelectorAll('.modal-backdrop.erp-image-viewer-backdrop').forEach(function(el){ el.classList.remove('erp-image-viewer-backdrop'); });
      unlockPageZoom();
    });
  }
  document.addEventListener('click', function(e){
    const btn = e.target.closest('.js-preview-open, [data-image-preview]');
    if(!btn) return;
    const src = btn.getAttribute('data-preview-src') || btn.getAttribute('data-image-preview');
    const title = btn.getAttribute('data-preview-title') || btn.getAttribute('data-image-title') || 'معاينة الصورة';
    if(src){ e.preventDefault(); window.openErpImageViewer(src, title); }
  });
  document.addEventListener('DOMContentLoaded', function(){ setupModalFilePreviews(document); });
  document.addEventListener('shown.bs.modal', function(e){ setupModalFilePreviews(e.target); });
})();
</script>

<div class="modal fade modal-erp erp-image-viewer-modal" id="erpImageViewerModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="erpImageViewerTitle">معاينة الصورة</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div class="erp-image-viewer-wrap" id="erpImageViewerWrap">
          <div class="erp-image-viewer-stage" id="erpImageViewerStage">
            <img id="erpImageViewerImg" src="" alt="Preview">
          </div>
        </div>
        <div class="d-flex align-items-center justify-content-between gap-2 flex-wrap mt-3">
          <div class="erp-image-viewer-hint">افتح المعاينة ثم كبّر الصورة بإصبعين أو اسحبها للتحريك داخل النافذة.</div>
          <div class="d-flex gap-2 flex-wrap">
            <button type="button" class="btn btn-outline-secondary" id="erpImageZoomOut"><i class="bi bi-zoom-out"></i> -</button>
            <button type="button" class="btn btn-outline-secondary" id="erpImageReset"><i class="bi bi-arrow-counterclockwise"></i> إعادة</button>
            <button type="button" class="btn btn-outline-secondary" id="erpImageZoomIn"><i class="bi bi-zoom-in"></i> +</button>
            <button type="button" class="btn btn-dark" data-bs-dismiss="modal"><i class="bi bi-check2"></i> تم</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
window.quickSources = window.quickSources || {};
</script>
<script>
const ajaxQuickModalEl = document.getElementById('ajaxQuickModal');
const ajaxQuickModal = ajaxQuickModalEl ? new bootstrap.Modal(ajaxQuickModalEl) : null;
const ajaxQuickForm = document.getElementById('ajaxQuickForm');
const ajaxQuickFields = document.getElementById('ajaxQuickFields');
const ajaxQuickTitle = document.getElementById('ajaxQuickModalTitle');
const ajaxQuickFeedback = document.getElementById('ajaxQuickFeedback');
const ajaxQuickSubmitBtn = document.getElementById('ajaxQuickSubmitBtn');
let ajaxQuickContext = null;

function loadQuickAccountPreview(){
  if(!ajaxQuickContext || ajaxQuickContext.entity !== 'account') return;
  const parent = document.getElementById('aq_parent_id')?.value || '';
  const type = document.getElementById('aq_type')?.value || '';
  if(!type) return;
  const params = new URLSearchParams({parent_id: parent, type});
  fetch('<?= url('/accounts/code_preview.php') ?>?'+params.toString())
    .then(r => r.json())
    .then(data => {
      if(data && data.success){
        const fld = document.getElementById('aq_code_preview');
        if(fld) fld.value = data.code || '';
      }
    }).catch(()=>{});
}

const quickSchemas = {
  account: {
    title: 'إضافة حساب جديد',
    endpoint: '<?= url('/accounts/ajax_create.php') ?>',
    submitLabel: 'حفظ الحساب',
    fields: [
      {name:'code_preview', label:'كود الحساب (تلقائي)', type:'text', col:'col-md-4', readonly:true},
      {name:'name', label:'اسم الحساب', type:'text', required:true, col:'col-md-8'},
      {name:'type', label:'النوع', type:'select', required:true, col:'col-md-4', options:[['ASSET','أصول'],['LIABILITY','خصوم'],['EQUITY','حقوق ملكية'],['REVENUE','إيرادات'],['EXPENSE','مصروفات']]},
      {name:'parent_id', label:'الحساب الأب', type:'select', col:'col-md-8', source:'accounts_optional'},
      {name:'is_cash', label:'حساب نقدي (صندوق/بنك)', type:'checkbox', col:'col-12'}
    ]
  },
  employee: {
    title: 'إضافة موظف',
    endpoint: '<?= url('/hr/ajax_employee_create.php') ?>',
    submitLabel: 'حفظ الموظف',
    fields: [
      {name:'full_name', label:'اسم الموظف', type:'text', required:true, col:'col-md-6'},
      {name:'phone', label:'الهاتف', type:'text', col:'col-md-3'},
      {name:'email', label:'البريد الإلكتروني', type:'email', col:'col-md-3'},
      {name:'job_title', label:'المسمى الوظيفي', type:'text', col:'col-md-6'},
      {name:'hire_date', label:'تاريخ التعيين', type:'date', col:'col-md-3', value:'<?= date('Y-m-d') ?>'},
      {name:'salary_monthly', label:'الراتب الشهري', type:'number', step:'0.01', col:'col-md-3', value:'0'}
    ]
  },
  customer: {
    title: 'إضافة عميل',
    endpoint: '<?= url('/tourism/ajax_customer_create.php') ?>',
    submitLabel: 'حفظ العميل',
    fields: [
      {name:'full_name', label:'اسم العميل', type:'text', required:true, col:'col-md-6'},
      {name:'phone', label:'الهاتف', type:'text', col:'col-md-3'},
      {name:'email', label:'البريد الإلكتروني', type:'email', col:'col-md-3'},
      {name:'notes', label:'ملاحظات', type:'textarea', col:'col-12'}
    ]
  },
  supplier: {
    title: 'إضافة مورد',
    endpoint: '<?= url('/tourism/ajax_supplier_create.php') ?>',
    submitLabel: 'حفظ المورد',
    fields: [
      {name:'name', label:'اسم المورد', type:'text', required:true, col:'col-md-6'},
      {name:'kind', label:'النوع', type:'select', required:true, col:'col-md-3', options:[['HOTEL','فندق'],['APARTMENT','شقق'],['CAR','سيارات'],['FLIGHT','طيران'],['TOUR','رحلات'],['UMRAH','حج/عمرة'],['OTHER','أخرى']]},
      {name:'phone', label:'الهاتف', type:'text', col:'col-md-3'},
      {name:'notes', label:'ملاحظات', type:'textarea', col:'col-12'}
    ]
  },
  service: {
    title: 'إضافة خدمة',
    endpoint: '<?= url('/tourism/ajax_service_create.php') ?>',
    submitLabel: 'حفظ الخدمة',
    fields: [
      {name:'name', label:'اسم الخدمة', type:'text', required:true, col:'col-md-6'},
      {name:'kind', label:'النوع', type:'select', required:true, col:'col-md-3', options:[['HOTEL','فندق'],['APARTMENT','شقق'],['CAR','سيارات'],['FLIGHT','طيران'],['TOUR','رحلات'],['UMRAH','حج/عمرة'],['OTHER','أخرى']]},
      {name:'default_price', label:'السعر الافتراضي', type:'number', step:'0.01', col:'col-md-3', value:'0'},
      {name:'revenue_account_id', label:'حساب الإيراد', type:'select', required:true, col:'col-12', source:'revenue_accounts'}
    ]
  }
};

function renderQuickField(field){
  const col = field.col || 'col-12';
  if(field.type === 'checkbox'){
    return `<div class="${col}"><div class="form-check mt-4"><input class="form-check-input" type="checkbox" name="${field.name}" id="aq_${field.name}" value="1"><label class="form-check-label" for="aq_${field.name}">${field.label}</label></div></div>`;
  }
  let control = '';
  if(field.type === 'textarea'){
    control = `<textarea class="form-control" name="${field.name}" id="aq_${field.name}" rows="2" ${field.required ? 'required' : ''}></textarea>`;
  } else if(field.type === 'select'){
    let options = '<option value="">اختر...</option>';
    const list = field.options || (window.quickSources && window.quickSources[field.source] ? window.quickSources[field.source] : []);
    list.forEach(opt => {
      const value = Array.isArray(opt) ? opt[0] : opt.value;
      const text = Array.isArray(opt) ? opt[1] : opt.text;
      options += `<option value="${String(value)}">${String(text)}</option>`;
    });
    control = `<select class="selectpicker" data-style="form-select" data-live-search="true" data-size="6" data-dropup-auto="false" name="${field.name}" id="aq_${field.name}" ${field.required ? 'required' : ''}>${options}</select>`;
  } else {
    const step = field.step ? ` step="${field.step}"` : '';
    const value = field.value !== undefined ? ` value="${field.value}"` : '';
    const ro = field.readonly ? ' readonly' : '';
    control = `<input class="form-control" type="${field.type || 'text'}" name="${field.name}" id="aq_${field.name}" ${field.required ? 'required' : ''}${step}${value}${ro}>`;
  }
  return `<div class="${col}"><label class="form-label" for="aq_${field.name}">${field.label}</label>${control}</div>`;
}

function openQuickCreate(btn){
  const entity = btn.dataset.entity;
  const schema = quickSchemas[entity];
  if(!schema || !ajaxQuickModal) return;
  ajaxQuickContext = {
    entity,
    endpoint: schema.endpoint,
    targetSelector: btn.dataset.target,
    textField: btn.dataset.textField || 'text',
    extraPriceTarget: btn.dataset.priceTarget || '',
    extraPriceField: btn.dataset.priceField || ''
  };
  ajaxQuickTitle.textContent = schema.title;
  ajaxQuickSubmitBtn.textContent = schema.submitLabel || 'حفظ';
  ajaxQuickFields.innerHTML = schema.fields.map(renderQuickField).join('');
  ajaxQuickFeedback.style.display = 'none';
  ajaxQuickFeedback.textContent = '';
  initSelectPickers(ajaxQuickFields);
  ajaxQuickModal.show();
  setTimeout(() => {
    const firstInput = ajaxQuickFields.querySelector('input:not([type=checkbox]), textarea, select');
    firstInput?.focus();
  }, 180);
}

document.addEventListener('click', function(e){
  const btn = e.target.closest('.js-open-ajax-modal');
  if(btn){
    e.preventDefault();
    openQuickCreate(btn);
  }
});

ajaxQuickForm?.addEventListener('submit', async function(e){
  e.preventDefault();
  if(!ajaxQuickContext) return;
  ajaxQuickSubmitBtn.disabled = true;
  ajaxQuickFeedback.style.display = 'none';
  const formData = new FormData(ajaxQuickForm);
  formData.append('_csrf', '<?= h(csrf_token()) ?>');
  try{
    const res = await fetch(ajaxQuickContext.endpoint, { method:'POST', body: formData, headers: {'X-Requested-With':'XMLHttpRequest'} });
    const data = await res.json();
    if(!res.ok || !data.success){ throw new Error(data.message || 'تعذر الحفظ'); }
    const target = document.querySelector(ajaxQuickContext.targetSelector);
    if(target){
      const opt = new Option(data.item.text, data.item.id, true, true);
      if(data.item.price !== undefined){ opt.setAttribute('data-price', data.item.price); }
      target.add(opt);
      target.value = data.item.id;
      if(window.jQuery && $(target).hasClass('selectpicker')){ $(target).selectpicker('refresh').selectpicker('val', String(data.item.id)); }
      target.dispatchEvent(new Event('change', {bubbles:true}));
    }
    ajaxQuickForm.reset();
    ajaxQuickModal.hide();
    showErpToast(data.message || 'تمت الإضافة بنجاح');
  } catch(err){
    ajaxQuickFeedback.textContent = err.message || 'حدث خطأ غير متوقع';
    ajaxQuickFeedback.style.display = 'block';
  } finally {
    ajaxQuickSubmitBtn.disabled = false;
  }
});
</script>

<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script src="https://cdn.jsdelivr.net/npm/flatpickr/dist/l10n/ar.js"></script>
<script>
  // Bootstrap-friendly date picker
  document.addEventListener('DOMContentLoaded', function(){
    if (window.flatpickr) {
      flatpickr(".datepick", {
        dateFormat: "Y-m-d",
        locale: "ar",
        allowInput: true
      });
    }
  });
</script>


<script>
window.__USER_FAVORITES__ = <?= json_encode($favoriteMap, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) ?>;
document.addEventListener('DOMContentLoaded', function(){
  const sidebar = document.getElementById('sidebar');
  const sidebarSearchInput = document.getElementById('sidebarSearchInput');
  const storageKey = 'erp_sidebar_scroll_top';
  const favoriteNavStorageKey = 'erp_sidebar_favorite_nav';
  const favoriteMap = window.__USER_FAVORITES__ || {};
  const favoritesSection = document.getElementById('favoritesSec');
  const favoritesAccordionItem = favoritesSection ? favoritesSection.closest('.accordion-item') : null;
  const favoritesSubmenu = favoritesSection ? favoritesSection.querySelector('.submenu') : null;
  const favoritesToggle = favoritesAccordionItem ? favoritesAccordionItem.querySelector('.accordion-button') : null;

  const normalizeText = (s) => (s || '')
    .toString()
    .toLowerCase()
    .replace(/[أإآ]/g,'ا')
    .replace(/ة/g,'ه')
    .replace(/ى/g,'ي')
    .replace(/\s+/g,' ')
    .trim();

  const normalizeUrl = (url) => {
    const cleaned = (url || '').toString().replace(location.origin, '').replace(/\/+$/, '');
    return cleaned || '/';
  };

  const favoriteCount = () => favoritesSubmenu ? favoritesSubmenu.querySelectorAll('.favorite-link-row').length : 0;

  const syncFavoritesVisibility = () => {
    if(!favoritesAccordionItem || !favoritesSection || !favoritesToggle) return;
    const hasItems = favoriteCount() > 0;
    favoritesAccordionItem.style.display = hasItems ? '' : 'none';
    if(hasItems) {
      favoritesSection.classList.add('show');
      favoritesToggle.classList.remove('collapsed');
      favoritesToggle.setAttribute('aria-expanded', 'true');
    } else {
      favoritesSection.classList.remove('show');
      favoritesToggle.classList.add('collapsed');
      favoritesToggle.setAttribute('aria-expanded', 'false');
    }
  };

  const setButtonState = (btn, active) => {
    if(!btn) return;
    const icon = btn.querySelector('i');
    btn.classList.toggle('active', !!active);
    btn.setAttribute('aria-label', active ? 'إزالة من المفضلة' : 'إضافة إلى المفضلة');
    btn.setAttribute('title', active ? 'إزالة من المفضلة' : 'إضافة إلى المفضلة');
    if(icon) icon.className = active ? 'bi bi-star-fill' : 'bi bi-star';
  };

  const removeFavoriteRow = (normalized) => {
    if(!favoritesSubmenu) return;
    favoritesSubmenu.querySelectorAll('.favorite-link-row').forEach(function(row){
      const rowUrl = normalizeUrl(row.getAttribute('data-favorite-url') || row.querySelector('.sidebar-fav-btn')?.getAttribute('data-page-url') || '');
      if(rowUrl === normalized) row.remove();
    });
    syncFavoritesVisibility();
  };

  const createFavoriteRow = (normalized, title) => {
    if(!favoritesSubmenu) return;
    const row = document.createElement('div');
    row.className = 'sidebar-link-row favorite-link-row';
    row.setAttribute('data-favorite-url', normalized);

    const link = document.createElement('a');
    link.className = 'slink';
    if(normalized === normalizeUrl(location.pathname)) link.classList.add('active');
    link.href = normalized;
    link.innerHTML = '<span class="sicon"><i class="bi bi-star"></i></span><span class="slabel"></span>';
    link.querySelector('.slabel').textContent = title || 'صفحة مفضلة';

    const btn = document.createElement('button');
    btn.type = 'button';
    btn.className = 'sidebar-fav-btn active sidebar-fav-btn-favorite';
    btn.setAttribute('data-page-url', normalized);
    btn.innerHTML = '<i class="bi bi-star-fill"></i>';
    setButtonState(btn, true);
    attachFavoriteHandler(btn, link);

    row.appendChild(link);
    row.appendChild(btn);
    favoritesSubmenu.insertBefore(row, favoritesSubmenu.firstChild);
    syncFavoritesVisibility();
  };

  const upsertFavoriteRow = (normalized, title) => {
    if(!favoritesSubmenu) return;
    const existing = Array.from(favoritesSubmenu.querySelectorAll('.favorite-link-row')).find(function(row){
      return normalizeUrl(row.getAttribute('data-favorite-url') || '') === normalized;
    });
    if(existing) {
      const label = existing.querySelector('.slabel');
      if(label && title) label.textContent = title;
      const btn = existing.querySelector('.sidebar-fav-btn');
      if(btn) {
        btn.setAttribute('data-page-url', normalized);
        setButtonState(btn, true);
      }
      syncFavoritesVisibility();
      return;
    }
    createFavoriteRow(normalized, title);
  };

  const updateAllButtons = (normalized, active) => {
    document.querySelectorAll('.sidebar-fav-btn[data-page-url]').forEach(function(btn){
      if(normalizeUrl(btn.getAttribute('data-page-url') || '') === normalized) {
        setButtonState(btn, active);
      }
    });
  };

  async function toggleFavorite(normalized, title) {
    const res = await fetch('<?= url('/app/toggle_favorite.php') ?>', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
      body: JSON.stringify({ page_url: normalized, page_title: title })
    });
    const data = await res.json();
    if(!data || !data.ok) throw new Error(data && data.message ? data.message : 'تعذر تحديث المفضلة');
    return data;
  }

  function attachFavoriteHandler(btn, link){
    if(!btn || btn.dataset.favoriteBound === '1') return;
    btn.dataset.favoriteBound = '1';
    btn.addEventListener('click', async function(e){
      e.preventDefault();
      e.stopPropagation();
      const normalized = normalizeUrl(btn.getAttribute('data-page-url') || (link ? link.getAttribute('href') : ''));
      const title = ((link && link.querySelector('.slabel') ? link.querySelector('.slabel').textContent : '') || (link ? link.textContent : '') || '').trim() || 'صفحة مفضلة';
      const beforeScroll = sidebar ? sidebar.scrollTop : 0;
      btn.disabled = true;
      try {
        const data = await toggleFavorite(normalized, title);
        const active = !!data.active;
        if(active) {
          favoriteMap[normalized] = title;
          upsertFavoriteRow(normalized, title);
        } else {
          delete favoriteMap[normalized];
          removeFavoriteRow(normalized);
        }
        updateAllButtons(normalized, active);
        if(sidebar) sidebar.scrollTop = beforeScroll;
      } catch (err) {
        alert(err.message || 'تعذر تحديث المفضلة');
      } finally {
        btn.disabled = false;
      }
    });
  }

  if(sidebar){
    const savedScroll = sessionStorage.getItem(storageKey);
    if(savedScroll !== null){
      sidebar.scrollTop = parseInt(savedScroll, 10) || 0;
    }
    sidebar.addEventListener('scroll', function(){
      sessionStorage.setItem(storageKey, String(sidebar.scrollTop || 0));
    }, { passive:true });
    sidebar.querySelectorAll('a').forEach(function(link){
      link.addEventListener('click', function(){
        sessionStorage.setItem(storageKey, String(sidebar.scrollTop || 0));
        const normalizedHref = normalizeUrl(link.getAttribute('href') || '');
        if(link.closest('#favoritesSec') && normalizedHref && normalizedHref !== '#') {
          sessionStorage.setItem(favoriteNavStorageKey, normalizedHref);
        } else {
          sessionStorage.removeItem(favoriteNavStorageKey);
        }
      });
    });
  }

  const favoriteNavigatedToCurrentPage = sessionStorage.getItem(favoriteNavStorageKey) === normalizeUrl(location.pathname);
  if(favoriteNavigatedToCurrentPage) {
    sessionStorage.removeItem(favoriteNavStorageKey);
    document.querySelectorAll('#sidebarAccordion .accordion-collapse').forEach(function(section){
      if(section.id !== 'favoritesSec') {
        section.classList.remove('show');
      }
    });
    document.querySelectorAll('#sidebarAccordion .accordion-button').forEach(function(btn){
      const target = btn.getAttribute('data-bs-target') || '';
      if(target === '#favoritesSec') {
        btn.classList.remove('collapsed');
        btn.setAttribute('aria-expanded', 'true');
      } else {
        btn.classList.add('collapsed');
        btn.setAttribute('aria-expanded', 'false');
      }
    });
    if(favoritesSection) favoritesSection.classList.add('show');
  }

  if(sidebarSearchInput && sidebar){
    const searchableRows = Array.from(sidebar.querySelectorAll('.submenu a.slink, .sidebar-home-link'));
    sidebarSearchInput.addEventListener('input', function(){
      const q = normalizeText(this.value);
      searchableRows.forEach(function(link){
        const row = link.closest('.sidebar-link-row') || link;
        const text = normalizeText(link.textContent || '');
        row.classList.toggle('sidebar-filter-hidden', !!q && !text.includes(q));
      });
    });
  }

  const submenuLinks = Array.from(document.querySelectorAll('.submenu > a.slink'));
  submenuLinks.forEach(function(link){
    if(link.closest('#favoritesSec')) return;
    const hrefAttr = link.getAttribute('href') || '';
    if(!hrefAttr || hrefAttr === '#') return;
    const normalized = normalizeUrl(hrefAttr);
    const row = document.createElement('div');
    row.className = 'sidebar-link-row';
    link.parentNode.insertBefore(row, link);
    row.appendChild(link);

    const btn = document.createElement('button');
    btn.type = 'button';
    btn.className = 'sidebar-fav-btn';
    btn.setAttribute('data-page-url', normalized);
    btn.innerHTML = '<i class="bi bi-star"></i>';
    setButtonState(btn, Object.prototype.hasOwnProperty.call(favoriteMap, normalized));
    attachFavoriteHandler(btn, link);

    row.appendChild(btn);
  });

  document.querySelectorAll('#favoritesSec .sidebar-fav-btn[data-page-url]').forEach(function(btn){
    const row = btn.closest('.favorite-link-row');
    const link = row ? row.querySelector('a.slink') : null;
    attachFavoriteHandler(btn, link);
  });

  syncFavoritesVisibility();
});
</script>

<script>
window.__SMART_NAV__ = <?= json_encode($smartNav, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) ?>;
document.addEventListener('DOMContentLoaded', function(){
  const input = document.getElementById('smartSearchInput');
  const panel = document.getElementById('smartSearchPanel');
  if(!input || !panel || !Array.isArray(window.__SMART_NAV__)) return;

  const normalize = (s) => (s || '')
    .toString()
    .toLowerCase()
    .replace(/[أإآ]/g,'ا')
    .replace(/ة/g,'ه')
    .replace(/ى/g,'ي')
    .replace(/\s+/g,' ')
    .trim();

  const items = window.__SMART_NAV__.map(item => ({
    ...item,
    haystack: normalize([item.title].concat(item.keywords || []).join(' '))
  }));

  let activeIndex = -1;
  let current = [];

  function score(item, q){
    if(!q) return 0;
    const title = normalize(item.title);
    if(title === q) return 120;
    if(title.startsWith(q)) return 90;
    if(title.includes(q)) return 70;
    if(item.haystack.includes(q)) return 50;
    const parts = q.split(' ').filter(Boolean);
    let matched = 0;
    for(const p of parts){ if(item.haystack.includes(p)) matched++; }
    return matched ? 20 + matched * 10 : 0;
  }

  function render(list){
    current = list.slice(0, 8);
    activeIndex = -1;
    if(!current.length){
      panel.innerHTML = '<div class="smart-search-empty">لا توجد صفحات مطابقة.</div>';
      panel.classList.add('show');
      return;
    }
    panel.innerHTML = current.map((item, idx) => `
      <a class="smart-search-item" href="${item.url}" data-index="${idx}">
        <div class="meta">
          <div class="title">${item.title}</div>
          <div class="hint">${(item.keywords || []).slice(0,4).join(' • ')}</div>
        </div>
        <i class="bi bi-arrow-up-left go"></i>
      </a>
    `).join('');
    panel.classList.add('show');
  }

  function runSearch(){
    const q = normalize(input.value);
    if(!q){
      panel.classList.remove('show');
      panel.innerHTML = '';
      return;
    }
    const ranked = items
      .map(item => ({item, s: score(item, q)}))
      .filter(x => x.s > 0)
      .sort((a,b) => b.s - a.s || a.item.title.localeCompare(b.item.title))
      .map(x => x.item);
    render(ranked);
  }

  input.addEventListener('input', runSearch);
  input.addEventListener('focus', function(){ if(input.value.trim()) runSearch(); });
  document.addEventListener('click', function(e){
    if(!e.target.closest('#smartSearch')) panel.classList.remove('show');
  });

  input.addEventListener('keydown', function(e){
    if(!panel.classList.contains('show') || !current.length) return;
    const rows = Array.from(panel.querySelectorAll('.smart-search-item'));
    if(e.key === 'ArrowDown'){
      e.preventDefault();
      activeIndex = (activeIndex + 1) % rows.length;
    } else if(e.key === 'ArrowUp'){
      e.preventDefault();
      activeIndex = (activeIndex - 1 + rows.length) % rows.length;
    } else if(e.key === 'Enter'){
      e.preventDefault();
      const target = rows[activeIndex] || rows[0];
      if(target) window.location.href = target.getAttribute('href');
      return;
    } else if(e.key === 'Escape'){
      panel.classList.remove('show');
      return;
    } else {
      return;
    }
    rows.forEach((row, idx) => row.classList.toggle('active', idx === activeIndex));
  });
});
</script>

</body>
</html>
<?php } ?>