<?php use App\Shared\Support\RoutePaths; ?>
<?php $canPos = can('sales.pos'); ?>
<?php
$today_sales  = $today_sales ?? ['c' => 0, 's' => 0];
$today_returns = $today_returns ?? ['c' => 0, 's' => 0];
$items_count  = (int)($items_count ?? 0);
$low_count    = (int)($low_count ?? 0);
$draft_invoices = (int)($draft_invoices ?? 0);
$suspended_count = (int)($suspended_count ?? 0);
$suspended_preview = $suspended_preview ?? [];
$latest_sales = $latest_sales ?? [];
$latest_returns = $latest_returns ?? [];
?>
<div class="page-actions-bar mb-3">
  <a class="btn btn-outline-primary" href="<?= e(url('/sales/invoices')) ?>"><i class="fa-solid fa-file-invoice-dollar me-1"></i>فواتير المبيعات</a>
  <a class="btn btn-primary" href="<?= e(url('/sales/invoices/form')) ?>"><i class="fa-solid fa-plus me-1"></i>فاتورة جديدة</a>
  <?php if ($canPos): ?><a class="btn btn-success" href="<?= e(url(RoutePaths::posBase())) ?>"><i class="fa-solid fa-cash-register me-1"></i>نقطة البيع</a><?php else: ?><button type="button" class="btn btn-outline-secondary" disabled title="لا تملك صلاحية استخدام نقطة البيع"><i class="fa-solid fa-cash-register me-1"></i>نقطة البيع</button><?php endif; ?>
  <a class="btn btn-outline-secondary" href="<?= e(url('/sales/returns')) ?>"><i class="fa-solid fa-rotate-left me-1"></i>مرتجعات البيع</a>
</div>

<div class="sales-kpis-grid mb-4">
  <div class="sales-kpi-card sales-kpi-card--primary">
    <div class="sales-kpi-card__label">مبيعات اليوم</div>
    <div class="sales-kpi-card__value"><?= format_money($today_sales['s'] ?? 0) ?></div>
    <div class="sales-kpi-card__meta"><?= (int)($today_sales['c'] ?? 0) ?> فاتورة</div>
  </div>
  <div class="sales-kpi-card sales-kpi-card--success">
    <div class="sales-kpi-card__label">مرتجعات اليوم</div>
    <div class="sales-kpi-card__value"><?= format_money($today_returns['s'] ?? 0) ?></div>
    <div class="sales-kpi-card__meta"><?= (int)($today_returns['c'] ?? 0) ?> مرتجع</div>
  </div>
  <div class="sales-kpi-card sales-kpi-card--info">
    <div class="sales-kpi-card__label">المسودات</div>
    <div class="sales-kpi-card__value"><?= (int)$draft_invoices ?></div>
    <div class="sales-kpi-card__meta">فواتير غير مرحلة</div>
  </div>
  <div class="sales-kpi-card sales-kpi-card--warning">
    <div class="sales-kpi-card__label">السلال المعلقة</div>
    <div class="sales-kpi-card__value"><?= (int)$suspended_count ?></div>
    <div class="sales-kpi-card__meta">جاهزة للاستكمال من POS</div>
  </div>
  <div class="sales-kpi-card sales-kpi-card--neutral">
    <div class="sales-kpi-card__label">الأصناف</div>
    <div class="sales-kpi-card__value"><?= (int)$items_count ?></div>
    <div class="sales-kpi-card__meta">نقص مخزون: <?= (int)$low_count ?></div>
  </div>
</div>

<div class="sales-quick-links mb-4">
  <a class="sales-quick-link" href="<?= e(url('/sales/invoices/form')) ?>"><i class="fa-solid fa-plus"></i><span>إنشاء فاتورة بيع</span></a>
  <?php if ($canPos): ?><a class="sales-quick-link" href="<?= e(url(RoutePaths::posBase())) ?>"><i class="fa-solid fa-cash-register"></i><span>نقطة البيع</span></a><?php else: ?><span class="sales-quick-link disabled opacity-50" title="لا تملك صلاحية استخدام نقطة البيع"><i class="fa-solid fa-cash-register"></i><span>نقطة البيع</span></span><?php endif; ?>
  <a class="sales-quick-link" href="<?= e(url(RoutePaths::receiptsForm())) ?>"><i class="fa-solid fa-hand-holding-dollar"></i><span>سند قبض</span></a>
  <a class="sales-quick-link" href="<?= e(url('/sales/quotations')) ?>"><i class="fa-solid fa-file-signature"></i><span>عروض الأسعار</span></a>
  <a class="sales-quick-link" href="<?= e(url('/sales/returns')) ?>"><i class="fa-solid fa-rotate-left"></i><span>مرتجعات البيع</span></a>
  <a class="sales-quick-link" href="<?= e(url('/parties/customers')) ?>"><i class="fa-solid fa-users"></i><span>العملاء</span></a>
</div>

