<!doctype html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>فواتير المشتريات</title>

  <style>
    /* ========= Themes (3 حالات) ========= */

    :root{ /* LIGHT (هو القديم) */
      --bg:#f6f7fb;
      --card:#ffffff;
      --text:#111827;
      --muted:#6b7280;
      --border:#e5e7eb;
      --shadow:0 10px 25px rgba(0,0,0,.06);

      --btn:#111827; --btnText:#ffffff;
      --btn2Bg:#ffffff; --btn2Text:#111827; --btn2Border:#d1d5db;

      --homeBg:#2563eb; --homeText:#ffffff;
      --dangerBg:#dc2626; --dangerText:#ffffff;

      --okBg:#ecfdf3; --okBorder:#bbf7d0; --okText:#166534;
      --errBg:#fef2f2; --errBorder:#fecaca; --errText:#991b1b;

      --tableBg:#ffffff;
      --tableHead:#f9fafb;
      --tableBorder:#e5e7eb;
      --tableHover:#f3f4f6;

      --inputBg:#ffffff;
      --inputText:#111827;
      --focusRing:rgba(17,24,39,.10);
    }

    html[data-theme="dim"]{ /* مريح */
      --bg:#0f172a;
      --card:#111c33;
      --text:#e5e7eb;
      --muted:#9ca3af;
      --border:rgba(255,255,255,.10);
      --shadow:0 14px 35px rgba(0,0,0,.30);

      --btn:#111827; --btnText:#ffffff;
      --btn2Bg:rgba(255,255,255,.06); --btn2Text:#ffffff; --btn2Border:rgba(255,255,255,.14);

      --homeBg:#2563eb; --homeText:#ffffff;
      --dangerBg:#ef4444; --dangerText:#ffffff;

      --okBg:rgba(34,197,94,.14); --okBorder:rgba(34,197,94,.35); --okText:#ffffff;
      --errBg:rgba(239,68,68,.14); --errBorder:rgba(239,68,68,.35); --errText:#ffffff;

      --tableBg:#0b1327;
      --tableHead:rgba(255,255,255,.07);
      --tableBorder:rgba(255,255,255,.10);
      --tableHover:rgba(255,255,255,.05);

      --inputBg:#0b1327;
      --inputText:#e5e7eb;
      --focusRing:rgba(99,102,241,.20);
    }

    html[data-theme="dark"]{ /* داكن */
      --bg:#0b1220;
      --card:#0f172a;
      --text:#ffffff;
      --muted:#cbd5e1;
      --border:rgba(255,255,255,.16);
      --shadow:0 16px 40px rgba(0,0,0,.40);

      --btn:#111827; --btnText:#ffffff;
      --btn2Bg:rgba(255,255,255,.08); --btn2Text:#ffffff; --btn2Border:rgba(255,255,255,.20);

      --homeBg:#2563eb; --homeText:#ffffff;
      --dangerBg:#ef4444; --dangerText:#ffffff;

      --okBg:rgba(34,197,94,.14); --okBorder:rgba(34,197,94,.35); --okText:#ffffff;
      --errBg:rgba(239,68,68,.14); --errBorder:rgba(239,68,68,.35); --errText:#ffffff;

      --tableBg:#0b1327;
      --tableHead:rgba(255,255,255,.10);
      --tableBorder:rgba(255,255,255,.18);
      --tableHover:rgba(255,255,255,.06);

      --inputBg:#0b1327;
      --inputText:#ffffff;
      --focusRing:rgba(99,102,241,.22);
    }

    *{box-sizing:border-box}
    body{
      font-family:Arial, sans-serif;
      margin:32px;
      background:var(--bg);
      color:var(--text);
    }
    .container{max-width:1200px;margin:0 auto}

    .bar{display:flex;justify-content:space-between;align-items:flex-start;gap:12px;margin-bottom:16px;flex-wrap:wrap}
    .title{font-weight:900;font-size:18px}
    .subtitle{color:var(--muted);font-size:13px;margin-top:4px}

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

    .btn{
      padding:10px 12px;border-radius:12px;background:var(--btn);color:var(--btnText);
      border:0;cursor:pointer;font-weight:900;font-size:13px;line-height:1;
    }
    .btn:hover{opacity:.95}

    .btn2{
      padding:10px 12px;border-radius:12px;background:var(--btn2Bg);color:var(--btn2Text);
      border:1px solid var(--btn2Border);cursor:pointer;text-decoration:none;
      font-weight:900;font-size:13px;line-height:1;display:inline-flex;align-items:center;gap:8px;
    }

    .active{background:#111827;color:#fff;border-color:#111827}
    html[data-theme="dim"] .active,
    html[data-theme="dark"] .active{
      background:rgba(37,99,235,.22);
      border-color:rgba(37,99,235,.55);
      color:#fff;
    }

    .btnHome{
      padding:10px 12px;border-radius:12px;background:var(--homeBg);color:var(--homeText);
      border:1px solid rgba(0,0,0,.08);cursor:pointer;text-decoration:none;
      font-weight:900;font-size:13px;line-height:1;display:inline-flex;align-items:center;gap:8px;
    }

    .btnDanger{
      padding:10px 12px;border-radius:12px;background:var(--dangerBg);color:var(--dangerText);
      border:0;cursor:pointer;font-weight:900;font-size:13px;line-height:1;
    }
    .btnDanger:disabled{
      opacity:.45;
      cursor:not-allowed;
      filter:grayscale(.2);
    }

    /* ✅ زر واحد فقط للثيم */
    .themeBtn{display:inline-flex;align-items:center;gap:8px}

    .card{
      background:var(--card);border:1px solid var(--border);border-radius:14px;
      box-shadow:var(--shadow);padding:16px;margin-bottom:14px;
    }

    .alert{padding:12px;border-radius:12px;border:1px solid;font-weight:900;margin-bottom:14px}
    .alert.ok{background:var(--okBg);border-color:var(--okBorder);color:var(--okText)}
    .alert.err{background:var(--errBg);border-color:var(--errBorder);color:var(--errText)}

    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(--border);
      border-radius:12px;
      outline:none;
      font-size:14px;
      background:var(--inputBg);
      color:var(--inputText);
    }
    input:focus,select:focus{
      box-shadow:0 0 0 3px var(--focusRing);
    }

    .grid{
      display:grid;
      grid-template-columns: 1fr 1fr 1fr 1fr 1fr auto;
      gap:12px;
      align-items:end;
    }
    @media (max-width: 980px){ body{margin:18px} .grid{grid-template-columns: 1fr 1fr;} }
    @media (max-width: 560px){ .grid{grid-template-columns: 1fr;} }

    .tableWrap{
      overflow:auto;
      border-radius:12px;
      border:1px solid var(--tableBorder);
      margin-top:10px;
      background:var(--tableBg);
    }
    table{width:100%;border-collapse:collapse;min-width:1250px;background:var(--tableBg)}
    th,td{
      padding:10px 12px;
      border-bottom:1px solid var(--tableBorder);
      text-align:right;
      vertical-align:middle;
      color:var(--text);
    }
    th{background:var(--tableHead);font-weight:900;font-size:14px;white-space:nowrap}
    td{font-size:13px}
    tbody tr:hover td{background:var(--tableHover)}
    .num{font-weight:900}

    .kpis{display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin-top:12px}
    @media (max-width: 980px){ .kpis{grid-template-columns:repeat(2,1fr);} }
    @media (max-width: 560px){ .kpis{grid-template-columns:1fr;} }
    .kpi{border:1px solid var(--border);border-radius:14px;padding:12px;background:var(--tableBg)}
    .kpi .t{color:var(--muted);font-size:12px;font-weight:900}
    .kpi .v{margin-top:8px;font-size:16px;font-weight:900;color:var(--text)}

    .empty{padding:16px;text-align:center;color:var(--muted);font-weight:900}

    .chk{width:18px;height:18px;cursor:pointer;accent-color:#2563eb}
    html[data-theme="dim"] .chk,
    html[data-theme="dark"] .chk{accent-color:#60a5fa}

    .actionsRow{display:flex;gap:8px;flex-wrap:wrap;justify-content:flex-end}

    .selCount{
      font-weight:900;
      color:var(--muted);
      padding:8px 10px;
      border:1px dashed var(--border);
      border-radius:12px;
      background:var(--tableBg);
    }
  </style>

  <!-- ✅ Apply saved theme ASAP -->
  <script>
    (function(){
      const key = "ui_theme_3";
      const saved = localStorage.getItem(key);
      const t = (saved === "dim" || saved === "dark") ? saved : "light";
      document.documentElement.setAttribute("data-theme", t);
    })();
  </script>
</head>

<body>
<div class="container">

  <?php
    $role = auth()->check() ? (auth()->user()->role ?? 'user') : 'guest';
    $canDelete = in_array($role, ['admin','super'], true);
  ?>

  <div class="bar">
    <div>
      <div class="title">فواتير المشتريات</div>
      <div class="subtitle">عرض + فلترة + تصدير</div>
    </div>

    <div class="navRow">
      <a class="btnHome" href="<?php echo e(route('dashboard')); ?>">الرئيسية</a>

      <a class="btn2" href="<?php echo e(route('dashboard.sales')); ?>">المبيعات</a>
      <a class="btn2 active" href="<?php echo e(route('purchases.index')); ?>">المشتريات</a>
      <a class="btn2" href="<?php echo e(route('expenses.index')); ?>">المصروفات</a>
      <a class="btn2" href="<?php echo e(route('dashboard.reports')); ?>">التقارير</a>
      <a class="btn2" href="<?php echo e(route('settings.index')); ?>">الإعدادات</a>

      <?php if(auth()->check() && (auth()->user()->role ?? 'user') === 'admin'): ?>
        <a class="btn2" href="<?php echo e(route('branches.index')); ?>">إدارة الفروع</a>
        <a class="btn2" href="<?php echo e(route('users.index')); ?>">إدارة المستخدمين</a>
      <?php endif; ?>

      <!-- ✅ زر واحد فقط يتبدّل (فاتح → مريح → داكن) -->
      <button class="btn2 themeBtn" type="button" id="themeToggle">
        <span id="themeIcon">☀️</span>
        <span id="themeText">فاتح</span>
      </button>

      <form method="POST" action="<?php echo e(route('logout')); ?>" style="display:inline">
        <?php echo csrf_field(); ?>
        <button class="btnDanger" type="submit">خروج</button>
      </form>
    </div>
  </div>

  <div class="card">
    <div class="navRow">
      <a class="btn2" href="<?php echo e(route('purchases.index', ['branch_id' => $branchId])); ?>">إضافة فاتورة</a>
      <a class="btn2 active" href="<?php echo e(route('purchases.invoices', ['branch_id' => $branchId])); ?>">فواتير المشتريات</a>

      <a class="btn2"
         href="<?php echo e(route('purchases.invoices.export', [
            'branch_id'=>request('branch_id',0),
            'supplier_id'=>request('supplier_id',0),
            'from'=>request('from'),
            'to'=>request('to'),
            'q'=>request('q','')
         ])); ?>">
        تصدير CSV
      </a>

      <?php if($canDelete): ?>
        <button id="deleteBtn" class="btnDanger" type="button" onclick="submitDeleteSelected()" disabled>
          حذف المحدد
        </button>
        <span id="selCount" class="selCount">المحدد: 0</span>
      <?php endif; ?>
    </div>
  </div>

  <?php if(session('error')): ?> <div class="alert err"><?php echo e(session('error')); ?></div> <?php endif; ?>
  <?php if(session('ok')): ?>    <div class="alert ok"><?php echo e(session('ok')); ?></div> <?php endif; ?>

  <div class="card">
    <form method="GET" action="<?php echo e(route('purchases.invoices')); ?>">
      <div class="grid">

        <div>
          <label>الفرع</label>
          <select name="branch_id">
            <option value="0">كل الفروع</option>
            <?php $__currentLoopData = $branches; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $b): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
              <option value="<?php echo e($b->id); ?>" <?php if((int)$branchId === (int)$b->id): echo 'selected'; endif; ?>>
                <?php echo e($b->branch_no); ?> - <?php echo e($b->name); ?>

              </option>
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
          </select>
        </div>

        <div>
          <label>المورد</label>
          <select name="supplier_id">
            <option value="0">الكل</option>
            <?php $__currentLoopData = $suppliers; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $s): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
              <option value="<?php echo e($s->id); ?>" <?php if((int)$supplierId === (int)$s->id): echo 'selected'; endif; ?>><?php echo e($s->name); ?></option>
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
          </select>
        </div>

        <div>
          <label>من تاريخ</label>
          <input type="date" name="from" value="<?php echo e($from); ?>">
        </div>

        <div>
          <label>إلى تاريخ</label>
          <input type="date" name="to" value="<?php echo e($to); ?>">
        </div>

        <div>
          <label>بحث</label>
          <input type="text" name="q" value="<?php echo e($q); ?>" placeholder="رقم فاتورة / اسم مورد">
        </div>

        <div class="actionsRow">
          <button class="btn" type="submit">تطبيق</button>
          <a class="btn2" href="<?php echo e(route('purchases.invoices', ['branch_id' => request('branch_id', 0)])); ?>">مسح</a>
        </div>

      </div>

      <div class="kpis">
        <div class="kpi">
          <div class="t">الإجمالي قبل الضريبة</div>
          <div class="v"><?php echo e(number_format($totals->subtotal ?? 0, 2)); ?></div>
        </div>
        <div class="kpi">
          <div class="t">قيمة الضريبة</div>
          <div class="v"><?php echo e(number_format($totals->vat_amount ?? 0, 2)); ?></div>
        </div>
        <div class="kpi">
          <div class="t">الإجمالي شامل</div>
          <div class="v"><?php echo e(number_format($totals->total ?? 0, 2)); ?></div>
        </div>
      </div>
    </form>
  </div>

  <?php if($canDelete): ?>
    <form id="deleteForm" method="POST" action="<?php echo e(route('purchases.invoices.delete')); ?>">
      <?php echo csrf_field(); ?>
    </form>
  <?php endif; ?>

  <div class="card">
    <div class="tableWrap">
      <table>
        <thead>
          <tr>
            <?php if($canDelete): ?>
              <th style="width:40px">
                <input class="chk" type="checkbox" id="chkAll" onclick="toggleAll(this)">
              </th>
            <?php endif; ?>
            <th>ID</th>
            <th>الفرع</th>
            <th>رقم داخل الفرع</th>
            <th>رقم فاتورة المورد</th>
            <th>التاريخ</th>
            <th>المورد</th>
            <th>قبل الضريبة</th>
            <th>الضريبة</th>
            <th>الإجمالي</th>
            <th>تاريخ الإدخال</th>
          </tr>
        </thead>
        <tbody>
          <?php $__currentLoopData = $rows; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $r): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
            <tr>
              <?php if($canDelete): ?>
                <td>
                  <input class="chk rowChk" type="checkbox" value="<?php echo e($r->id); ?>">
                </td>
              <?php endif; ?>
              <td class="num"><?php echo e($r->id); ?></td>
              <td><?php echo e($r->branch_no); ?> - <?php echo e($r->branch_name); ?></td>
              <td class="num"><?php echo e($r->inv_no_branch); ?></td>
              <td class="num"><?php echo e($r->supplier_bill_no); ?></td>
              <td><?php echo e($r->bill_date ?: '-'); ?></td>
              <td style="font-weight:900"><?php echo e($r->supplier_name); ?></td>
              <td class="num"><?php echo e(number_format($r->subtotal, 2)); ?></td>
              <td class="num"><?php echo e(number_format($r->vat_amount, 2)); ?></td>
              <td class="num"><?php echo e(number_format($r->total, 2)); ?></td>
              <td><?php echo e($r->created_at); ?></td>
            </tr>
          <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>

          <?php if(count($rows) === 0): ?>
            <tr>
              <td colspan="<?php echo e($canDelete ? 11 : 10); ?>" class="empty">لا توجد بيانات</td>
            </tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>

