<?php
require_once __DIR__ . '/_report_common.php';

$as_of = $_GET['as_of'] ?? date('Y-m-d');

// Pull balances up to as_of, calculate balance based on normal_side
$stmt = $pdo->prepare("
  SELECT
    a.id, a.code, a.name, a.type, a.normal_side,
    SUM(jl.debit)  AS debits,
    SUM(jl.credit) AS credits,
    CASE
      WHEN a.normal_side='DEBIT' THEN SUM(jl.debit - jl.credit)
      ELSE SUM(jl.credit - jl.debit)
    END AS balance
  FROM accounts a
  LEFT JOIN journal_lines jl
    ON jl.account_id = a.id AND jl.company_id = a.company_id
  LEFT JOIN journal_entries je
    ON je.id = jl.entry_id AND je.status='POSTED' AND je.entry_date <= ?
  WHERE a.company_id = ?
    AND a.is_active = 1
    AND a.type IN ('ASSET','LIABILITY','EQUITY')
  GROUP BY a.id
  HAVING ABS(balance) > 0.0001
  ORDER BY a.type, a.code
");
$stmt->execute([$as_of, $cid]);
$rows = $stmt->fetchAll();

$assets = [];
$liab   = [];
$equity = [];

foreach ($rows as $r) {
  $amt = (float)$r['balance'];
  if ($r['type'] === 'ASSET')      $assets[] = [$r['code'].' - '.$r['name'], $amt];
  if ($r['type'] === 'LIABILITY')  $liab[]   = [$r['code'].' - '.$r['name'], $amt];
  if ($r['type'] === 'EQUITY')     $equity[] = [$r['code'].' - '.$r['name'], $amt];
}

$sum = function(array $arr): float {
  $t = 0.0;
  foreach ($arr as $r) $t += (float)$r[1];
  return $t;
};

$totalAssets = $sum($assets);
$totalLiab   = $sum($liab);
$totalEquity = $sum($equity);
$totalRight  = $totalLiab + $totalEquity;

render_layout("قائمة المركز المالي", "الرئيسية <span class='mx-1'>/</span> التقارير <span class='mx-1'>/</span> المركز المالي", function() use ($as_of,$companyName,$assets,$liab,$equity,$totalAssets,$totalLiab,$totalEquity,$totalRight) {
?>
<style>
  .bs-page{ background:#fff; border:1px solid rgba(2,6,23,.08); border-radius:16px; box-shadow:0 10px 30px rgba(2,6,23,.06); padding:18px; }
  .bs-head{ text-align:center; margin-bottom:10px; }
  .bs-title{ font-weight:800; font-size:20px; }
  .bs-sub{ color:#64748b; font-size:13px; }
  .bs-table{ width:100%; }
  .bs-table th{ background:#f1f5f9; font-weight:800; }
  .bs-table td, .bs-table th{ padding:8px; border:1px solid #e5e7eb; vertical-align:top; }
  .mini td{ padding:6px; border-bottom:1px solid #eef2f7; }
  .mini tr:last-child td{ border-bottom:0; }
  .total-row td{ font-weight:800; background:#fafafa; }
  .no-print{ }
  @media print{
    body{ background:#fff !important; }
    .topbar, .sidebar, .no-print{ display:none !important; }
    .content{ padding:0 !important; }
    .bs-page{ box-shadow:none !important; border:0 !important; border-radius:0 !important; }
    @page { size: A4; margin: 12mm; }
  }
</style>

<div class="container-fluid mt-3">
  <div class="d-flex align-items-center justify-content-between flex-wrap gap-2 no-print">
    <div>
      <div class="fw-bold fs-5">قائمة المركز المالي</div>
      <div class="text-secondary small">حتى تاريخ: <?= h($as_of) ?></div>
    </div>
    <div class="d-flex gap-2">
      <button class="btn btn-dark btn-sm" onclick="window.print()"><i class="bi bi-printer"></i> طباعة</button>
    </div>
  </div>

  <div class="bs-page mt-3">
    <div class="bs-head">
      <div class="bs-title">قائمة المركز المالي</div>
      <div class="bs-sub"><?= h($companyName) ?> — حتى تاريخ <?= h($as_of) ?></div>
    </div>

    <table class="bs-table">
      <tr>
        <th style="width:50%">الأصول</th>
        <th style="width:50%">الخصوم وحقوق الملكية</th>
      </tr>
      <tr>
        <td>
          <table class="table table-sm mb-0 mini">
            <?php foreach($assets as $r): ?>
              <tr>
                <td><?= h($r[0]) ?></td>
                <td class="text-end"><?= number_format((float)$r[1], 2) ?></td>
              </tr>
            <?php endforeach; ?>
            <tr class="total-row">
              <td>إجمالي الأصول</td>
              <td class="text-end"><?= number_format($totalAssets, 2) ?></td>
            </tr>
          </table>
        </td>

        <td>
          <div class="fw-bold mb-1">الخصوم</div>
          <table class="table table-sm mb-3 mini">
            <?php foreach($liab as $r): ?>
              <tr>
                <td><?= h($r[0]) ?></td>
                <td class="text-end"><?= number_format((float)$r[1], 2) ?></td>
              </tr>
            <?php endforeach; ?>
            <tr class="total-row">
              <td>إجمالي الخصوم</td>
              <td class="text-end"><?= number_format($totalLiab, 2) ?></td>
            </tr>
          </table>

          <div class="fw-bold mb-1">حقوق الملكية</div>
          <table class="table table-sm mb-0 mini">
            <?php foreach($equity as $r): ?>
              <tr>
                <td><?= h($r[0]) ?></td>
                <td class="text-end"><?= number_format((float)$r[1], 2) ?></td>
              </tr>
            <?php endforeach; ?>
            <tr class="total-row">
              <td>إجمالي حقوق الملكية</td>
              <td class="text-end"><?= number_format($totalEquity, 2) ?></td>
            </tr>
            <tr class="total-row">
              <td>إجمالي الخصوم وحقوق الملكية</td>
              <td class="text-end"><?= number_format($totalRight, 2) ?></td>
            </tr>
          </table>

          <?php if (abs($totalAssets - $totalRight) > 0.01): ?>
            <div class="alert alert-warning mt-2 mb-0">
              تنبيه: القائمة غير متوازنة (فرق = <?= number_format($totalAssets - $totalRight, 2) ?>).
            </div>
          <?php endif; ?>
        </td>
      </tr>
    </table>
  </div>
</div>

<?php }); ?>