<div class="row g-3">
  <div class="col-12 col-xl-7">
    <div class="content-card h-100">
      <div class="card-header d-flex justify-content-between align-items-center">
        <span>آخر فواتير البيع</span>
        <a class="btn btn-sm btn-outline-primary" href="<?= e(url('/sales/invoices')) ?>">عرض الكل</a>
      </div>
      <div class="card-body p-0">
        <div class="table-responsive">
          <table class="table table-clean align-middle mb-0">
            <thead>
              <tr>
                <th>الرقم</th>
                <th>العميل</th>
                <th>التاريخ</th>
                <th>القيمة</th>
                <th>الحالة</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              <?php if (!$latest_sales): ?>
                <tr><td colspan="6" class="text-center text-muted py-4">لا توجد فواتير بيع بعد.</td></tr>
              <?php else: foreach ($latest_sales as $inv): ?>
                <tr>
                  <td class="fw-bold"><?= e((string)($inv['invoice_no'] ?? '')) ?></td>
                  <td><?= e((string)($inv['party_name'] ?? '')) ?></td>
                  <td><?= e((string)($inv['invoice_date'] ?? '')) ?></td>
                  <td><?= format_money((float)($inv['grand_total'] ?? 0)) ?></td>
                  <td><span class="badge text-bg-<?= (($inv['status'] ?? '') === 'POSTED') ? 'success' : 'secondary' ?>"><?= e((string)($inv['status'] ?? 'draft')) ?></span></td>
                  <td><a class="btn btn-sm btn-outline-secondary" href="<?= e(url('/sales/invoices/view?id='.(int)($inv['id'] ?? 0))) ?>">عرض</a></td>
                </tr>
              <?php endforeach; endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>

  <div class="col-12 col-xl-5">
    <div class="content-card h-100">
      <div class="card-header d-flex justify-content-between align-items-center">
        <span>ملخص السلال المعلقة</span>
        <?php if ($canPos): ?><a class="btn btn-sm btn-outline-warning" href="<?= e(url(RoutePaths::posSuspendedBase())) ?>">إدارة السلال</a><?php endif; ?>
      </div>
      <div class="card-body">
        <?php if (!$suspended_preview): ?>
          <div class="text-muted text-center py-4">لا توجد سلال معلقة حاليًا.</div>
        <?php else: ?>
          <div class="sales-suspended-list">
            <?php foreach ($suspended_preview as $sc): $cart = (array)($sc['cart'] ?? []); ?>
              <div class="sales-suspended-item">
                <div>
                  <div class="fw-bold">سلة معلقة #<?= e((string)($sc['id'] ?? '')) ?></div>
                  <div class="small text-muted"><?= e((string)($sc['created_at'] ?? '')) ?></div>
                  <div class="small text-muted">عدد الأصناف: <?= count($cart) ?><?= isset($sc['cart_total']) ? ' • الإجمالي: '.format_money((float)$sc['cart_total']) : '' ?></div>
                </div>
                <div class="d-flex gap-2 flex-wrap">
                  <a class="btn btn-sm btn-outline-primary" href="<?= e(url(RoutePaths::posBase() . '?action=resume&sid=' . urlencode((string)($sc['id'] ?? '')))) ?>">استكمال</a>
                  <a class="btn btn-sm btn-outline-danger" href="<?= e(url(RoutePaths::posBase() . '?action=delete_suspend&sid=' . urlencode((string)($sc['id'] ?? '')))) ?>" onclick="return confirm('حذف السلة المعلقة؟')">حذف</a>
                </div>
              </div>
            <?php endforeach; ?>
          </div>
        <?php endif; ?>
      </div>
    </div>
  </div>

  <div class="col-12">
    <div class="content-card">
      <div class="card-header d-flex justify-content-between align-items-center">
        <span>آخر مرتجعات البيع</span>
        <a class="btn btn-sm btn-outline-secondary" href="<?= e(url('/sales/returns')) ?>">عرض الكل</a>
      </div>
      <div class="card-body p-0">
        <div class="table-responsive">
          <table class="table table-clean align-middle mb-0">
            <thead>
              <tr>
                <th>الرقم</th>
                <th>العميل</th>
                <th>التاريخ</th>
                <th>القيمة</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              <?php if (!$latest_returns): ?>
                <tr><td colspan="5" class="text-center text-muted py-4">لا توجد مرتجعات بيع بعد.</td></tr>
              <?php else: foreach ($latest_returns as $ret): ?>
                <tr>
                  <td class="fw-bold"><?= e((string)($ret['return_no'] ?? '')) ?></td>
                  <td><?= e((string)($ret['party_name'] ?? '')) ?></td>
                  <td><?= e((string)($ret['return_date'] ?? '')) ?></td>
                  <td><?= format_money((float)($ret['grand_total'] ?? 0)) ?></td>
                  <td><a class="btn btn-sm btn-outline-secondary" href="<?= e(url('/sales/returns/view?id='.(int)($ret['id'] ?? 0))) ?>">عرض</a></td>
                </tr>
              <?php endforeach; endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>
