<?php
// finance.php - Finance Dashboard (Branch-aware + Permission can_finance)
declare(strict_types=1);
session_start();

require_once __DIR__ . '/db.php';
require_once __DIR__ . '/inc/app_url.php';
require_once __DIR__ . '/inc/auth.php';

require_login();

/* صلاحية المالية */
if (!function_exists('can_finance') || !can_finance()) {
  http_response_code(403);
  exit('غير مصرح');
}

$pdo = db();
if (!$pdo instanceof PDO) { http_response_code(500); die('DB not ready'); }
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

/* Debug: finance.php?debug=1 */
$debug = (isset($_GET['debug']) && $_GET['debug'] === '1');
if ($debug) {
  ini_set('display_errors','1');
  ini_set('display_startup_errors','1');
  error_reporting(E_ALL);
}

/* Helpers */
function h($s): string { return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
function u(string $path): string { return app_url($path); }

function table_exists(PDO $pdo, string $table): bool {
  try {
    $db = (string)$pdo->query("SELECT DATABASE()")->fetchColumn();
    if ($db === '') return false;
    $st = $pdo->prepare("SELECT 1 FROM information_schema.tables WHERE table_schema=? AND table_name=? LIMIT 1");
    $st->execute([$db, $table]);
    return (bool)$st->fetchColumn();
  } catch (Throwable $e) { return false; }
}
function col_exists(PDO $pdo, string $table, string $col): bool {
  try {
    $db = (string)$pdo->query("SELECT DATABASE()")->fetchColumn();
    if ($db === '') return false;
    $st = $pdo->prepare("SELECT 1 FROM information_schema.columns WHERE table_schema=? AND table_name=? AND column_name=? LIMIT 1");
    $st->execute([$db, $table, $col]);
    return (bool)$st->fetchColumn();
  } catch (Throwable $e) { return false; }
}
function money(float $v): string { return number_format($v, 2) . ' AED'; }
function money_short(float $v): string {
  if ($v >= 1000000) return rtrim(rtrim(number_format($v/1000000, 1, '.', ''), '0'), '.') . 'M';
  if ($v >= 1000)    return rtrim(rtrim(number_format($v/1000, 1, '.', ''), '0'), '.') . 'K';
  return (string)(int)$v;
}

/* Session basics */
$name = (string)($_SESSION['name'] ?? $_SESSION['username'] ?? 'مستخدم');
$role = strtoupper((string)($_SESSION['role'] ?? 'STAFF'));
$logo = "https://hamdanlegalgroup.ae/wp-content/uploads/2026/02/logomail.png";

/* Branch */
$branchId = (int)($_SESSION['branch_id'] ?? 1);
if ($branchId <= 0) $branchId = 1;

function getBranchName(PDO $pdo, int $branchId): string {
  $fallback = ($branchId === 2) ? 'دبي' : 'أبوظبي';
  if (!table_exists($pdo,'branches') || !col_exists($pdo,'branches','name_ar')) return $fallback;
  try {
    $st = $pdo->prepare("SELECT name_ar FROM branches WHERE id=? LIMIT 1");
    $st->execute([$branchId]);
    $n = trim((string)($st->fetchColumn() ?: ''));
    return $n !== '' ? $n : $fallback;
  } catch (Throwable $e) { return $fallback; }
}
$currentBranchName = getBranchName($pdo, $branchId);

/* Validate invoices */
$hasInvoices = table_exists($pdo,'invoices');

$metrics = [
  'due_amount' => 0.0,
  'overdue_count' => 0,
  'paid_this_month' => 0.0,
  'total_invoices' => 0,
  'unpaid_count' => 0,
  'partial_count' => 0,
  'paid_count' => 0,
];

$recentInvoices = [];
$topClients = [];
$monthly = []; // last 6 months paid & due

if ($hasInvoices) {
  $invBranchCol = col_exists($pdo,'invoices','branch_id') ? 'branch_id' : '';
  $totalCol     = col_exists($pdo,'invoices','total_amount') ? 'total_amount' : (col_exists($pdo,'invoices','total') ? 'total' : '');
  $paidCol      = col_exists($pdo,'invoices','paid_amount') ? 'paid_amount' : (col_exists($pdo,'invoices','paid') ? 'paid' : '');
  $dueDateCol   = col_exists($pdo,'invoices','due_date') ? 'due_date' : '';
  $statusCol    = col_exists($pdo,'invoices','status') ? 'status' : '';
  $createdAtCol = col_exists($pdo,'invoices','created_at') ? 'created_at' : '';

  $where = "1=1";
  $par = [];
  if ($invBranchCol !== '') { $where = "`$invBranchCol`=?"; $par[] = $branchId; }

  if ($totalCol !== '' && $paidCol !== '') {
    // 1) المبالغ المستحقة
    $sql = "SELECT COALESCE(SUM(GREATEST((`$totalCol` - `$paidCol`),0)),0)
            FROM invoices
            WHERE $where AND (UPPER(`$statusCol`) IN ('UNPAID','PARTIAL') OR (`$totalCol` - `$paidCol`) > 0)";
    $st = $pdo->prepare($sql);
    $st->execute($par);
    $metrics['due_amount'] = (float)($st->fetchColumn() ?: 0);

    // 2) فواتير متأخرة
    if ($dueDateCol !== '') {
      $sql = "SELECT COUNT(*)
              FROM invoices
              WHERE $where
                AND `$dueDateCol` IS NOT NULL
                AND `$dueDateCol` < CURDATE()
                AND (`$totalCol` - `$paidCol`) > 0";
      $st = $pdo->prepare($sql);
      $st->execute($par);
      $metrics['overdue_count'] = (int)($st->fetchColumn() ?: 0);
    }

    // 3) المدفوع هذا الشهر
    if ($createdAtCol !== '') {
      $sql = "SELECT COALESCE(SUM(`$paidCol`),0)
              FROM invoices
              WHERE $where
                AND `$createdAtCol` >= DATE_FORMAT(CURDATE(), '%Y-%m-01')
                AND `$createdAtCol` <  DATE_ADD(DATE_FORMAT(CURDATE(), '%Y-%m-01'), INTERVAL 1 MONTH)";
      $st = $pdo->prepare($sql);
      $st->execute($par);
      $metrics['paid_this_month'] = (float)($st->fetchColumn() ?: 0);
    }

    // 4) إجمالي الفواتير
    $sql = "SELECT COUNT(*) FROM invoices WHERE $where";
    $st = $pdo->prepare($sql);
    $st->execute($par);
    $metrics['total_invoices'] = (int)($st->fetchColumn() ?: 0);

    // 5) توزيع الحالات (UNPAID / PARTIAL / PAID)
    if ($statusCol !== '') {
      $sql = "SELECT UPPER(`$statusCol`) st, COUNT(*) c
              FROM invoices
              WHERE $where
              GROUP BY UPPER(`$statusCol`)";
      $st = $pdo->prepare($sql);
      $st->execute($par);
      $map = [];
      foreach ($st->fetchAll() as $r) $map[(string)($r['st'] ?? '')] = (int)($r['c'] ?? 0);
      $metrics['unpaid_count']  = $map['UNPAID']  ?? 0;
      $metrics['partial_count'] = $map['PARTIAL'] ?? 0;
      $metrics['paid_count']    = $map['PAID']    ?? 0;
    }

    // 6) أحدث الفواتير
    $colsWant = [
      "id",
      ($createdAtCol !== '' ? "`$createdAtCol` AS created_at" : "NULL AS created_at"),
      ($dueDateCol   !== '' ? "`$dueDateCol` AS due_date" : "NULL AS due_date"),
      ($statusCol    !== '' ? "`$statusCol` AS status" : "NULL AS status"),
      "`$totalCol` AS total_amount",
      "`$paidCol` AS paid_amount",
      (col_exists($pdo,'invoices','client_name') ? "client_name" : "'' AS client_name"),
      (col_exists($pdo,'invoices','case_id') ? "case_id" : "NULL AS case_id"),
    ];
    $sql = "SELECT ".implode(',', $colsWant)."
            FROM invoices
            WHERE $where
            ORDER BY id DESC
            LIMIT 12";
    $st = $pdo->prepare($sql);
    $st->execute($par);
    $recentInvoices = $st->fetchAll();

    // 7) أفضل العملاء حسب المبالغ المستحقة (Top 6)
    if (col_exists($pdo,'invoices','client_name')) {
      $sql = "SELECT client_name,
                     COALESCE(SUM(GREATEST((`$totalCol`-`$paidCol`),0)),0) AS due_sum
              FROM invoices
              WHERE $where
              GROUP BY client_name
              ORDER BY due_sum DESC
              LIMIT 6";
      $st = $pdo->prepare($sql);
      $st->execute($par);
      $topClients = $st->fetchAll();
    }

    // 8) مؤشر آخر 6 أشهر (مدفوع + مستحق)
    if ($createdAtCol !== '') {
      $sql = "SELECT
                DATE_FORMAT(`$createdAtCol`, '%Y-%m') ym,
                COALESCE(SUM(`$paidCol`),0) paid_sum,
                COALESCE(SUM(GREATEST((`$totalCol`-`$paidCol`),0)),0) due_sum
              FROM invoices
              WHERE $where
                AND `$createdAtCol` >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH)
              GROUP BY ym
              ORDER BY ym ASC";
      $st = $pdo->prepare($sql);
      $st->execute($par);
      $monthly = $st->fetchAll();
    }
  }
}

