<!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>
    @page { size: A4; margin: 14mm; }
    *{box-sizing:border-box}
    body{font-family:Arial, sans-serif;color:#111827}

    @media print{
      .noPrint{display:none !important; visibility:hidden !important;}
      a[href]:after{content:""}
    }

    /* شاشة فقط */
    .topCard{background:#fff;border:1px solid #e5e7eb;border-radius:14px;padding:12px;margin-bottom:10px}
    .topBar{display:flex;gap:8px;align-items:center;justify-content:space-between;flex-wrap:wrap;margin-bottom:10px}
    .leftBtns{display:flex;gap:8px;align-items:center;flex-wrap:wrap}
    .btnHome{padding:10px 12px;border-radius:10px;border:1px solid #2563eb;background:#2563eb;color:#fff;font-weight:900;text-decoration:none;display:inline-flex;align-items:center}
    .btnPrint{padding:10px 12px;border-radius:10px;border:1px solid #d1d5db;background:#111827;color:#fff;font-weight:900;cursor:pointer;display:inline-flex;align-items:center}
    .btnLogout{padding:10px 12px;border-radius:10px;border:1px solid #dc2626;background:#dc2626;color:#fff;font-weight:900;cursor:pointer;display:inline-flex;align-items:center}
    .subTabs{display:flex;gap:8px;align-items:center;flex-wrap:wrap}
    .tabBtn{padding:10px 12px;border-radius:10px;border:1px solid #d1d5db;background:#fff;color:#111827;font-weight:900;text-decoration:none;display:inline-flex;align-items:center}
    .tabBtn.active{background:#111827;color:#fff;border-color:#111827}

    /* Header */
    .reportHeader{display:flex;justify-content:space-between;align-items:flex-start;gap:12px;padding-bottom:10px;border-bottom:1px solid #e5e7eb;margin-bottom:10px}
    .business{min-width:260px}
    .businessName{font-weight:900;font-size:24px;line-height:1.2}
    .reportTitle{margin-top:6px;font-weight:900;font-size:14px}
    .meta{flex:1;font-size:12px;color:#374151;line-height:1.9;margin-top:2px}
    .lbl{color:#6b7280;font-weight:900}
    .logo{width:110px;display:flex;justify-content:flex-start}
    .logo img{width:110px;height:70px;object-fit:contain}
    .printMetaLine{display:flex;justify-content:space-between;gap:10px;margin:8px 0 12px;font-size:12px;color:#374151}
    .printMetaLine > div{white-space:nowrap}

    /* Summary */
    .summaryRow{display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin:0 0 10px}
    .sumBox{border:1px solid #e5e7eb;border-radius:12px;padding:12px}
    .sumLabel{color:#6b7280;font-weight:900;font-size:12px}
    .sumVal{margin-top:6px;font-weight:900;font-size:16px}

    /* Table (✅ الإصلاح الحقيقي هنا) */
    .box{border:1px solid #e5e7eb;border-radius:12px;padding:10px}
    table{width:100%;border-collapse:collapse;table-layout:auto;} /* مهم */
    th,td{
      border-bottom:1px solid #e5e7eb;
      padding:7px 8px;
      text-align:right;
      font-size:11.8px;
      vertical-align:top;

      word-break:normal;
      overflow-wrap:break-word;
      white-space:normal;
    }
    th{background:#f9fafb;font-weight:900}
    .num{font-weight:900; white-space:nowrap;}
    .nowrap{white-space:nowrap;}
    .txtWrap{white-space:normal; overflow-wrap:anywhere;}
  </style>
</head>
<body>

@php
  $company = null;
  try { $company = \Illuminate\Support\Facades\DB::table('company_settings')->where('id', 1)->first(); }
  catch (\Throwable $e) { $company = null; }

  $businessName = $company->business_name ?? 'اسم النشاط التجاري';
  $logoUrl = (!empty($company->logo_path)) ? asset('storage/'.$company->logo_path) : null;

  $printedBy = auth()->check() ? (auth()->user()->name ?? '-') : '-';
  $printedAt = now()->format('d/m/Y H:i');

  $branchLabel = 'كل الفروع';
  if ((int)($branchId ?? 0)) {
    $b = $branches->firstWhere('id', (int)$branchId);
    $branchLabel = $b ? ($b->branch_no.' - '.$b->name) : ('فرع #' . (int)$branchId);
  }

  $catLabel = 'كل المصروفات';
  if (!empty($categoryId) && (int)$categoryId) {
    $c = $categories->firstWhere('id', (int)$categoryId);
    $catLabel = $c ? $c->name : ('مصروف #' . (int)$categoryId);
  }

  $subLabel = 'كل التفاصيل';
  if (!empty($subId) && (int)$subId) {
    $sc = $subcats->firstWhere('id', (int)$subId);
    $subLabel = $sc ? $sc->name : ('تفصيل #' . (int)$subId);
  }
@endphp

<div class="topCard noPrint">
  <div class="topBar">
    <div class="leftBtns">
      <a class="btnHome" href="{{ Route::has('dashboard.sales') ? route('dashboard.sales') : '#' }}">الرئيسية</a>
      <button class="btnPrint" type="button" onclick="window.print()">طباعة / حفظ PDF</button>
    </div>
    <form method="POST" action="{{ Route::has('logout') ? route('logout') : '#' }}" style="display:inline">
      @csrf
      <button class="btnLogout" type="submit">خروج</button>
    </form>
  </div>

  <div class="subTabs">
    <a class="tabBtn" href="{{ Route::has('dashboard.reports.print') ? route('dashboard.reports.print', request()->query()) : '#' }}">تقرير شامل</a>
    <a class="tabBtn" href="{{ Route::has('dashboard.reports.sales.print') ? route('dashboard.reports.sales.print', request()->query()) : '#' }}">تقرير المبيعات</a>
    <a class="tabBtn" href="{{ Route::has('dashboard.reports.purchases.print') ? route('dashboard.reports.purchases.print', request()->query()) : '#' }}">تقرير المشتريات</a>
    <a class="tabBtn active" href="{{ Route::has('dashboard.reports.expenses.print') ? route('dashboard.reports.expenses.print', request()->query()) : '#' }}">تقرير المصروفات</a>
  </div>
</div>

<div class="reportHeader">
  <div class="business">
    <div class="businessName">{{ $businessName }}</div>
    <div class="reportTitle">تقرير المصروفات</div>
  </div>

  <div class="meta">
    <div><span class="lbl">الفترة:</span> {{ $from }} → {{ $to }}</div>
    <div><span class="lbl">الفرع:</span> {{ $branchLabel }}</div>
    <div><span class="lbl">المصروف:</span> {{ $catLabel }}</div>
    <div><span class="lbl">التفصيل:</span> {{ $subLabel }}</div>
    @if(!empty($q))
      <div><span class="lbl">بحث:</span> {{ $q }}</div>
    @endif
  </div>

  <div class="logo">
    @if($logoUrl)<img src="{{ $logoUrl }}" alt="Logo">@endif
  </div>
</div>

<div class="printMetaLine">
  <div><span class="lbl">طبع بواسطة:</span> {{ $printedBy }}</div>
  <div><span class="lbl">تاريخ الطباعة:</span> {{ $printedAt }}</div>
</div>

<div class="summaryRow">
  <div class="sumBox">
    <div class="sumLabel">قبل الضريبة</div>
    <div class="sumVal">{{ number_format((float)($totals->subtotal ?? 0), 2) }}</div>
  </div>
  <div class="sumBox">
    <div class="sumLabel">الضريبة</div>
    <div class="sumVal">{{ number_format((float)($totals->vat_amount ?? 0), 2) }}</div>
  </div>
  <div class="sumBox">
    <div class="sumLabel">الإجمالي</div>
    <div class="sumVal">{{ number_format((float)($totals->total ?? 0), 2) }}</div>
  </div>
</div>

<div class="box">
  <table>
    <thead>
      <tr>
        <th class="nowrap" style="width:86px">التاريخ</th>
        <th class="nowrap" style="width:95px">الفرع</th>
        <th>المصروف</th>
        <th>التفصيل</th>
        <th class="nowrap" style="width:95px">رقم الفاتورة</th>
        <th class="nowrap" style="width:85px">قبل الضريبة</th>
        <th class="nowrap" style="width:70px">الضريبة</th>
        <th class="nowrap" style="width:85px">الإجمالي</th>
        <th style="width:130px">ملاحظات</th>
      </tr>
    </thead>
    <tbody>
      @forelse($rows as $r)
        <tr>
          <td class="num">{{ \Carbon\Carbon::parse($r->bill_date)->format('d/m/Y') }}</td>
          <td class="nowrap">{{ $r->branch_no }} - {{ $r->branch_name }}</td>
          <td class="txtWrap">{{ $r->category_name ?? '' }}</td>
          <td class="txtWrap">{{ $r->subcategory_name ?? '' }}</td>
          <td class="num">{{ $r->bill_no ?? ($r->inv_no_branch ?? '') }}</td>
          <td class="num">{{ number_format((float)($r->subtotal ?? 0), 2) }}</td>
          <td class="num">{{ number_format((float)($r->vat_amount ?? 0), 2) }}</td>
          <td class="num">{{ number_format((float)($r->total ?? 0), 2) }}</td>
          <td class="txtWrap">{{ $r->notes ?? '' }}</td>
        </tr>
      @empty
        <tr><td colspan="9" style="text-align:center;color:#6b7280;font-weight:900;padding:14px">لا توجد بيانات</td></tr>
      @endforelse
    </tbody>
  </table>
</div>

<script>
(function () {
  try {
    var params = new URLSearchParams(window.location.search);
    if (params.get('autoprint') === '1') {
      window.addEventListener('load', function () {
        setTimeout(function () { window.print(); }, 250);
      });
    }
  } catch (e) {}
})();
</script>

</body>
</html>
