<?php
$fmtMoney = static fn($v) => number_format((float)$v, 2);
$fmtDate  = static fn($v) => $v ? date('Y-m-d', strtotime((string)$v)) : '-';
$checkBadgeClass = static function(string $status): string {
  return match ($status) {
    'returned' => 'danger',
    'endorsed' => 'warning',
    default => 'primary',
  };
};
?>
<?php if (!empty($alertsError ?? '')): ?>
  <div class="alert alert-warning border-0 shadow-sm mb-3">
    <?= e((string)$alertsError) ?>
  </div>
<?php endif; ?>
<div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-3">
  <div>
    <h3 class="mb-1">لوحة التنبيهات</h3>
    <div class="text-muted small">متابعة موحدة للشيكات والمخزون والعملاء والموردين والخزن والبنوك</div>
  </div>
  <form class="d-flex flex-wrap gap-2 align-items-end" method="get">
    <div>
      <label class="form-label form-label-sm mb-1">تنبيه الشيكات</label>
      <select name="days_ahead" class="form-select form-select-sm" style="width:auto">
        <?php foreach ([3,7,14,30] as $d): ?>
          <option value="<?= $d ?>" <?= $daysAhead===$d?'selected':'' ?>><?= $d ?> يوم</option>
        <?php endforeach; ?>
      </select>
    </div>
    <div>
      <label class="form-label form-label-sm mb-1">أعمار الديون</label>
      <select name="aging_days" class="form-select form-select-sm" style="width:auto">
        <?php foreach ([15,30,45,60,90] as $d): ?>
          <option value="<?= $d ?>" <?= $agingDays===$d?'selected':'' ?>><?= $d ?> يوم</option>
        <?php endforeach; ?>
      </select>
    </div>
    <div>
      <label class="form-label form-label-sm mb-1">حد تنبيه الخزنة</label>
      <input type="number" step="0.01" min="0" name="cash_min" class="form-control form-control-sm" value="<?= e((string)$cashMin) ?>" style="width:120px">
    </div>
    <div>
      <label class="form-label form-label-sm mb-1">حد تنبيه البنك</label>
      <input type="number" step="0.01" min="0" name="bank_min" class="form-control form-control-sm" value="<?= e((string)$bankMin) ?>" style="width:120px">
    </div>
    <div>
      <label class="form-label form-label-sm mb-1">الأصناف الراكدة</label>
      <select name="stagnant_days" class="form-select form-select-sm" style="width:auto">
        <?php foreach ([30,60,90,180] as $d): ?>
          <option value="<?= $d ?>" <?= $stagnantDays===$d?'selected':'' ?>><?= $d ?> يوم</option>
        <?php endforeach; ?>
      </select>
    </div>
    <div>
      <label class="form-label form-label-sm mb-1">المسودات القديمة</label>
      <select name="draft_days" class="form-select form-select-sm" style="width:auto">
        <?php foreach ([3,7,14,30] as $d): ?>
          <option value="<?= $d ?>" <?= $draftDays===$d?'selected':'' ?>><?= $d ?> يوم</option>
        <?php endforeach; ?>
      </select>
    </div>
    <button class="btn btn-sm btn-primary">تحديث</button>
  </form>
</div>

<div class="row g-3 mb-4">
  <div class="col-lg col-md-6"><div class="card border-0 shadow-sm h-100"><div class="card-body"><div class="text-muted small">إجمالي التنبيهات</div><div class="display-6 fw-bold"><?= (int)$counts['total'] ?></div></div></div></div>
  <div class="col-lg col-md-6"><div class="card border-0 shadow-sm h-100"><div class="card-body"><div class="text-muted small">الشيكات</div><div class="display-6 fw-bold text-warning"><?= (int)$counts['checks']['total'] ?></div><div class="small text-muted">مرتدة / مستحقة / متأخرة</div></div></div></div>
  <div class="col-lg col-md-6"><div class="card border-0 shadow-sm h-100"><div class="card-body"><div class="text-muted small">المخزون</div><div class="display-6 fw-bold text-danger"><?= (int)$counts['inventory']['total'] ?></div><div class="small text-muted">منخفض أو نافد أو راكد</div></div></div></div>
  <div class="col-lg col-md-6"><div class="card border-0 shadow-sm h-100"><div class="card-body"><div class="text-muted small">الأطراف</div><div class="display-6 fw-bold text-info"><?= (int)$counts['parties']['total'] ?></div><div class="small text-muted">عملاء متأخرون / موردون مستحقون</div></div></div></div>
  <div class="col-lg col-md-6"><div class="card border-0 shadow-sm h-100"><div class="card-body"><div class="text-muted small">الخزن والبنوك</div><div class="display-6 fw-bold text-success"><?= (int)$counts['treasury']['total'] ?></div><div class="small text-muted">أرصدة منخفضة أو سالبة</div></div></div></div>
  <div class="col-lg col-md-6"><div class="card border-0 shadow-sm h-100"><div class="card-body"><div class="text-muted small">المسودات القديمة</div><div class="display-6 fw-bold text-secondary"><?= (int)$counts['drafts']['total'] ?></div><div class="small text-muted">بيع / شراء / مرتجعات</div></div></div></div>