/* UI helpers */
function badge_status(?string $st): array {
  $s = strtoupper(trim((string)$st));
  return match($s){
    'PAID'    => ['مدفوعة','paid'],
    'PARTIAL' => ['جزئية','partial'],
    'UNPAID'  => ['غير مدفوعة','unpaid'],
    default   => ['-','default'],
  };
}
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1" />
  <title>المالية</title>
  <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700;800&display=swap" rel="stylesheet">
  <style>
    :root{
      --hlg-dark:#0f2a33;--hlg-dark2:#0b2230;--hlg-teal:#006a7a;--hlg-gold:#d4af37;
      --bg:#f4f7f8;--card:#fff;--muted:#6b7a7f;--border:#e6edef;
      --radius:18px;--sidebar-w:280px;--topbar-h:68px;--ring:0 0 0 4px rgba(0,106,122,.12);
    }
    *{box-sizing:border-box}
    body{margin:0;font-family:"Tajawal",system-ui;background:linear-gradient(180deg,#fff,var(--bg));color:#0b1b1f}
    a{color:inherit;text-decoration:none}
    .app{min-height:100vh;display:grid;grid-template-columns:var(--sidebar-w) 1fr;}
    .sidebar{background:linear-gradient(180deg,#0b2230,#0a1d28);color:#eaf5f7;padding:18px 16px;position:sticky;top:0;height:100vh;overflow:auto}
    .brand{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:10px 10px 16px;border-bottom:1px solid rgba(255,255,255,.08);margin-bottom:14px}
    .brand-left{display:flex;align-items:center;gap:12px;min-width:0}
    .brand-logo{width:46px;height:46px;border-radius:14px;background:rgba(255,255,255,.10);border:1px solid rgba(255,255,255,.14);display:flex;align-items:center;justify-content:center;overflow:hidden}
    .brand-logo img{width:100%;height:100%;object-fit:contain;padding:8px}
    .brand-title{display:flex;flex-direction:column;gap:2px;min-width:0}
    .brand-title .name{font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
    .brand-title .sub{font-size:12.5px;opacity:.85;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
    .nav{margin-top:10px;display:grid;gap:6px}
    .nav a{display:flex;align-items:center;justify-content:space-between;gap:10px;padding:11px 12px;border-radius:14px;color:#eaf5f7;border:1px solid transparent;transition:.15s ease}
    .nav a:hover{background:rgba(255,255,255,.06);border-color:rgba(255,255,255,.08)}
    .nav a.active{background:rgba(255,255,255,.08);border-color:rgba(255,255,255,.10)}
    .nav .label{font-weight:700;opacity:.95}
    .pill{font-size:12px;color:#d7f3f7;background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.10);padding:4px 8px;border-radius:999px;opacity:.9}
    .logout{margin-top:16px;padding-top:14px;border-top:1px solid rgba(255,255,255,.08);display:flex;gap:10px;align-items:center;justify-content:space-between;opacity:.95}
    .logout a{display:inline-flex;align-items:center;gap:8px;padding:10px 12px;border-radius:14px;background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.10)}
    .main{min-width:0;padding:18px 22px 26px}

    .topbar{height:var(--topbar-h);display:flex;align-items:center;justify-content:space-between;gap:14px;padding:10px 12px;background:#fff;border:1px solid var(--border);
      border-radius:var(--radius);box-shadow:0 10px 25px rgba(0,0,0,.05);position:sticky;top:12px;z-index:10}
    .branch-dot{width:10px;height:10px;border-radius:50%;background:var(--hlg-teal);box-shadow:0 0 0 4px rgba(0,106,122,.12)}
    .muted{color:var(--muted);font-size:13px}

    .page-head{margin:18px 6px 14px;display:flex;align-items:flex-end;justify-content:space-between;gap:12px;flex-wrap:wrap}
    .pageTitle{font-size:30px;font-weight:900;color:#0f2a33;margin:0}
    .pageSub{color:var(--muted);font-size:14px}

    .cards{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:14px;margin-top:10px}
    @media(max-width:1200px){.cards{grid-template-columns:repeat(2,minmax(0,1fr))}}
    @media(max-width:620px){.app{grid-template-columns:1fr}.sidebar{position:relative;height:auto}.cards{grid-template-columns:1fr}}

    .cardStat{background:var(--card);border:1px solid var(--border);border-radius:var(--radius);box-shadow:0 10px 25px rgba(0,0,0,.05);
      padding:16px;display:flex;align-items:center;justify-content:space-between;gap:10px;min-height:92px}
    .cardStat.danger{border-color:rgba(220,38,38,.25);box-shadow:0 10px 25px rgba(220,38,38,.10)}
    .val{font-size:26px;font-weight:900;color:#0f2a33;line-height:1}
    .lab{color:var(--muted);font-size:13px;font-weight:800}
    .ico{width:44px;height:44px;border-radius:14px;background:#f3f7f8;border:1px solid var(--border);display:flex;align-items:center;justify-content:center}

    .grid{margin-top:14px;display:grid;grid-template-columns:1.15fr .85fr;gap:14px}
    @media(max-width:1100px){.grid{grid-template-columns:1fr}}
    .box{background:var(--card);border:1px solid var(--border);border-radius:var(--radius);box-shadow:0 10px 25px rgba(0,0,0,.05);overflow:hidden}
    .box .head{padding:14px 16px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--border)}
    .box .head .title{font-size:16px;font-weight:900;color:#0f2a33}
    .box .body{padding:12px 14px}

    .bars{display:grid;gap:10px}
    .barRow{display:grid;grid-template-columns:90px 1fr 90px;gap:10px;align-items:center}
    .barLabel{font-weight:900;color:#0f2a33}
    .barTrack{height:12px;border-radius:999px;background:#f1f5f6;border:1px solid var(--border);overflow:hidden}
    .barFill{height:100%;width:0%;background:linear-gradient(90deg,var(--hlg-teal),#0aa6b5)}
    .barVal{font-weight:900;color:#0f2a33;text-align:left;direction:ltr}

    table{width:100%;border-collapse:collapse}
    th,td{padding:12px 10px;border-bottom:1px solid var(--border);text-align:right;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
    th{background:#f8fafb;color:#51666c;font-size:13px;font-weight:900}
    td{font-size:13px;color:#0f2a33}
    .tag{font-size:12px;padding:6px 10px;border-radius:999px;border:1px solid var(--border);background:#fbfeff;font-weight:900}
    .tag.paid{background:rgba(16,185,129,.10);border-color:rgba(16,185,129,.18);color:#047857}
    .tag.partial{background:rgba(245,158,11,.10);border-color:rgba(245,158,11,.20);color:#9a5b07}
    .tag.unpaid{background:rgba(220,38,38,.10);border-color:rgba(220,38,38,.20);color:#b91c1c}
    .tag.default{background:rgba(148,163,184,.12);border-color:rgba(148,163,184,.20);color:#334155}

    .note{margin-top:12px;color:var(--muted);font-size:12.5px}
  </style>
</head>
<body>
<div class="app">

  <aside class="sidebar">
    <div class="brand">
      <div class="brand-left">
        <div class="brand-logo"><img src="<?=h($logo)?>" alt="HLG"></div>
        <div class="brand-title">
          <div class="name">مجموعة حمدان القانونية</div>
          <div class="sub">بوابة إدارة الأعمال القانونية</div>
        </div>
      </div>
    </div>

    <nav class="nav">
      <a class="<?= basename($_SERVER['PHP_SELF'])==='dashboard.php'?'active':''; ?>" href="<?=h(u('dashboard.php'))?>">
        <span class="label">الرئيسية</span><span class="pill">لوحة التحكم</span>
      </a>
      <a class="<?= basename($_SERVER['PHP_SELF'])==='cases.php'?'active':''; ?>" href="<?=h(u('cases.php'))?>">
        <span class="label">القضايا</span><span class="pill">إدارة</span>
      </a>
      <a class="<?= basename($_SERVER['PHP_SELF'])==='tasks.php'?'active':''; ?>" href="<?=h(u('tasks.php'))?>">
        <span class="label">المهام</span><span class="pill">متابعة</span>
      </a>
      <a href="<?=h(u('hr_employee_form.php'))?>"><span class="label">شؤون الموظفين</span><span class="pill">HR</span></a>

      <a class="<?= basename($_SERVER['PHP_SELF'])==='finance.php'?'active':''; ?>" href="<?=h(u('finance.php'))?>">
        <span class="label">المالية</span><span class="pill">Finance</span>
      </a>

      <?php if (in_array($role, ['OWNER','ADMIN'], true)): ?>
        <a class="<?= basename($_SERVER['PHP_SELF'])==='permissions_manage.php'?'active':''; ?>" href="<?=h(u('permissions_manage.php'))?>">
          <span class="label">الصلاحيات</span><span class="pill">تحكم</span>
        </a>
      <?php endif; ?>
    </nav>

    <div class="logout">
      <div style="min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;"><?=h($name)?></div>
      <a href="<?=h(u('logout.php'))?>">خروج</a>
    </div>
  </aside>

  <main class="main">
    <div class="topbar">
      <div style="display:flex;align-items:center;gap:10px;">
        <span class="branch-dot"></span>
        <div>
          <div style="font-weight:900">المالية</div>
          <div class="muted">الفرع الحالي: <?=h($currentBranchName)?></div>
        </div>
      </div>
      <a href="<?=h(u('dashboard.php'))?>" class="muted" style="font-weight:900;">↩ العودة للداشبورد</a>
    </div>

    <div class="page-head">
      <div>
        <h1 class="pageTitle">مؤشرات مالية</h1>
        <div class="pageSub">ملخص سريع للفواتير والتحصيل حسب الفرع</div>
      </div>
    </div>

    <?php if (!$hasInvoices): ?>
      <div class="box">
        <div class="head"><div class="title">تنبيه</div></div>
        <div class="body">لم يتم العثور على جدول invoices.</div>
      </div>
    <?php else: ?>
      <section class="cards">
        <div class="cardStat">
          <div>
            <div class="val"><?=h(money_short((float)$metrics['due_amount']))?></div>
            <div class="lab">المبالغ المستحقة</div>
            <div class="muted" style="font-size:12px;direction:ltr;text-align:left;"><?=h(money((float)$metrics['due_amount']))?></div>
          </div>
          <div class="ico">💰</div>
        </div>

        <div class="cardStat <?= ((int)$metrics['overdue_count']>0 ? 'danger' : '') ?>">
          <div>
            <div class="val"><?=(int)$metrics['overdue_count']?></div>
            <div class="lab">فواتير متأخرة</div>
            <div class="muted" style="font-size:12px;">قبل تاريخ الاستحقاق</div>
          </div>
          <div class="ico">⏰</div>
        </div>

        <div class="cardStat">
          <div>
            <div class="val"><?=h(money_short((float)$metrics['paid_this_month']))?></div>
            <div class="lab">المدفوع هذا الشهر</div>
            <div class="muted" style="font-size:12px;direction:ltr;text-align:left;"><?=h(money((float)$metrics['paid_this_month']))?></div>
          </div>
          <div class="ico">✅</div>
        </div>

        <div class="cardStat">
          <div>
            <div class="val"><?=(int)$metrics['total_invoices']?></div>
            <div class="lab">إجمالي الفواتير</div>
            <div class="muted" style="font-size:12px;">كل الحالات</div>
          </div>
          <div class="ico">🧾</div>
        </div>
      </section>

      <section class="grid">
        <div class="box">
          <div class="head">
            <div class="title">توزيع حالات الفواتير</div>
            <div class="muted">Paid / Partial / Unpaid</div>
          </div>
          <div class="body">
            <?php
              $total = (int)$metrics['total_invoices'];
              $pPaid    = $total ? round(((int)$metrics['paid_count']    / $total) * 100) : 0;
              $pPartial = $total ? round(((int)$metrics['partial_count'] / $total) * 100) : 0;
              $pUnpaid  = $total ? round(((int)$metrics['unpaid_count']  / $total) * 100) : 0;
            ?>
            <div class="bars">
              <div class="barRow">
                <div class="barLabel">مدفوعة</div>
                <div class="barTrack"><div class="barFill" style="width:<?=$pPaid?>%"></div></div>
                <div class="barVal"><?=(int)$metrics['paid_count']?> • <?=$pPaid?>%</div>
              </div>
              <div class="barRow">
                <div class="barLabel">جزئية</div>
                <div class="barTrack"><div class="barFill" style="width:<?=$pPartial?>%"></div></div>
                <div class="barVal"><?=(int)$metrics['partial_count']?> • <?=$pPartial?>%</div>
              </div>
              <div class="barRow">
                <div class="barLabel">غير مدفوعة</div>
                <div class="barTrack"><div class="barFill" style="width:<?=$pUnpaid?>%"></div></div>
                <div class="barVal"><?=(int)$metrics['unpaid_count']?> • <?=$pUnpaid?>%</div>
              </div>
            </div>

            <?php if (!empty($monthly)): ?>
              <div class="note">مؤشر 6 أشهر (مدفوع + مستحق) حسب created_at في invoices.</div>
              <div style="margin-top:10px;overflow:auto;">
                <table>
                  <thead>
                    <tr>
                      <th>الشهر</th>
                      <th>مدفوع</th>
                      <th>مستحق</th>
                    </tr>
                  </thead>
                  <tbody>
                  <?php foreach ($monthly as $m): ?>
                    <tr>
                      <td><?=h((string)($m['ym'] ?? ''))?></td>
                      <td style="direction:ltr;text-align:left;"><?=h(money((float)($m['paid_sum'] ?? 0)))?></td>
                      <td style="direction:ltr;text-align:left;"><?=h(money((float)($m['due_sum'] ?? 0)))?></td>
                    </tr>
                  <?php endforeach; ?>
                  </tbody>
                </table>
              </div>
            <?php endif; ?>
          </div>
        </div>

        <div class="box">
          <div class="head">
            <div class="title">أعلى العملاء (مستحق)</div>
            <div class="muted">Top 6</div>
          </div>
          <div class="body">
            <?php if (empty($topClients)): ?>
              <div class="muted">لا توجد بيانات كافية.</div>
            <?php else: ?>
              <table>
                <thead>
                  <tr><th>العميل</th><th>المستحق</th></tr>
                </thead>
                <tbody>
                  <?php foreach ($topClients as $tc): ?>
                    <tr>
                      <td><?=h((string)($tc['client_name'] ?? '-'))?></td>
                      <td style="direction:ltr;text-align:left;"><?=h(money((float)($tc['due_sum'] ?? 0)))?></td>
                    </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>
            <?php endif; ?>
          </div>
        </div>
      </section>

      <section class="box" style="margin-top:14px;">
        <div class="head">
          <div class="title">آخر 12 فاتورة</div>
          <div class="muted">الأحدث</div>
        </div>
        <div class="body" style="overflow:auto;">
          <table style="min-width:980px;">
            <thead>
              <tr>
                <th>#</th>
                <th>العميل</th>
                <th>الحالة</th>
                <th>الإجمالي</th>
                <th>المدفوع</th>
                <th>المستحق</th>
                <th>الاستحقاق</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($recentInvoices as $inv): ?>
                <?php
                  $id = (int)($inv['id'] ?? 0);
                  $client = (string)($inv['client_name'] ?? '-');
                  $totalA = (float)($inv['total_amount'] ?? 0);
                  $paidA  = (float)($inv['paid_amount'] ?? 0);
                  $dueA   = max($totalA - $paidA, 0);
                  [$stTxt,$stCls] = badge_status((string)($inv['status'] ?? ''));
                  $dueDate = (string)($inv['due_date'] ?? '');
                ?>
                <tr>
                  <td><?= (int)$id ?></td>
                  <td><?= h($client) ?></td>
                  <td><span class="tag <?=$stCls?>"><?= h($stTxt) ?></span></td>
                  <td style="direction:ltr;text-align:left;"><?= h(money($totalA)) ?></td>
                  <td style="direction:ltr;text-align:left;"><?= h(money($paidA)) ?></td>
                  <td style="direction:ltr;text-align:left;"><?= h(money($dueA)) ?></td>
                  <td><?= $dueDate !== '' ? h($dueDate) : '<span class="muted">-</span>' ?></td>
                </tr>
              <?php endforeach; ?>
              <?php if (empty($recentInvoices)): ?>
                <tr><td colspan="7" class="muted">لا توجد فواتير</td></tr>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </section>
    <?php endif; ?>

  </main>
</div>
</body>
</html>