<?php
require_once __DIR__ . '/../config/config.php';
require_permission('accounting.reports_view');

$asOf = $_GET['as_of'] ?? date('Y-m-d');
$yearStart = date('Y-01-01', strtotime($asOf));

$accounts = get_chart_of_accounts($pdo);
$byClass = ['asset' => [], 'liability' => [], 'equity' => []];
$totals = ['asset' => 0, 'liability' => 0, 'equity' => 0];

foreach ($accounts as $a) {
    if ($a['statement'] !== 'balance_sheet') continue;
    $balance = get_account_balance($pdo, $a['id'], $a['normal_balance'], $asOf);
    if (abs($balance) < 0.005) continue;
    $byClass[$a['classification']][] = ['account' => $a, 'amount' => $balance];
    $totals[$a['classification']] += $balance;
}

// Current-year earnings plug, so the sheet balances before formal year-end closing
$incomeAccounts = array_filter($accounts, fn($a) => $a['statement'] === 'income_statement');
$currentYearEarnings = 0;
foreach ($incomeAccounts as $a) {
    $asOfDate = get_account_balance($pdo, $a['id'], $a['normal_balance'], $asOf);
    $asOfBeforeYear = get_account_balance($pdo, $a['id'], $a['normal_balance'], date('Y-m-d', strtotime($yearStart . ' -1 day')));
    $movement = $asOfDate - $asOfBeforeYear;
    $currentYearEarnings += in_array($a['classification'], ['revenue']) ? $movement : -$movement;
}

$totalAssets = $totals['asset'];
$totalLiabilities = $totals['liability'];
$totalEquity = $totals['equity'] + $currentYearEarnings;

function render_bs_section($title, $rows) {
    if (empty($rows)) return 0;
    echo '<div class="mb-4"><p class="text-sm font-semibold text-slate-600 mb-2">' . e($title) . '</p><div class="space-y-1">';
    $total = 0;
    foreach ($rows as $r) {
        echo '<div class="flex justify-between text-sm px-2"><span class="text-slate-500">' . e($r['account']['description']) . '</span><span>₦' . number_format($r['amount'],2) . '</span></div>';
        $total += $r['amount'];
    }
    echo '</div></div>';
    return $total;
}

$pageTitle = 'Balance Sheet';
include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<h1 class="text-2xl font-bold mb-6">Balance Sheet</h1>

<form method="GET" class="flex flex-wrap items-end gap-3 mb-6 bg-white rounded-xl shadow-sm border border-slate-200 p-4">
  <div>
    <label class="text-xs text-slate-500 block mb-1">As of Date</label>
    <input type="date" name="as_of" value="<?= e($asOf) ?>" class="border border-slate-300 rounded-lg px-3 py-2 text-sm">
  </div>
  <button class="bg-blue-700 hover:bg-blue-800 text-white text-sm font-medium px-4 py-2 rounded-lg">View</button>
</form>

<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
  <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-6">
    <p class="text-xs text-slate-400 mb-4">Assets as of <?= date('M j, Y', strtotime($asOf)) ?></p>
    <?php render_bs_section('Assets', $byClass['asset']); ?>
    <div class="flex justify-between text-base font-bold border-t-2 border-slate-800 py-2 px-2">
      <span>Total Assets</span><span>₦<?= number_format($totalAssets,2) ?></span>
    </div>
  </div>

  <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-6">
    <p class="text-xs text-slate-400 mb-4">Liabilities &amp; Equity as of <?= date('M j, Y', strtotime($asOf)) ?></p>
    <?php render_bs_section('Liabilities', $byClass['liability']); ?>
    <div class="flex justify-between text-sm font-semibold border-t border-slate-100 pt-1 px-2 mb-4">
      <span>Total Liabilities</span><span>₦<?= number_format($totalLiabilities,2) ?></span>
    </div>

    <?php render_bs_section('Equity', $byClass['equity']); ?>
    <div class="flex justify-between text-sm px-2">
      <span class="text-slate-500">Current Year Earnings</span><span>₦<?= number_format($currentYearEarnings,2) ?></span>
    </div>
    <div class="flex justify-between text-sm font-semibold border-t border-slate-100 pt-1 px-2 mb-4 mt-1">
      <span>Total Equity</span><span>₦<?= number_format($totalEquity,2) ?></span>
    </div>

    <div class="flex justify-between text-base font-bold border-t-2 border-slate-800 py-2 px-2">
      <span>Total Liabilities &amp; Equity</span><span>₦<?= number_format($totalLiabilities + $totalEquity,2) ?></span>
    </div>
  </div>
</div>

<?php if (round($totalAssets,2) !== round($totalLiabilities + $totalEquity, 2)): ?>
  <p class="text-red-600 text-sm mt-4">⚠ Assets (₦<?= number_format($totalAssets,2) ?>) do not equal Liabilities + Equity (₦<?= number_format($totalLiabilities+$totalEquity,2) ?>) — check for unbalanced entries.</p>
<?php else: ?>
  <p class="text-emerald-600 text-sm mt-4">✓ Balance sheet is in balance.</p>
<?php endif; ?>
<?php include __DIR__ . '/../includes/footer.php'; ?>
