<!doctype html>
<html lang="ar" dir="rtl" data-theme="dim">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="csrf-token" content="{{ csrf_token() }}">
  <title>الإعدادات</title>

  <style>
    /* =========================
       Theme Variables (Default = DIM)
       ========================= */
    :root{ /* default = dim */
      --bg:#121826;
      --surface:#101827;
      --card:#151e30;
      --card2:#0f1a33;

      --text:#e5e7eb;
      --muted:#9ca3af;

      --border:rgba(255,255,255,.10);
      --border2:rgba(255,255,255,.14);
      --shadow:0 18px 40px rgba(0,0,0,.22);

      --primary:#6366f1;
      --primary2:#4f46e5;
      --success:#22c55e;
      --warning:#f59e0b;
      --danger:#ef4444;

      --input:#0b1327;
      --inputBorder:rgba(255,255,255,.12);
      --inputFocus:rgba(99,102,241,.35);

      --tableHead:rgba(255,255,255,.05);
      --rowHover:rgba(99,102,241,.08);
    }

    /* ✅ Dark (أغمق) */
    html[data-theme="dark"]{
      --bg:#070b14;
      --surface:#0b1220;
      --card:#0f172a;
      --card2:#0b1327;
    }

    /* ✅ Light (أبيض صافي مثل التصميم القديم) */
    html[data-theme="light"]{
      --bg:#ffffff;          /* ✅ أبيض بالكامل */
      --surface:#ffffff;
      --card:#ffffff;
      --card2:#ffffff;

      --text:#111827;
      --muted:#6b7280;

      --border:rgba(17,24,39,.10);
      --border2:rgba(17,24,39,.14);
      --shadow:0 12px 28px rgba(0,0,0,.10);

      --primary:#111827;     /* نفس روح القديم */
      --primary2:#111827;

      --success:#16a34a;
      --warning:#d97706;
      --danger:#dc2626;

      --input:#ffffff;
      --inputBorder:rgba(17,24,39,.14);
      --inputFocus:rgba(17,24,39,.12);

      --tableHead:rgba(17,24,39,.03);
      --rowHover:rgba(17,24,39,.03);
    }

    *{box-sizing:border-box}

    body{
      font-family:Arial, sans-serif;
      margin:0;
      background:var(--bg); /* ✅ لا تدرج في الفاتح */
      color:var(--text);
      padding:22px;
    }

    /* ✅ لو الثيم dim/dark نخلي خلفية لطيفة (اختياري) */
    html[data-theme="dim"] body,
    html[data-theme="dark"] body{
      background:linear-gradient(180deg, var(--bg), var(--bg));
    }

    .container{max-width:1200px;margin:0 auto}

    /* Page header */
    .pageHeader{
      background:linear-gradient(180deg, rgba(255,255,255,.04), rgba(255,255,255,.02));
      border:1px solid var(--border);
      border-radius:18px;
      box-shadow:var(--shadow);
      padding:16px 16px 12px;
      margin-bottom:14px;
    }

    /* ✅ الفاتح يكون Header أبيض مع رمادي خفيف */
    html[data-theme="light"] .pageHeader{
      background:#ffffff;
      border-color:rgba(17,24,39,.10);
      box-shadow:0 12px 28px rgba(0,0,0,.08);
    }

    .headerTop{
      display:flex;align-items:flex-start;justify-content:space-between;gap:12px;flex-wrap:wrap
    }
    .title{font-weight:900;font-size:18px;letter-spacing:.2px}
    .subtitle{color:var(--muted);font-size:13px;margin-top:6px;line-height:1.6}

    .navRow{
      display:flex;gap:8px;flex-wrap:nowrap;overflow:auto;max-width:100%;
      padding-top:10px;padding-bottom:6px;-webkit-overflow-scrolling:touch;align-items:center
    }
    .navRow > *{flex:0 0 auto; white-space:nowrap;}

    /* Buttons */
    .btn{
      padding:10px 12px;border-radius:12px;border:1px solid transparent;
      cursor:pointer;font-weight:900;font-size:13px;line-height:1;
      display:inline-flex;align-items:center;gap:8px;text-decoration:none;
      transition:transform .05s ease, opacity .15s ease, border-color .15s ease;
      user-select:none;
    }
    .btn:active{transform:translateY(1px)}
    .btnPrimary{
      background:linear-gradient(180deg, var(--primary), var(--primary2));
      color:#fff;border-color:rgba(255,255,255,.10)
    }
    html[data-theme="light"] .btnPrimary{
      background:#111827; color:#fff; border-color:rgba(17,24,39,.12);
    }

    .btnGhost{
      background:rgba(255,255,255,.03);
      color:var(--text);
      border-color:var(--border2)
    }
    html[data-theme="light"] .btnGhost{
      background:#ffffff;
      border-color:rgba(17,24,39,.12);
    }
    .btnGhost:hover{border-color:rgba(255,255,255,.18)}
    html[data-theme="light"] .btnGhost:hover{border-color:rgba(17,24,39,.20)}

    .btnDanger{
      background:rgba(239,68,68,.14);
      color:#fff;border-color:rgba(239,68,68,.35)
    }
    html[data-theme="light"] .btnDanger{
      background:#ffffff;
      color:#dc2626;
      border-color:rgba(220,38,38,.25);
    }
    .btnDanger:hover{opacity:.95}

    .activeTab{
      background:rgba(99,102,241,.20);
      border-color:rgba(99,102,241,.55);
      color:#fff;
    }
    html[data-theme="light"] .activeTab{
      background:rgba(17,24,39,.05);
      border-color:rgba(17,24,39,.18);
      color:#111827;
    }

    /* Cards */
    .card{
      background:linear-gradient(180deg, rgba(255,255,255,.035), rgba(255,255,255,.02));
      border:1px solid var(--border);
      border-radius:18px;
      box-shadow:var(--shadow);
      padding:16px;
      margin-bottom:14px;
    }
    html[data-theme="light"] .card{
      background:#ffffff;
      border-color:rgba(17,24,39,.10);
      box-shadow:0 12px 28px rgba(0,0,0,.08);
    }

    .cardTitle{
      display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;
      margin-bottom:10px;
    }
    .cardTitle h3{margin:0;font-size:15px;font-weight:900}
    .cardHint{color:var(--muted);font-size:12px;font-weight:900}

    /* Alerts */
    .alert{padding:12px;border-radius:14px;border:1px solid;font-weight:900;margin-bottom:14px}
    .alert.err{background:rgba(239,68,68,.14);border-color:rgba(239,68,68,.35);color:#fff}
    .alert.ok{background:rgba(34,197,94,.14);border-color:rgba(34,197,94,.35);color:#fff}
    html[data-theme="light"] .alert.err{color:#991b1b;background:#fef2f2;border-color:#fecaca}
    html[data-theme="light"] .alert.ok{color:#166534;background:#ecfdf3;border-color:#bbf7d0}

    /* Forms */
    label{display:block;font-size:12px;color:var(--muted);font-weight:900;margin-bottom:6px}
    input, select{
      width:100%;
      padding:11px 12px;
      border:1px solid var(--inputBorder);
      border-radius:12px;
      outline:none;
      font-size:14px;
      background:var(--input);
      color:var(--text);
    }
    input:focus, select:focus{
      border-color:rgba(99,102,241,.55);
      box-shadow:0 0 0 3px var(--inputFocus);
    }
    html[data-theme="light"] input:focus,
    html[data-theme="light"] select:focus{
      border-color:rgba(17,24,39,.22);
      box-shadow:0 0 0 3px rgba(17,24,39,.08);
    }

    .grid{
      display:grid;
      grid-template-columns: 1.2fr 260px auto;
      gap:10px;
      align-items:end;
    }
  @media (max-width: 768px){
  .grid{grid-template-columns:1fr}
  body{padding:16px}
}

    /* Table */
    .tableWrap{
      overflow:auto;
      border-radius:14px;
      border:1px solid var(--border);
      background:rgba(0,0,0,.10);
      margin-top:12px;
    }
    html[data-theme="light"] .tableWrap{
      background:#ffffff;
      border-color:rgba(17,24,39,.10);
    }

    table{
      width:100%;
      border-collapse:separate;
      border-spacing:0;
      min-width:820px;
    }
    thead th{
      position:sticky;top:0;z-index:2;
      background:var(--tableHead);
      border-bottom:1px solid var(--border);
      padding:12px 12px;
      font-weight:900;
      font-size:13px;
      white-space:nowrap;
      text-align:right;
    }
    tbody td{
      padding:12px 12px;
      border-bottom:1px solid rgba(255,255,255,.06);
      font-size:13px;
      vertical-align:middle;
    }
    html[data-theme="light"] tbody td{
      border-bottom:1px solid rgba(17,24,39,.08);
    }
    tbody tr:hover td{background:var(--rowHover)}

    .muted{color:var(--muted);font-weight:900;font-size:12px}

    /* Badges */
    .badge{
      display:inline-flex;align-items:center;gap:6px;
      padding:6px 10px;border-radius:999px;font-weight:900;font-size:12px;
      border:1px solid rgba(255,255,255,.10);
      background:rgba(255,255,255,.03);
      color:var(--text);
    }
    html[data-theme="light"] .badge{
      border-color:rgba(17,24,39,.12);
      background:rgba(17,24,39,.03);
      color:var(--text);
    }
    .badge.on{border-color:rgba(34,197,94,.40);background:rgba(34,197,94,.14)}
    .badge.off{border-color:rgba(239,68,68,.40);background:rgba(239,68,68,.14)}

    /* Inline actions */
    .rowActions{display:flex;gap:8px;flex-wrap:wrap;justify-content:flex-end}
    .miniBtn{
      padding:8px 10px;border-radius:12px;border:1px solid var(--border2);
      background:rgba(255,255,255,.03);color:var(--text);font-weight:900;cursor:pointer;font-size:12px;
    }
    html[data-theme="light"] .miniBtn{
      background:#ffffff;
      border-color:rgba(17,24,39,.12);
    }
    .miniBtn:hover{border-color:rgba(255,255,255,.18)}
    html[data-theme="light"] .miniBtn:hover{border-color:rgba(17,24,39,.20)}

    .miniBtnDanger{
      padding:8px 10px;border-radius:12px;border:1px solid rgba(239,68,68,.35);
      background:rgba(239,68,68,.14);color:#fff;font-weight:900;cursor:pointer;font-size:12px;
    }

    .logoPreview{
      height:64px;max-width:240px;object-fit:contain;
      border:1px solid var(--border);border-radius:12px;padding:8px;background:rgba(255,255,255,.03);
      display:block;margin-top:10px;
    }
    html[data-theme="light"] .logoPreview{
      background:#fff;border-color:rgba(17,24,39,.10);
    }

    .tabsWrap{display:flex;gap:8px;flex-wrap:wrap;}
  
    /* =========================
       Modal (Restore)
       ========================= */
    .btnWarning{background:var(--warning);color:#111827;border:0}
    .btnWarning:hover{filter:brightness(.95)}
    html[data-theme="light"] .btnWarning{color:#111827}

    .miniBtnWarning{
      padding:8px 10px;border-radius:12px;border:1px solid rgba(245,158,11,.45);
      background:rgba(245,158,11,.14);color:var(--text);font-weight:900;cursor:pointer;font-size:12px;
    }
    html[data-theme="light"] .miniBtnWarning{color:#111827;border-color:rgba(217,119,6,.35);background:rgba(217,119,6,.12)}
    .miniBtnWarning:hover{filter:brightness(.98)}

    .modalWrap{
      position:fixed; inset:0;
      background:rgba(0,0,0,.55);
      display:flex; align-items:center; justify-content:center;
      padding:16px;
      z-index:9999;
    }
    .modalCard{
      width:min(520px, 100%);
      background:rgba(17,24,39,.92);
      border:1px solid rgba(255,255,255,.08);
      border-radius:16px;
      padding:14px;
      box-shadow:0 10px 40px rgba(0,0,0,.5);
    }
    html[data-theme="light"] .modalCard{
      background:#fff;border-color:rgba(17,24,39,.12);
      box-shadow:0 10px 28px rgba(0,0,0,.12);
    }
/* Action buttons in backup table */
.actBtns{
  display:flex;
  gap:8px;
  flex-wrap:nowrap;
  justify-content:flex-end;
  align-items:center;
  white-space:nowrap;
}
.actBtns .btn{
  padding:8px 12px;
  border-radius:12px;
  font-weight:800;
}

/* Backup table buttons colors */
.btnDownload{
  background:rgba(255,255,255,.08);
  border:1px solid rgba(255,255,255,.14);
  color:#fff;
}
.btnRestore{
  background:#f59e0b;
  color:#111827;
  border:0;
}
.btnDelete{
  background:#7f1d1d;
  border:1px solid rgba(255,255,255,.10);
  color:#fff;
}
.btnDownload:hover,.btnRestore:hover,.btnDelete:hover{ filter:brightness(.95); }

</style>

  <!-- ✅ Apply saved theme ASAP (avoid flash) -->
  
  <!-- ✅ Restore Modal -->
  <div id="restoreModal" class="modalWrap" style="display:none">
    <div class="modalCard">
      <div style="display:flex;align-items:center;justify-content:space-between;gap:10px">
        <div>
          <div style="font-weight:900">استعادة النسخة الاحتياطية</div>
          <div class="muted" id="restoreFileName" style="margin-top:4px"></div>
        </div>
        <button id="restoreClose" class="btn btnGhost" type="button">إغلاق</button>
      </div>

      <div style="margin-top:12px">
        <label>كلمة مرور الأدمن للتأكيد</label>
        <input id="restorePassword" type="password" placeholder="اكتب كلمة المرور">
        <div class="muted" style="margin-top:8px;line-height:1.7">
          تنبيه: سيتم استبدال قاعدة البيانات بمحتوى النسخة.
        </div>
      </div>

      <div style="display:flex;justify-content:flex-end;gap:8px;margin-top:14px;flex-wrap:wrap">
        <button id="restoreCancel" class="btn btnGhost" type="button">إلغاء</button>
        <button id="restoreConfirm" class="btn btnWarning" type="button">تأكيد الاستعادة</button>
      </div>

      <div id="restoreMsg" class="muted" style="margin-top:10px"></div>
    </div>
  </div>


<script>

// =========================
// DB Backups UI (AJAX)
// =========================
document.addEventListener('DOMContentLoaded', function(){
  const csrf = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';
  const rowsEl = document.getElementById('backupRows');
  const msgEl  = document.getElementById('backupMsg');
  const purgeMsgEl = document.getElementById('purgeMsg');

  function fmtSize(bytes){
    if(bytes == null) return '-';
    const b = Number(bytes);
    if(!isFinite(b)) return '-';
    if(b < 1024) return b + ' B';
    if(b < 1024*1024) return (b/1024).toFixed(1) + ' KB';
    if(b < 1024*1024*1024) return (b/1024/1024).toFixed(1) + ' MB';
    return (b/1024/1024/1024).toFixed(2) + ' GB';
  }

  function fmtDate(ts){
    if(!ts) return '-';
    // ts from PHP is unix seconds
    const d = new Date(Number(ts) * 1000);
    return d.toLocaleString('ar-SA');
  }

  function setMsg(el, text, isError){
    if(!el) return;
    el.textContent = text || '';
    el.style.color = isError ? 'var(--danger)' : 'var(--muted)';
    if(!text) el.style.color = 'var(--muted)';
  }

  async function fetchJson(url, opts){
    const res = await fetch(url, opts);
    const ct = res.headers.get('content-type') || '';
    let data = null;
    if(ct.includes('application/json')){
      data = await res.json().catch(()=>null);
    }
    if(!res.ok){
      const msg = (data && (data.message || data.error)) ? (data.message || data.error) : (res.status + ' ' + res.statusText);
      throw new Error(msg);
    }
    return data;
  }

  
  // Restore Modal controls
  const restoreModal = document.getElementById('restoreModal');
  const restoreFileNameEl = document.getElementById('restoreFileName');
  const restorePassEl = document.getElementById('restorePassword');
  const restoreMsgEl = document.getElementById('restoreMsg');
  const restoreCloseBtn = document.getElementById('restoreClose');
  const restoreCancelBtn = document.getElementById('restoreCancel');
  const restoreConfirmBtn = document.getElementById('restoreConfirm');

  let restoreUrlPending = null;

  function openRestore(url, fileName){
    restoreUrlPending = url;
    if(restoreFileNameEl) restoreFileNameEl.textContent = fileName ? ('الملف: ' + fileName) : '';
    if(restorePassEl) restorePassEl.value = '';
    setMsg(restoreMsgEl, '', false);
    if(restoreModal) restoreModal.style.display = 'flex';
    setTimeout(() => { restorePassEl?.focus(); }, 50);
  }
  function closeRestore(){
    restoreUrlPending = null;
    if(restoreModal) restoreModal.style.display = 'none';
  }
  restoreCloseBtn?.addEventListener('click', closeRestore);
  restoreCancelBtn?.addEventListener('click', closeRestore);
  restoreModal?.addEventListener('click', function(ev){
    if(ev.target === restoreModal) closeRestore();
  });

  async function doRestore(){
    if(!restoreUrlPending) return;
    const pass = (restorePassEl?.value || '').trim();
    if(!pass){
      setMsg(restoreMsgEl, 'اكتب كلمة المرور أولاً.', true);
      return;
    }
    // تأكيد إضافي
    if(!confirm('تأكيد الاستعادة؟ سيتم استبدال قاعدة البيانات بالكامل.')) return;

    try{
      setMsg(restoreMsgEl, 'جاري الاستعادة... لا تغلق الصفحة.', false);
      await fetchJson(restoreUrlPending, {
        method: 'POST',
        headers: {
          'X-CSRF-TOKEN': csrf,
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ password: pass })
      });
      setMsg(restoreMsgEl, 'تمت الاستعادة بنجاح. سيتم تحديث الصفحة.', false);
      setTimeout(() => { location.reload(); }, 900);
    }catch(e){
      setMsg(restoreMsgEl, 'فشل الاستعادة: ' + e.message, true);
    }
  }
  restoreConfirmBtn?.addEventListener('click', doRestore);


function render(files){
    if(!rowsEl) return;

    if(!files || !files.length){
      rowsEl.innerHTML = `<tr><td colspan="4" class="muted" style="padding:14px;text-align:center">لا توجد نسخ حالياً</td></tr>`;
      return;
    }

    rowsEl.innerHTML = files.map(f => {
      const name = f.name;
      const dl = `{{ url('/dashboard/settings/db-backups/download') }}/${encodeURIComponent(name)}`;
      const del = `{{ url('/dashboard/settings/db-backups/delete') }}/${encodeURIComponent(name)}`;
      const restore = `{{ url('/dashboard/settings/db-backups/restore') }}/${encodeURIComponent(name)}`;

      return `
        <tr>
          <td style="font-weight:900">${name}</td>
          <td>${fmtSize(f.size)}</td>
          <td>${fmtDate(f.time)}</td>
          <td>
            <div style="display:flex;gap:8px;flex-wrap:wrap;justify-content:flex-start">
              <a class="miniBtn" href="${dl}">Download</a>
              <button class="miniBtnWarning" data-restore="${restore}" data-file="${name}" type="button">Restore</button>
              <button class="miniBtnDanger" data-del="${del}" type="button">Delete</button>
            </div>
          </td>
        </tr>
      `;
    }).join('');
  }

  async function load(){
    if(!rowsEl) return; // إذا مو في تبويب الشركة
    setMsg(msgEl, 'جاري التحميل...', false);
    try{
      const data = await fetchJson(`{{ route('db.backups.index') }}`);
      render(data.files || []);
      setMsg(msgEl, '', false);
    }catch(e){
      render([]);
      setMsg(msgEl, 'تعذر تحميل النسخ: ' + e.message, true);
    }
  }

  async function createBackup(){
    setMsg(msgEl, 'جاري إنشاء النسخة...', false);
    try{
      const data = await fetchJson(`{{ route('db.backups.create') }}`, {
        method: 'POST',
        headers: {
          'X-CSRF-TOKEN': csrf,
          'Accept': 'application/json'
        }
      });
      render((data && data.files) ? data.files : []);
      setMsg(msgEl, 'تم إنشاء النسخة: ' + (data.file || ''), false);
    }catch(e){
      setMsg(msgEl, 'فشل إنشاء النسخة: ' + e.message, true);
    }
  }

  async function deleteBackup(url){
    if(!confirm('متأكد من حذف النسخة؟')) return;
    setMsg(msgEl, 'جاري الحذف...', false);
    try{
      const data = await fetchJson(url, {
        method: 'DELETE',
        headers: {
          'X-CSRF-TOKEN': csrf,
          'Accept': 'application/json'
        }
      });
      render((data && data.files) ? data.files : []);
      setMsg(msgEl, 'تم حذف النسخة.', false);
    }catch(e){
      setMsg(msgEl, 'فشل الحذف: ' + e.message, true);
    }
  }

  async function purgeAll(){
    const pass = document.getElementById('purgePassword')?.value || '';
    if(!pass){
      setMsg(purgeMsgEl, 'اكتب كلمة المرور أولاً.', true);
      return;
    }
    const ok = confirm('تأكيد نهائي: سيتم حذف كل بيانات الشركة. هل أنت متأكد؟');
    if(!ok) return;

    setMsg(purgeMsgEl, 'جاري تنفيذ الحذف...', false);
    try{
      await fetchJson(`{{ route('company.data.purge') }}`, {
        method: 'POST',
        headers: {
          'X-CSRF-TOKEN': csrf,
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ password: pass })
      });
      setMsg(purgeMsgEl, 'تم تنفيذ الحذف.', false);
    }catch(e){
      setMsg(purgeMsgEl, 'تعذر التنفيذ: ' + e.message, true);
    }
  }

  // bind
  document.getElementById('btnRefreshBackups')?.addEventListener('click', load);
  document.getElementById('btnCreateBackup')?.addEventListener('click', createBackup);
  document.getElementById('btnPurge')?.addEventListener('click', purgeAll);

  // delegate row buttons
  document.addEventListener('click', function(ev){
    const t = ev.target;
    if(!(t instanceof HTMLElement)) return;

    const delUrl = t.getAttribute('data-del');
    if(delUrl){
      deleteBackup(delUrl);
      return;
    }

    const restoreUrl = t.getAttribute('data-restore');
    if(restoreUrl){
      const fileName = t.getAttribute('data-file') || '';
      openRestore(restoreUrl, fileName);
      return;
    }
  });
  // initial load if tab company
  load();
});
    (function(){
      const themes = ["light","dim","dark"];
      const key = "ui_theme";
      const saved = localStorage.getItem(key);
      const t = (saved && themes.includes(saved)) ? saved : "dim";
      document.documentElement.setAttribute("data-theme", t);
    })();
  </script>

  <script>
    // ✅ Theme toggle (زر واحد: مريح/فاتح/غامق)
    document.addEventListener('DOMContentLoaded', () => {
      const themes = ['light','dim','dark'];
      const key = 'ui_theme';
      const html = document.documentElement;
      const btn  = document.getElementById('themeBtn');

      function label(t){
        if(t === 'light') return '☀️ فاتح';
        if(t === 'dark')  return '🌙 غامق';
        return '🌗 مريح';
      }

      function apply(t){
        html.setAttribute('data-theme', t);
        try{ localStorage.setItem(key, t); }catch(e){}
        if(btn) btn.textContent = '🎨 ' + label(t);
      }

      // initial sync (ASAP script already set data-theme)
      const saved = (function(){ try{ return localStorage.getItem(key); }catch(e){ return null; } })();
      const cur = (saved && themes.includes(saved)) ? saved : (html.getAttribute('data-theme') || 'dim');
      apply(cur);

      if(btn){
        btn.addEventListener('click', () => {
          const now = html.getAttribute('data-theme') || 'dim';
          const idx = themes.indexOf(now);
          const next = themes[(idx + 1) % themes.length];
          apply(next);
        });
      }
    });
  </script>
</head>
<body>
<div class="container">

  @php
    $tab = request()->get('tab', 'suppliers'); // suppliers | items | company
    $isAdmin = auth()->check() && ((auth()->user()->role ?? 'user') === 'admin');
    if(!$isAdmin && $tab === 'company'){ $tab = 'suppliers'; }

    $company = \Illuminate\Support\Facades\DB::table('company_settings')->where('id', 1)->first();
  @endphp

  <div class="pageHeader">
    <div class="headerTop">
      <div>
        <div class="title">الإعدادات</div>
        <div class="subtitle">إدارة الموردين والأصناف وإعدادات الشركة (Admin).</div>
      </div>

      <div class="navRow">
        <a class="btn btnPrimary" href="{{ Route::has('dashboard.sales') ? route('dashboard.sales') : '#' }}">الرئيسية</a>

        <a class="btn btnGhost {{ Route::currentRouteNamed('dashboard.sales') ? 'activeTab' : '' }}"
           href="{{ Route::has('dashboard.sales') ? route('dashboard.sales') : '#' }}">المبيعات</a>

        <a class="btn btnGhost {{ Route::currentRouteNamed('purchases.*') ? 'activeTab' : '' }}"
           href="{{ Route::has('purchases.index') ? route('purchases.index') : '#' }}">المشتريات</a>

        <a class="btn btnGhost {{ Route::currentRouteNamed('expenses.*') ? 'activeTab' : '' }}"
           href="{{ Route::has('expenses.index') ? route('expenses.index') : '#' }}">المصروفات</a>

        <a class="btn btnGhost {{ Route::currentRouteNamed('dashboard.reports*') ? 'activeTab' : '' }}"
           href="{{ Route::has('dashboard.reports') ? route('dashboard.reports') : '#' }}">التقارير</a>

        <a class="btn btnGhost activeTab"
           href="{{ Route::has('settings.index') ? route('settings.index') : '#' }}">الإعدادات</a>

        @if($isAdmin)
          <a class="btn btnGhost" href="{{ Route::has('branches.index') ? route('branches.index') : '#' }}">إدارة الفروع</a>
          <a class="btn btnGhost" href="{{ Route::has('users.index') ? route('users.index') : '#' }}">إدارة المستخدمين</a>
        @endif

        <!-- ✅ زر واحد فقط لتبديل المظهر (مريح/فاتح/غامق) -->
        <button class="btn btnGhost" type="button" id="themeBtn">🎨 المظهر</button>

        <form method="POST" action="{{ Route::has('logout') ? route('logout') : '#' }}" style="display:inline">
          @csrf
          <button class="btn btnDanger" type="submit">خروج</button>
        </form>
      </div>
    </div>
  </div>

  @if(session('error')) <div class="alert err">{{ session('error') }}</div> @endif
  @if(session('ok'))    <div class="alert ok">{{ session('ok') }}</div> @endif
  @if($errors->any())   <div class="alert err">{{ $errors->first() }}</div> @endif

  <div class="card">
    <div class="cardTitle">
      <h3>أقسام الإعدادات</h3>
      <div class="cardHint">اختر القسم الذي تريد إدارته</div>
    </div>

    <div class="tabsWrap">
      <a class="btn btnGhost {{ $tab==='suppliers' ? 'activeTab' : '' }}" href="{{ route('settings.index', ['tab'=>'suppliers']) }}">الموردين</a>
      <a class="btn btnGhost {{ $tab==='items' ? 'activeTab' : '' }}" href="{{ route('settings.index', ['tab'=>'items']) }}">الأصناف</a>

      @if($isAdmin)
        <a class="btn btnGhost {{ $tab==='company' ? 'activeTab' : '' }}" href="{{ route('settings.index', ['tab'=>'company']) }}">إعدادات الشركة</a>
      @endif
    </div>
  </div>

  @if($isAdmin)
    <div class="card">
      <div class="cardTitle">
        <h3>أدوات الإدارة</h3>
        <div class="cardHint">عمليات صيانة وحذف (تحتاج Backup)</div>
      </div>

      <div style="display:flex;gap:8px;flex-wrap:wrap">
        <a class="btn btnDanger"
           href="{{ Route::has('admin.invoices.purge.form') ? route('admin.invoices.purge.form') : (Route::has('admin.invoices.purge') ? route('admin.invoices.purge') : '/dashboard/admin/invoices/purge') }}">
          حذف فواتير المبيعات (صيانة)
        </a>
      </div>
    </div>
  @endif

  @if($tab === 'suppliers')
    <div class="card">
      <div class="cardTitle">
        <h3>الموردين</h3>
        <div class="cardHint">إضافة / تعديل / تفعيل - تعطيل</div>
      </div>

      <form method="POST" action="{{ route('settings.suppliers.store') }}">
        @csrf
        <div class="grid">
          <div>
            <label>اسم المورد</label>
            <input type="text" name="name" placeholder="مثال: شركة المنظفات" required>
          </div>
          <div>
            <label>&nbsp;</label>
            <button class="btn btnPrimary" type="submit">إضافة</button>
          </div>
          <div></div>
        </div>
      </form>

      <div class="tableWrap">
        <table>
          <thead>
            <tr>
              <th style="width:90px">#</th>
              <th>اسم المورد</th>
              <th style="width:140px">الحالة</th>
              <th style="text-align:left;width:220px">إجراءات</th>
            </tr>
          </thead>
          <tbody>
            @forelse(($suppliers ?? []) as $s)
              <tr>
                <td class="muted">{{ $s->id }}</td>

                <td>
                  <form method="POST" action="{{ route('settings.suppliers.update', ['id'=>$s->id]) }}"
                        style="display:flex;gap:8px;align-items:center;flex-wrap:wrap">
                    @csrf
                    <input name="name" value="{{ $s->name }}" style="max-width:520px" required>
                    <button class="miniBtn" type="submit">حفظ</button>
                  </form>
                </td>

                <td>
                  @if((int)$s->is_active === 1)
                    <span class="badge on">مفعل</span>
                  @else
                    <span class="badge off">معطل</span>
                  @endif
                </td>

                <td style="text-align:left">
                  <div class="rowActions">
                    <form method="POST" action="{{ route('settings.suppliers.toggle', ['id'=>$s->id]) }}">
                      @csrf
                      @if((int)$s->is_active === 1)
                        <button class="miniBtnDanger" type="submit">تعطيل</button>
                      @else
                        <button class="miniBtn" type="submit">تفعيل</button>
                      @endif
                    </form>
                  </div>
                </td>
              </tr>
            @empty
              <tr><td colspan="4" class="muted" style="padding:16px;text-align:center">لا يوجد موردين حالياً</td></tr>
            @endforelse
          </tbody>
        </table>
      </div>
    </div>
  @endif

  @if($tab === 'items')
    <div class="card">
      <div class="cardTitle">
        <h3>الأصناف</h3>
        <div class="cardHint">إضافة / تعديل / تفعيل - تعطيل (مع سعر افتراضي اختياري)</div>
      </div>

      <form method="POST" action="{{ route('settings.items.store') }}">
        @csrf
        <div class="grid" style="grid-template-columns: 1.2fr 260px auto;">
          <div>
            <label>اسم الصنف</label>
            <input type="text" name="name" placeholder="مثال: مسحوق غسيل 10KG" required>
          </div>
          <div>
            <label>السعر الافتراضي (اختياري)</label>
            <input type="number" name="default_price_gross" step="0.01" min="0" placeholder="0.00">
          </div>
          <div style="display:flex;justify-content:flex-end;align-items:end;align-self:end;">
            <button class="btn btnPrimary" type="submit">إضافة</button>
          </div>
        </div>
      </form>

      <div class="tableWrap">
        <table>
          <thead>
            <tr>
              <th style="width:90px">#</th>
              <th>الصنف</th>
              <th style="width:220px">السعر الافتراضي</th>
              <th style="width:140px">الحالة</th>
              <th style="text-align:left;width:220px">إجراءات</th>
            </tr>
          </thead>
          <tbody>
            @forelse(($items ?? []) as $it)
              <tr>
                <td class="muted">{{ $it->id }}</td>

                <td>
                  <form method="POST" action="{{ route('settings.items.update', ['id'=>$it->id]) }}"
                        style="display:flex;gap:8px;align-items:center;flex-wrap:wrap">
                    @csrf
                    <input name="name" value="{{ $it->name }}" style="max-width:420px" required>
                </td>

                <td>
                    <input name="default_price_gross"
                           value="{{ number_format((float)($it->default_price_gross ?? 0), 2, '.', '') }}"
                           step="0.01" min="0" type="number" style="max-width:220px">
                    <button class="miniBtn" type="submit">حفظ</button>
                  </form>
                </td>

                <td>
                  @if((int)$it->is_active === 1)
                    <span class="badge on">مفعل</span>
                  @else
                    <span class="badge off">معطل</span>
                  @endif
                </td>

                <td style="text-align:left">
                  <div class="rowActions">
                    <form method="POST" action="{{ route('settings.items.toggle', ['id'=>$it->id]) }}">
                      @csrf
                      @if((int)$it->is_active === 1)
                        <button class="miniBtnDanger" type="submit">تعطيل</button>
                      @else
                        <button class="miniBtn" type="submit">تفعيل</button>
                      @endif
                    </form>
                  </div>
                </td>
              </tr>
            @empty
              <tr><td colspan="5" class="muted" style="padding:16px;text-align:center">لا يوجد أصناف حالياً</td></tr>
            @endforelse
          </tbody>
        </table>
      </div>
    </div>
  @endif

  @if($tab === 'company' && $isAdmin)

  {{-- ✅ كرت إعدادات الشركة --}}
  <div class="card">
    <div class="cardTitle">
      <h3>إعدادات الشركة</h3>
      <div class="cardHint">Admin فقط — يظهر في صفحة الدخول والتقارير</div>
    </div>

    <form method="POST" action="{{ route('settings.company.update') }}" enctype="multipart/form-data">
      @csrf

      <div class="grid" style="grid-template-columns: 1.1fr 1fr auto; align-items:start;">
        <div>
          <label>اسم النشاط</label>
          <input type="text" name="business_name" value="{{ $company->business_name ?? '' }}" placeholder="مثال: BabHara Laundry">
        </div>

        <div>
          <label>الشعار (اختياري)</label>
          <input type="file" name="logo" accept=".png,.jpg,.jpeg,.webp">

          @if(!empty($company->logo_path))
            <img class="logoPreview" src="{{ asset('storage/'.$company->logo_path) }}" alt="Logo">
          @endif
        </div>

        <div style="display:flex;justify-content:flex-end;align-items:end;align-self:end;">
          <button class="btn btnPrimary" type="submit">حفظ</button>
        </div>
      </div>
    </form>

    <div class="muted" style="margin-top:12px">
      ملاحظة: لو الشعار ما يظهر، نفّذ مرة واحدة:
      <span style="font-weight:900;color:var(--text)">php artisan storage:link</span>
    </div>
  </div>

  {{-- ✅ كرت النسخ الاحتياطي --}}
  <div class="card">
    <div class="cardTitle">
      <h3>نسخ احتياطي (Backup)</h3>
      <div class="cardHint">Admin فقط — نسخة SQL كاملة قابلة للنقل (Create / Download / Delete)</div>
    </div>

    <div class="grid" style="grid-template-columns: 1fr auto; align-items:start;">
      <div class="muted" style="line-height:1.8">
     
        <div style="margin-top:6px">
          ملاحظة: يتم الاحتفاظ بـ <span style="font-weight:900;color:var(--text)">نسخة واحدة فقط</span> (الجديدة تستبدل القديمة).
        </div>
      </div>

      <div style="display:flex;justify-content:flex-end;align-items:end;gap:8px;flex-wrap:wrap;align-self:end;">
        <button id="btnCreateBackup" class="btn btnPrimary" type="button">إنشاء Backup</button>
        <button id="btnRefreshBackups" class="btn btnGhost" type="button">تحديث القائمة</button>
      </div>
    </div>

    <div id="backupMsg" class="muted" style="margin-top:10px"></div>

    <div style="overflow:auto;margin-top:10px">
      <table class="table">
        <thead>
          <tr>
            <th>الملف</th>
            <th style="width:150px">الحجم</th>
            <th style="width:200px">التاريخ</th>
            <th style="width:240px">إجراءات</th>
          </tr>
        </thead>
        <tbody id="backupRows">
          <tr><td colspan="4" class="muted" style="padding:14px;text-align:center">—</td></tr>
        </tbody>
      </table>
    </div>
  </div>

  {{-- ✅ كرت حذف كامل البيانات --}}
  <div class="card">
    <div class="cardTitle">
      <h3>حذف كامل بيانات الشركة</h3>
      <div class="cardHint">Admin فقط — سيبقى users + company_settings (اسم النشاط فقط)</div>
    </div>

    <div class="alert err" style="margin-bottom:10px">
      تنبيه: هذا الإجراء لا يمكن التراجع عنه. تأكد من إنشاء Backup قبل الحذف.
    </div>

    <div class="grid" style="grid-template-columns: 1fr auto; align-items:start;">
      <div>
        <label>كلمة مرور الأدمن للتأكيد</label>
        <input id="purgePassword" type="password" placeholder="اكتب كلمة المرور للتأكيد">
        <div class="muted" style="margin-top:8px;line-height:1.7">
          سيتم حذف كل البيانات/الجداول التشغيلية. سيبقى فقط:
          <span style="font-weight:900;color:var(--text)">users</span>
          و
          <span style="font-weight:900;color:var(--text)">company_settings.business_name</span>
        </div>
      </div>

      <div style="display:flex;justify-content:flex-end;align-items:end;gap:8px;flex-wrap:wrap;align-self:end;">
        <button id="btnPurge" class="btn btnDanger" type="button">حذف كامل البيانات</button>
      </div>
    </div>

    <div id="purgeMsg" class="muted" style="margin-top:10px"></div>
  </div>

@endif


</div>

<script>
(function(){
  const themes = ["light","dim","dark"];
  const key = "ui_theme";
  const html = document.documentElement;
  const btn = document.getElementById("themeBtn");

  function label(t){
    if(t === "light") return "☀️ فاتح";
    if(t === "dark") return "🌙 داكن";
    return "🌗 مريح";
  }

  function apply(t){
    html.setAttribute("data-theme", t);
    localStorage.setItem(key, t);
    if(btn) btn.textContent = "🎨 " + label(t);
  }

  const saved = localStorage.getItem(key);
  const t = (saved && themes.includes(saved)) ? saved : (html.getAttribute("data-theme") || "dim");
  apply(t);

  if(btn){
    btn.addEventListener("click", function(){
      const cur = html.getAttribute("data-theme") || "dim";
      const idx = themes.indexOf(cur);
      const next = themes[(idx + 1) % themes.length];
      apply(next);
    });
  }
})();
</script>

</body>
</html>