</div>

<div class="row g-3">
  <div class="col-12">
    <div class="card border-0 shadow-sm">
      <div class="card-header bg-transparent d-flex justify-content-between align-items-center">
        <strong>تنبيهات الشيكات</strong>
      </div>
      <div class="card-body">
        <div class="row g-3 mb-3">
          <div class="col-md-3"><div class="p-3 rounded bg-light border"><div class="small text-muted">مرتدة</div><div class="fs-4 fw-bold text-danger"><?= count($checkReturned) ?></div></div></div>
          <div class="col-md-3"><div class="p-3 rounded bg-light border"><div class="small text-muted">اليوم</div><div class="fs-4 fw-bold text-warning"><?= count($checkDueToday) ?></div></div></div>
          <div class="col-md-3"><div class="p-3 rounded bg-light border"><div class="small text-muted">قريبًا</div><div class="fs-4 fw-bold text-primary"><?= count($checkDueSoon) ?></div></div></div>
          <div class="col-md-3"><div class="p-3 rounded bg-light border"><div class="small text-muted">متأخرة</div><div class="fs-4 fw-bold text-dark"><?= count($checkOverdue) ?></div></div></div>
        </div>
        <div class="table-responsive">
          <table class="table table-sm align-middle">
            <thead><tr><th>رقم الشيك</th><th>العميل الأصلي</th><th>الاستحقاق</th><th>الحالة</th><th></th></tr></thead>
            <tbody>
              <?php $allChecks = array_slice(array_merge($checkReturned, $checkOverdue, $checkDueToday, $checkDueSoon), 0, 12); ?>
              <?php if (!$allChecks): ?>
                <tr><td colspan="5" class="text-center text-muted py-3">لا توجد تنبيهات شيكات حاليًا</td></tr>
              <?php else: foreach ($allChecks as $c): ?>
                <tr>
                  <td><?= e($c['check_no']) ?></td>
                  <td><?= e($c['drawer_name'] ?? '-') ?></td>
                  <td><?= e($fmtDate($c['due_date'] ?? null)) ?></td>
                  <td><span class="badge text-bg-<?= $checkBadgeClass((string)($c['current_status'] ?? '')) ?>"><?= e(check_status_label((string)($c['current_status'] ?? ''))) ?></span></td>
                  <td><a class="btn btn-sm btn-outline-secondary" href="<?= e(url('/finance/checks/view?id='.(int)$c['id'])) ?>">فتح</a></td>
                </tr>
              <?php endforeach; endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>

  <div class="col-lg-6">
    <div class="card border-0 shadow-sm h-100">
      <div class="card-header bg-transparent d-flex justify-content-between align-items-center">
        <strong>تنبيهات المخزون</strong>
        <span class="small text-muted">يشمل الأصناف الراكدة</span>
        <a class="btn btn-sm btn-outline-primary" href="<?= e(url('/reports/inventory/stock')) ?>">تقرير المخزون</a>
      </div>
      <div class="card-body p-0">
        <div class="table-responsive">
          <table class="table table-sm align-middle mb-0">
            <thead><tr><th>الصنف</th><th>الرصيد</th><th>الحد</th><th>الحالة</th></tr></thead>
            <tbody>
              <?php if (!$inventoryRows): ?>
                <tr><td colspan="4" class="text-center text-muted py-3">لا توجد تنبيهات مخزون حاليًا</td></tr>
              <?php else: foreach ($inventoryRows as $r): $qty=(float)$r['qty']; $min=(float)$r['min_level']; ?>
                <tr>
                  <td><a href="<?= e(url('/inventory/items')) ?>?edit=<?= (int)$r['id'] ?>"><?= e($r['name']) ?></a></td>
                  <td><?= e($fmtMoney($qty)) ?></td>
                  <td><?= e($fmtMoney($min)) ?></td>
                  <td>
                    <?php if ($qty <= 0): ?><span class="badge text-bg-danger">نافد</span>
                    <?php else: ?><span class="badge text-bg-warning">منخفض</span><?php endif; ?>
                  </td>
                </tr>
              <?php endforeach; endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>

  <div class="col-lg-6">
    <div class="card border-0 shadow-sm h-100">
      <div class="card-header bg-transparent d-flex justify-content-between align-items-center">
        <strong>تنبيهات الأصناف الراكدة</strong>
        <span class="small text-muted">بدون حركة منذ <?= (int)$stagnantDays ?> يوم — قبل <?= e($fmtDate($stagnantCutoff)) ?></span>
      </div>
      <div class="card-body p-0">
        <div class="table-responsive">
          <table class="table table-sm align-middle mb-0">
            <thead><tr><th>الصنف</th><th>الباركود</th><th>الرصيد</th><th>آخر حركة</th></tr></thead>
            <tbody>
              <?php if (!$stagnantRows): ?>
                <tr><td colspan="4" class="text-center text-muted py-3">لا توجد أصناف راكدة حسب الشرط الحالي</td></tr>
              <?php else: foreach ($stagnantRows as $r): ?>
                <tr>
                  <td><a href="<?= e(url('/inventory/items')) ?>?edit=<?= (int)$r['id'] ?>"><?= e($r['name']) ?></a></td>
                  <td><?= e($r['barcode'] !== '' ? $r['barcode'] : '-') ?></td>
                  <td><?= e($fmtMoney($r['qty'])) ?></td>
                  <td><?= e($fmtDate($r['last_move_at'] ?? null)) ?></td>
                </tr>
              <?php endforeach; endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>

  <div class="col-lg-6">
    <div class="card border-0 shadow-sm h-100">
      <div class="card-header bg-transparent d-flex justify-content-between align-items-center">
        <strong>العملاء المتأخرون في السداد</strong>
        <span class="small text-muted">آخر حركة قبل <?= e($cutoff) ?></span>
      </div>
      <div class="card-body p-0">
        <div class="table-responsive">
          <table class="table table-sm align-middle mb-0">
            <thead><tr><th>العميل</th><th>الرصيد</th><th>آخر حركة</th><th></th></tr></thead>
            <tbody>
              <?php if (!$customerOverdue): ?>
                <tr><td colspan="4" class="text-center text-muted py-3">لا يوجد عملاء متأخرون حسب الشرط الحالي</td></tr>
              <?php else: foreach ($customerOverdue as $r): ?>
                <tr>
                  <td><?= e($r['name']) ?></td>
                  <td><?= e($fmtMoney($r['balance'])) ?></td>
                  <td><?= e($fmtDate($r['last_doc_date'] ?? null)) ?></td>
                  <td><a class="btn btn-sm btn-outline-secondary" href="<?= e(url('/reports/parties/customer-statement?party_id='.(int)$r['id'])) ?>">كشف الحساب</a></td>
                </tr>
              <?php endforeach; endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>

  <div class="col-lg-6">
    <div class="card border-0 shadow-sm h-100">
      <div class="card-header bg-transparent d-flex justify-content-between align-items-center">
        <strong>موردون لهم مستحقات قديمة</strong>
        <span class="small text-muted">آخر حركة قبل <?= e($cutoff) ?></span>
      </div>
      <div class="card-body p-0">
        <div class="table-responsive">
          <table class="table table-sm align-middle mb-0">
            <thead><tr><th>المورد</th><th>المستحق</th><th>آخر حركة</th><th></th></tr></thead>
            <tbody>
              <?php if (!$supplierDue): ?>
                <tr><td colspan="4" class="text-center text-muted py-3">لا توجد مستحقات موردين قديمة حسب الشرط الحالي</td></tr>
              <?php else: foreach ($supplierDue as $r): ?>
                <tr>
                  <td><?= e($r['name']) ?></td>
                  <td><?= e($fmtMoney(abs((float)$r['balance']))) ?></td>
                  <td><?= e($fmtDate($r['last_doc_date'] ?? null)) ?></td>
                  <td><a class="btn btn-sm btn-outline-secondary" href="<?= e(url('/reports/parties/supplier-statement?party_id='.(int)$r['id'])) ?>">كشف الحساب</a></td>
                </tr>
              <?php endforeach; endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>


  <div class="col-lg-6">
    <div class="card border-0 shadow-sm h-100">
      <div class="card-header bg-transparent d-flex justify-content-between align-items-center">
        <strong>تنبيهات الخزن</strong>
        <a class="btn btn-sm btn-outline-primary" href="<?= e(url('/finance/cashboxes')) ?>">الخزن</a>
      </div>
      <div class="card-body p-0">
        <div class="table-responsive">
          <table class="table table-sm align-middle mb-0">
            <thead><tr><th>الخزنة</th><th>الرصيد الحالي</th><th>الحالة</th><th></th></tr></thead>
            <tbody>
              <?php if (!$cashboxRows): ?>
                <tr><td colspan="4" class="text-center text-muted py-3">لا توجد تنبيهات خزن حسب الحد الحالي</td></tr>
              <?php else: foreach ($cashboxRows as $r): $bal=(float)$r['current_balance']; ?>
                <tr>
                  <td><?= e($r['name']) ?></td>
                  <td><?= e($fmtMoney($bal)) ?></td>
                  <td><?php if ($bal < 0): ?><span class="badge text-bg-danger">رصيد سالب</span><?php else: ?><span class="badge text-bg-warning">أقل من الحد</span><?php endif; ?></td>
                  <td><a class="btn btn-sm btn-outline-secondary" href="<?= e(url('/finance/cashboxes/ledger?cashbox_id='.(int)$r['id'])) ?>">الحركات</a></td>
                </tr>
              <?php endforeach; endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>

  <div class="col-lg-6">
    <div class="card border-0 shadow-sm h-100">
      <div class="card-header bg-transparent d-flex justify-content-between align-items-center">
        <strong>تنبيهات البنوك</strong>
        <a class="btn btn-sm btn-outline-primary" href="<?= e(url('/reports/finance/bank-balances')) ?>">أرصدة البنوك</a>
      </div>
      <div class="card-body p-0">
        <div class="table-responsive">
          <table class="table table-sm align-middle mb-0">
            <thead><tr><th>الحساب</th><th>الرصيد الحالي</th><th>الحالة</th><th></th></tr></thead>
            <tbody>
              <?php if (!$bankRows): ?>
                <tr><td colspan="4" class="text-center text-muted py-3">لا توجد تنبيهات بنوك حسب الحد الحالي</td></tr>
              <?php else: foreach ($bankRows as $r): $bal=(float)$r['current_balance']; ?>
                <tr>
                  <td>
                    <div class="fw-semibold"><?= e($r['name']) ?></div>
                    <div class="small text-muted"><?= e($r['bank_name'] ?? '') ?></div>
                  </td>
                  <td><?= e($fmtMoney($bal)) ?> <span class="small text-muted"><?= e($r['currency_code'] ?? 'EGP') ?></span></td>
                  <td><?php if ($bal < 0): ?><span class="badge text-bg-danger">رصيد سالب</span><?php else: ?><span class="badge text-bg-warning">أقل من الحد</span><?php endif; ?></td>
                  <td><a class="btn btn-sm btn-outline-secondary" href="<?= e(url('/reports/finance/bank-statement?bank_account_id='.(int)$r['id'])) ?>">كشف الحساب</a></td>
                </tr>
              <?php endforeach; endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>

  <div class="col-12">
    <div class="card border-0 shadow-sm">
      <div class="card-header bg-transparent d-flex justify-content-between align-items-center">
        <strong>تنبيهات المستندات المسودة القديمة</strong>
        <span class="small text-muted">المستندات الأقدم من <?= (int)$draftDays ?> يوم — قبل <?= e($fmtDate($draftCutoff)) ?></span>
      </div>
      <div class="card-body">
        <div class="row g-3 mb-3">
          <div class="col-md-3"><div class="p-3 rounded bg-light border"><div class="small text-muted">فواتير البيع</div><div class="fs-4 fw-bold text-secondary"><?= count($draftSales) ?></div></div></div>
          <div class="col-md-3"><div class="p-3 rounded bg-light border"><div class="small text-muted">فواتير الشراء</div><div class="fs-4 fw-bold text-secondary"><?= count($draftPurchases) ?></div></div></div>
          <div class="col-md-3"><div class="p-3 rounded bg-light border"><div class="small text-muted">مرتجعات البيع</div><div class="fs-4 fw-bold text-secondary"><?= count($draftSalesReturns) ?></div></div></div>
          <div class="col-md-3"><div class="p-3 rounded bg-light border"><div class="small text-muted">مرتجعات الشراء</div><div class="fs-4 fw-bold text-secondary"><?= count($draftPurchaseReturns) ?></div></div></div>
        </div>
        <div class="row g-3">
          <div class="col-lg-6">
            <div class="table-responsive">
              <table class="table table-sm align-middle">
                <thead><tr><th colspan="5">فواتير البيع المسودة</th></tr><tr><th>الرقم</th><th>التاريخ</th><th>القيمة</th><th>الإنشاء</th><th></th></tr></thead>
                <tbody>
                  <?php if (!$draftSales): ?><tr><td colspan="5" class="text-center text-muted py-3">لا توجد مسودات قديمة</td></tr>
                  <?php else: foreach ($draftSales as $r): ?>
                    <tr><td><?= e($r['doc_no']) ?></td><td><?= e($fmtDate($r['doc_date'])) ?></td><td><?= e($fmtMoney($r['total'])) ?></td><td><?= e($fmtDate($r['created_at'])) ?></td><td><a class="btn btn-sm btn-outline-secondary" href="<?= e(url('/sales/invoices/form?id='.(int)$r['id'])) ?>">فتح</a></td></tr>
                  <?php endforeach; endif; ?>
                </tbody>
              </table>
            </div>
          </div>
          <div class="col-lg-6">
            <div class="table-responsive">
              <table class="table table-sm align-middle">
                <thead><tr><th colspan="5">فواتير الشراء المسودة</th></tr><tr><th>الرقم</th><th>التاريخ</th><th>القيمة</th><th>الإنشاء</th><th></th></tr></thead>
                <tbody>
                  <?php if (!$draftPurchases): ?><tr><td colspan="5" class="text-center text-muted py-3">لا توجد مسودات قديمة</td></tr>
                  <?php else: foreach ($draftPurchases as $r): ?>
                    <tr><td><?= e($r['doc_no']) ?></td><td><?= e($fmtDate($r['doc_date'])) ?></td><td><?= e($fmtMoney($r['total'])) ?></td><td><?= e($fmtDate($r['created_at'])) ?></td><td><a class="btn btn-sm btn-outline-secondary" href="<?= e(url('/purchases/invoices/form?id='.(int)$r['id'])) ?>">فتح</a></td></tr>
                  <?php endforeach; endif; ?>
                </tbody>
              </table>
            </div>
          </div>
          <div class="col-lg-6">
            <div class="table-responsive">
              <table class="table table-sm align-middle">
                <thead><tr><th colspan="5">مرتجعات البيع المسودة</th></tr><tr><th>الرقم</th><th>التاريخ</th><th>القيمة</th><th>الإنشاء</th><th></th></tr></thead>
                <tbody>
                  <?php if (!$draftSalesReturns): ?><tr><td colspan="5" class="text-center text-muted py-3">لا توجد مسودات قديمة</td></tr>
                  <?php else: foreach ($draftSalesReturns as $r): ?>
                    <tr><td><?= e($r['doc_no']) ?></td><td><?= e($fmtDate($r['doc_date'])) ?></td><td><?= e($fmtMoney($r['total'])) ?></td><td><?= e($fmtDate($r['created_at'])) ?></td><td><a class="btn btn-sm btn-outline-secondary" href="<?= e(url('/sales/returns/view?id='.(int)$r['id'])) ?>">فتح</a></td></tr>
                  <?php endforeach; endif; ?>
                </tbody>
              </table>
            </div>
          </div>
          <div class="col-lg-6">
            <div class="table-responsive">
              <table class="table table-sm align-middle">
                <thead><tr><th colspan="5">مرتجعات الشراء المسودة</th></tr><tr><th>الرقم</th><th>التاريخ</th><th>القيمة</th><th>الإنشاء</th><th></th></tr></thead>
                <tbody>
                  <?php if (!$draftPurchaseReturns): ?><tr><td colspan="5" class="text-center text-muted py-3">لا توجد مسودات قديمة</td></tr>
                  <?php else: foreach ($draftPurchaseReturns as $r): ?>
                    <tr><td><?= e($r['doc_no']) ?></td><td><?= e($fmtDate($r['doc_date'])) ?></td><td><?= e($fmtMoney($r['total'])) ?></td><td><?= e($fmtDate($r['created_at'])) ?></td><td><a class="btn btn-sm btn-outline-secondary" href="<?= e(url('/purchases/returns/view?id='.(int)$r['id'])) ?>">فتح</a></td></tr>
                  <?php endforeach; endif; ?>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

</div>

</div>