</div>

<script>
/* ===== Theme Toggle (زر واحد) ===== */
(function(){
  const key = "ui_theme_3";
  const order = ["light","dim","dark"];
  const meta = {
    light: { icon:"☀️", text:"فاتح" },
    dim:   { icon:"🌙", text:"مريح" },
    dark:  { icon:"🌑", text:"داكن" }
  };

  const html = document.documentElement;
  const btn  = document.getElementById("themeToggle");
  const ic   = document.getElementById("themeIcon");
  const tx   = document.getElementById("themeText");

  function apply(t){
    html.setAttribute("data-theme", t);
    localStorage.setItem(key, t);
    if (ic) ic.textContent = meta[t].icon;
    if (tx) tx.textContent = meta[t].text;
  }

  const saved = localStorage.getItem(key);
  apply(order.includes(saved) ? saved : (html.getAttribute("data-theme") || "light"));

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

/* ===== Delete Selected Logic (كما هو) ===== */
function updateDeleteBtn(){
  const btn = document.getElementById('deleteBtn');
  const counter = document.getElementById('selCount');

  const allItems = document.querySelectorAll('.rowChk');
  const checkedItems = Array.from(allItems).filter(c => c.checked);
  const checkedCount = checkedItems.length;

  if(btn){
    btn.disabled = (checkedCount === 0);
  }
  if(counter){
    counter.textContent = 'المحدد: ' + checkedCount;
  }

  const chkAll = document.getElementById('chkAll');
  if(chkAll){
    const all = allItems.length;
    chkAll.checked = (all > 0 && checkedCount === all);
    chkAll.indeterminate = (checkedCount > 0 && checkedCount < all);
  }
}

function toggleAll(el){
  const items = document.querySelectorAll('.rowChk');
  items.forEach(chk => chk.checked = el.checked);
  updateDeleteBtn();
}

document.addEventListener('change', function(e){
  if(e.target && e.target.classList.contains('rowChk')){
    updateDeleteBtn();
  }
});

document.addEventListener('DOMContentLoaded', updateDeleteBtn);

function submitDeleteSelected(){
  const form = document.getElementById('deleteForm');
  if(!form) return;

  form.querySelectorAll('input[name="ids[]"]').forEach(n => n.remove());

  const checked = Array.from(document.querySelectorAll('.rowChk')).filter(c => c.checked);
  if(checked.length === 0){
    alert('اختر فاتورة واحدة على الأقل');
    return;
  }

  if(!confirm('تأكيد: سيتم حذف الفواتير المحددة نهائياً. هل أنت متأكد؟')){
    return;
  }

  checked.forEach(c => {
    const inp = document.createElement('input');
    inp.type = 'hidden';
    inp.name = 'ids[]';
    inp.value = c.value;
    form.appendChild(inp);
  });

  form.submit();
}
</script>

</body>
</html>
<?php /**PATH /home/ksaad26/laravel/laundry-dashboard/resources/views/purchases_invoices.blade.php ENDPATH**/ ?>