<?php
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/accounting.php';
requireLogin();

$report    = $_GET['report']     ?? 'pl';
$from      = $_GET['from']       ?? date('Y-01-01');
$to        = $_GET['to']         ?? date('Y-m-d');
$asOf      = $_GET['as_of']      ?? date('Y-m-d');
$accountId = (int)($_GET['account_id'] ?? 0);

$pageTitle = match($report) {
    'pl'     => 'Profit & Loss',
    'bs'     => 'Balance Sheet',
    'tb'     => 'Trial Balance',
    'ledger' => 'Account Ledger',
    default  => 'Reports'
};

require_once __DIR__ . '/../../includes/header.php';
?>

<div class="page-header no-print">
    <div><div class="eyebrow">Accounts</div><h2 class="mb-0"><?= $pageTitle ?></h2></div>
    <div class="flex gap-8">
        <a href="index.php" class="btn"><?= icon('arrow-left') ?> Back</a>
        <button class="btn" onclick="window.print()"><?= icon('download') ?> Download / Print</button>
    </div>
</div>

<!-- Report type tabs -->
<div class="flex gap-8 no-print" style="margin-bottom:16px;flex-wrap:wrap;">
    <a href="?report=pl" class="btn <?= $report==='pl'?'btn-primary':'' ?>"><?= icon('report-analytics') ?> P&L</a>
    <a href="?report=bs" class="btn <?= $report==='bs'?'btn-primary':'' ?>"><?= icon('stack-2') ?> Balance Sheet</a>
    <a href="?report=tb" class="btn <?= $report==='tb'?'btn-primary':'' ?>"><?= icon('report-money') ?> Trial Balance</a>
    <a href="?report=ledger" class="btn <?= $report==='ledger'?'btn-primary':'' ?>"><?= icon('history') ?> Account Ledger</a>
</div>

<?php
// ─────────────────────────────────────────────
// PROFIT & LOSS
// ─────────────────────────────────────────────
if ($report === 'pl'):
    $rows = getProfitLoss($from, $to);
    $income = []; $expenses = [];
    foreach ($rows as $row) {
        $net = $row['account_type'] === 'income'
            ? $row['total_credit'] - $row['total_debit']
            : $row['total_debit'] - $row['total_credit'];
        if ($row['account_type'] === 'income')  $income[]   = array_merge($row, ['net' => $net]);
        if ($row['account_type'] === 'expense')  $expenses[] = array_merge($row, ['net' => $net]);
    }
    $totalIncome   = array_sum(array_column($income, 'net'));
    $totalExpenses = array_sum(array_column($expenses, 'net'));
    $netProfit     = $totalIncome - $totalExpenses;
?>
<!-- Date filter -->
<div class="card no-print" style="padding:12px 16px;">
    <form method="GET" class="flex gap-8" style="align-items:flex-end;">
        <input type="hidden" name="report" value="pl">
        <div class="form-group mb-0"><label class="text-sm">From</label><input type="date" name="from" value="<?= $from ?>"></div>
        <div class="form-group mb-0"><label class="text-sm">To</label><input type="date" name="to" value="<?= $to ?>"></div>
        <button class="btn btn-primary"><?= icon('filter') ?> Apply</button>
    </form>
</div>

<div class="card" style="max-width:800px;margin:0 auto;">
    <div class="flex-between" style="margin-bottom:20px;">
        <div>
            <h2 style="margin:0;">Profit & Loss Statement</h2>
            <div class="text-sm text-muted">Period: <?= formatDate($from) ?> to <?= formatDate($to) ?></div>
        </div>
        <div class="text-right">
            <div class="text-sm text-muted"><?= sanitize(getSetting('company_name','Your Company')) ?></div>
            <div class="text-sm text-muted">Generated: <?= date('d-M-Y') ?></div>
        </div>
    </div>

    <!-- Income -->
    <div style="font-weight:700;font-size:13px;text-transform:uppercase;letter-spacing:1px;color:var(--color-primary);padding:8px 0;border-bottom:2px solid var(--color-primary);margin-bottom:8px;">Income</div>
    <?php foreach ($income as $row): ?>
    <div class="flex-between" style="padding:6px 0;border-bottom:1px solid var(--color-border);">
        <span><?= sanitize($row['account_name']) ?></span>
        <span class="mono text-success"><?= formatMoney($row['net']) ?></span>
    </div>
    <?php endforeach; ?>
    <?php if (!$income): ?>
    <div class="text-sm text-faint" style="padding:8px 0;">No income recorded in this period.</div>
    <?php endif; ?>
    <div class="flex-between" style="padding:10px 0;font-weight:700;border-top:2px solid var(--color-border);margin-top:4px;">
        <span>Total Income</span>
        <span class="mono"><?= formatMoney($totalIncome) ?></span>
    </div>

    <div style="margin:20px 0;"></div>

    <!-- Expenses -->
    <div style="font-weight:700;font-size:13px;text-transform:uppercase;letter-spacing:1px;color:var(--color-danger);padding:8px 0;border-bottom:2px solid var(--color-danger);margin-bottom:8px;">Expenses</div>
    <?php foreach ($expenses as $row): ?>
    <div class="flex-between" style="padding:6px 0;border-bottom:1px solid var(--color-border);">
        <span><?= sanitize($row['account_name']) ?></span>
        <span class="mono text-danger"><?= formatMoney($row['net']) ?></span>
    </div>
    <?php endforeach; ?>
    <?php if (!$expenses): ?>
    <div class="text-sm text-faint" style="padding:8px 0;">No expenses recorded in this period.</div>
    <?php endif; ?>
    <div class="flex-between" style="padding:10px 0;font-weight:700;border-top:2px solid var(--color-border);margin-top:4px;">
        <span>Total Expenses</span>
        <span class="mono"><?= formatMoney($totalExpenses) ?></span>
    </div>

    <div style="margin:16px 0;padding:16px;background:<?= $netProfit >= 0 ? 'var(--color-success-light,#f0fdf4)' : '#fff1f2' ?>;border-radius:var(--radius-md);border:2px solid <?= $netProfit >= 0 ? 'var(--color-success)' : 'var(--color-danger)' ?>;">
        <div class="flex-between">
            <span style="font-weight:700;font-size:18px;"><?= $netProfit >= 0 ? 'Net Profit' : 'Net Loss' ?></span>
            <span class="mono <?= $netProfit >= 0 ? 'text-success' : 'text-danger' ?>" style="font-size:22px;font-weight:700;"><?= formatMoney(abs($netProfit)) ?></span>
        </div>
    </div>
</div>

<?php
// ─────────────────────────────────────────────
// BALANCE SHEET
// ─────────────────────────────────────────────
elseif ($report === 'bs'):
    $rows = getBalanceSheet($asOf);
    $assets = []; $liabilities = []; $equity = [];
    foreach ($rows as $row) {
        $normalBal = in_array($row['account_type'], ['asset','expense'])
            ? $row['opening_balance'] + $row['total_debit'] - $row['total_credit']
            : $row['opening_balance'] + $row['total_credit'] - $row['total_debit'];
        $row['balance'] = $normalBal;
        if ($row['account_type'] === 'asset')     $assets[]      = $row;
        if ($row['account_type'] === 'liability')  $liabilities[] = $row;
        if ($row['account_type'] === 'equity')     $equity[]      = $row;
    }
    $totalAssets      = array_sum(array_column($assets, 'balance'));
    $totalLiabilities = array_sum(array_column($liabilities, 'balance'));
    $totalEquity      = array_sum(array_column($equity, 'balance'));
?>
<div class="card no-print" style="padding:12px 16px;">
    <form method="GET" class="flex gap-8" style="align-items:flex-end;">
        <input type="hidden" name="report" value="bs">
        <div class="form-group mb-0"><label class="text-sm">As of Date</label><input type="date" name="as_of" value="<?= $asOf ?>"></div>
        <button class="btn btn-primary"><?= icon('filter') ?> Apply</button>
    </form>
</div>

<div class="form-grid" style="max-width:900px;margin:0 auto;">
    <!-- Assets column -->
    <div class="card">
        <div style="font-weight:700;font-size:13px;text-transform:uppercase;letter-spacing:1px;color:var(--color-primary);padding:8px 0;border-bottom:2px solid var(--color-primary);margin-bottom:8px;">Assets</div>
        <?php $lastGroup = ''; foreach ($assets as $row): ?>
        <?php if ($row['group_name'] !== $lastGroup): $lastGroup = $row['group_name']; ?>
        <div class="text-sm" style="font-weight:600;margin:10px 0 4px;color:var(--color-text-muted);"><?= sanitize($row['group_name']) ?></div>
        <?php endif; ?>
        <div class="flex-between" style="padding:4px 0 4px 12px;border-bottom:1px solid var(--color-border);">
            <span class="text-sm"><?= sanitize($row['account_name']) ?></span>
            <span class="mono text-sm"><?= formatMoney($row['balance']) ?></span>
        </div>
        <?php endforeach; ?>
        <div class="flex-between" style="padding:10px 0;font-weight:700;border-top:2px solid var(--color-primary);margin-top:8px;">
            <span>Total Assets</span>
            <span class="mono"><?= formatMoney($totalAssets) ?></span>
        </div>
    </div>

    <!-- Liabilities + Equity column -->
    <div>
        <div class="card">
            <div style="font-weight:700;font-size:13px;text-transform:uppercase;letter-spacing:1px;color:var(--color-danger);padding:8px 0;border-bottom:2px solid var(--color-danger);margin-bottom:8px;">Liabilities</div>
            <?php $lastGroup = ''; foreach ($liabilities as $row): ?>
            <?php if ($row['group_name'] !== $lastGroup): $lastGroup = $row['group_name']; ?>
            <div class="text-sm" style="font-weight:600;margin:10px 0 4px;color:var(--color-text-muted);"><?= sanitize($row['group_name']) ?></div>
            <?php endif; ?>
            <div class="flex-between" style="padding:4px 0 4px 12px;border-bottom:1px solid var(--color-border);">
                <span class="text-sm"><?= sanitize($row['account_name']) ?></span>
                <span class="mono text-sm"><?= formatMoney($row['balance']) ?></span>
            </div>
            <?php endforeach; ?>
            <div class="flex-between" style="padding:10px 0;font-weight:700;border-top:2px solid var(--color-danger);margin-top:8px;">
                <span>Total Liabilities</span>
                <span class="mono"><?= formatMoney($totalLiabilities) ?></span>
            </div>
        </div>

        <div class="card">
            <div style="font-weight:700;font-size:13px;text-transform:uppercase;letter-spacing:1px;color:var(--color-accent-dk,#854F0B);padding:8px 0;border-bottom:2px solid var(--color-accent-dk,#854F0B);margin-bottom:8px;">Equity</div>
            <?php foreach ($equity as $row): ?>
            <div class="flex-between" style="padding:4px 0 4px 12px;border-bottom:1px solid var(--color-border);">
                <span class="text-sm"><?= sanitize($row['account_name']) ?></span>
                <span class="mono text-sm"><?= formatMoney($row['balance']) ?></span>
            </div>
            <?php endforeach; ?>
            <div class="flex-between" style="padding:10px 0;font-weight:700;border-top:2px solid var(--color-accent-dk,#854F0B);margin-top:8px;">
                <span>Total Equity</span>
                <span class="mono"><?= formatMoney($totalEquity) ?></span>
            </div>
            <div class="flex-between" style="padding:8px 0;font-weight:700;">
                <span>Total Liabilities + Equity</span>
                <span class="mono"><?= formatMoney($totalLiabilities + $totalEquity) ?></span>
            </div>
        </div>

        <?php $diff = abs($totalAssets - ($totalLiabilities + $totalEquity)); ?>
        <?php if ($diff > 1): ?>
        <div class="alert alert-warning"><?= icon('alert-triangle') ?> Balance sheet difference: <?= formatMoney($diff) ?> — check for unposted entries.</div>
        <?php else: ?>
        <div class="alert alert-success"><?= icon('circle-check') ?> Balance sheet is balanced.</div>
        <?php endif; ?>
    </div>
</div>

<?php
// ─────────────────────────────────────────────
// TRIAL BALANCE
// ─────────────────────────────────────────────
elseif ($report === 'tb'):
    $rows = getTrialBalance($from, $to);
    $totalDr = 0; $totalCr = 0;
?>
<div class="card no-print" style="padding:12px 16px;">
    <form method="GET" class="flex gap-8" style="align-items:flex-end;">
        <input type="hidden" name="report" value="tb">
        <div class="form-group mb-0"><label class="text-sm">From</label><input type="date" name="from" value="<?= $from ?>"></div>
        <div class="form-group mb-0"><label class="text-sm">To</label><input type="date" name="to" value="<?= $to ?>"></div>
        <button class="btn btn-primary"><?= icon('filter') ?> Apply</button>
    </form>
</div>

<div class="card" style="max-width:900px;margin:0 auto;">
    <div class="flex-between" style="margin-bottom:16px;">
        <div>
            <h2 style="margin:0;">Trial Balance</h2>
            <div class="text-sm text-muted">Period: <?= formatDate($from) ?> to <?= formatDate($to) ?></div>
        </div>
        <div class="text-right text-sm text-muted"><?= sanitize(getSetting('company_name')) ?></div>
    </div>
    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th>Code</th>
                    <th>Account Name</th>
                    <th>Group</th>
                    <th class="text-right">Opening Bal</th>
                    <th class="text-right">Total Debit</th>
                    <th class="text-right">Total Credit</th>
                    <th class="text-right">Net Balance</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($rows as $row):
                $net = in_array($row['account_type'], ['asset','expense'])
                    ? $row['opening_balance'] + $row['total_debit'] - $row['total_credit']
                    : $row['opening_balance'] + $row['total_credit'] - $row['total_debit'];
                if ($net >= 0) $totalDr += $net;
                else $totalCr += abs($net);
                if ($row['total_debit'] == 0 && $row['total_credit'] == 0 && $row['opening_balance'] == 0) continue;
            ?>
            <tr>
                <td class="mono"><?= sanitize($row['account_code']) ?></td>
                <td><?= sanitize($row['account_name']) ?></td>
                <td class="text-sm text-muted"><?= sanitize($row['group_name'] ?? '') ?></td>
                <td class="num"><?= formatMoney($row['opening_balance']) ?></td>
                <td class="num mono"><?= formatMoney($row['total_debit']) ?></td>
                <td class="num mono"><?= formatMoney($row['total_credit']) ?></td>
                <td class="num mono <?= $net >= 0 ? '' : 'text-danger' ?>">
                    <strong><?= formatMoney(abs($net)) ?><?= $net < 0 ? ' Cr' : '' ?></strong>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
            <tfoot>
                <tr style="background:var(--color-surface-2);">
                    <td colspan="4" style="font-weight:700;text-align:right;">Totals</td>
                    <td class="num mono"><strong><?= formatMoney($totalDr) ?></strong></td>
                    <td class="num mono"><strong><?= formatMoney($totalCr) ?></strong></td>
                    <td class="num mono <?= abs($totalDr - $totalCr) < 1 ? 'text-success' : 'text-danger' ?>">
                        <strong><?= abs($totalDr - $totalCr) < 1 ? '✅ Balanced' : '❌ ' . formatMoney(abs($totalDr - $totalCr)) ?></strong>
                    </td>
                </tr>
            </tfoot>
        </table>
    </div>
</div>

<?php
// ─────────────────────────────────────────────
// ACCOUNT LEDGER (Statement per account)
// ─────────────────────────────────────────────
elseif ($report === 'ledger'):
    $allAccounts = $pdo->query("SELECT id, account_code, account_name, account_type, account_subtype FROM accounts WHERE is_active=1 ORDER BY account_code")->fetchAll();
    $ledgerRows = [];
    $selectedAcc = null;
    $openingBal = 0;
    $runningBal = 0;

    if ($accountId) {
        $stmt = $pdo->prepare("SELECT * FROM accounts WHERE id=?");
        $stmt->execute([$accountId]);
        $selectedAcc = $stmt->fetch();
        $openingBal  = (float)($selectedAcc['opening_balance'] ?? 0);

        // Opening balance as of start of period (all journals before $from)
        $obStmt = $pdo->prepare("SELECT COALESCE(SUM(jl.debit),0) dr, COALESCE(SUM(jl.credit),0) cr
                                  FROM journal_lines jl JOIN journal_entries je ON je.id=jl.journal_id
                                  WHERE jl.account_id=? AND je.entry_date < ?");
        $obStmt->execute([$accountId, $from]);
        $ob = $obStmt->fetch();
        $isDebitNormal = in_array($selectedAcc['account_type'], ['asset','expense']);
        $openingBal += $isDebitNormal ? ($ob['dr'] - $ob['cr']) : ($ob['cr'] - $ob['dr']);
        $runningBal  = $openingBal;

        $stmt = $pdo->prepare("SELECT je.entry_no, je.entry_date, je.entry_type, je.narration,
                                       jl.debit, jl.credit, jl.narration as line_note
                                FROM journal_lines jl
                                JOIN journal_entries je ON je.id=jl.journal_id
                                WHERE jl.account_id=? AND je.entry_date BETWEEN ? AND ?
                                ORDER BY je.entry_date, je.id");
        $stmt->execute([$accountId, $from, $to]);
        $ledgerRows = $stmt->fetchAll();
    }
?>
<div class="card no-print" style="padding:12px 16px;">
    <form method="GET" class="flex gap-8" style="align-items:flex-end;flex-wrap:wrap;">
        <input type="hidden" name="report" value="ledger">
        <div class="form-group mb-0">
            <label class="text-sm">Account</label>
            <select name="account_id" style="width:260px;" onchange="this.form.submit()">
                <option value="">-- Select Account --</option>
                <?php foreach ($allAccounts as $acc): ?>
                <option value="<?= $acc['id'] ?>" <?= $accountId==$acc['id']?'selected':'' ?>>
                    <?= sanitize($acc['account_code']) ?> — <?= sanitize($acc['account_name']) ?>
                </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="form-group mb-0"><label class="text-sm">From</label><input type="date" name="from" value="<?= $from ?>"></div>
        <div class="form-group mb-0"><label class="text-sm">To</label><input type="date" name="to" value="<?= $to ?>"></div>
        <button class="btn btn-primary"><?= icon('filter') ?> Apply</button>
    </form>
</div>

<?php if ($selectedAcc): ?>
<div class="card" style="max-width:900px;margin:0 auto;">
    <div class="flex-between" style="margin-bottom:16px;">
        <div>
            <h2 style="margin:0;"><?= sanitize($selectedAcc['account_name']) ?></h2>
            <div class="text-sm text-muted">Account Code: <?= sanitize($selectedAcc['account_code']) ?> &nbsp;|&nbsp; Period: <?= formatDate($from) ?> to <?= formatDate($to) ?></div>
        </div>
        <div class="text-right text-sm text-muted"><?= sanitize(getSetting('company_name')) ?></div>
    </div>

    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Entry No</th>
                    <th>Type</th>
                    <th>Narration</th>
                    <th class="text-right">Debit</th>
                    <th class="text-right">Credit</th>
                    <th class="text-right">Balance</th>
                </tr>
            </thead>
            <tbody>
            <!-- Opening balance row -->
            <tr style="background:var(--color-surface-2);font-style:italic;">
                <td><?= formatDate($from) ?></td>
                <td colspan="3">Opening Balance</td>
                <td class="num">-</td>
                <td class="num">-</td>
                <td class="num mono"><strong><?= formatMoney($openingBal) ?></strong></td>
            </tr>
            <?php foreach ($ledgerRows as $row):
                $isDebitNormal = in_array($selectedAcc['account_type'], ['asset','expense']);
                $runningBal += $isDebitNormal
                    ? ($row['debit'] - $row['credit'])
                    : ($row['credit'] - $row['debit']);
            ?>
            <tr>
                <td><?= formatDate($row['entry_date']) ?></td>
                <td class="mono"><?= sanitize($row['entry_no']) ?></td>
                <td><span class="badge badge-muted"><?= ucfirst($row['entry_type']) ?></span></td>
                <td class="text-sm"><?= sanitize($row['line_note'] ?: $row['narration']) ?></td>
                <td class="num mono"><?= $row['debit'] > 0 ? formatMoney($row['debit']) : '-' ?></td>
                <td class="num mono"><?= $row['credit'] > 0 ? formatMoney($row['credit']) : '-' ?></td>
                <td class="num mono <?= $runningBal < 0 ? 'text-danger' : '' ?>">
                    <strong><?= formatMoney(abs($runningBal)) ?><?= $runningBal < 0 ? ' Cr' : ' Dr' ?></strong>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
            <tfoot>
                <tr style="background:var(--color-surface-2);">
                    <td colspan="4" style="font-weight:700;text-align:right;">Closing Balance</td>
                    <td class="num mono"><strong><?= formatMoney(array_sum(array_column($ledgerRows,'debit'))) ?></strong></td>
                    <td class="num mono"><strong><?= formatMoney(array_sum(array_column($ledgerRows,'credit'))) ?></strong></td>
                    <td class="num mono <?= $runningBal < 0 ? 'text-danger' : 'text-success' ?>">
                        <strong><?= formatMoney(abs($runningBal)) ?><?= $runningBal < 0 ? ' Cr' : ' Dr' ?></strong>
                    </td>
                </tr>
            </tfoot>
        </table>
    </div>
    <?php if (!$ledgerRows): ?>
    <div class="empty-state"><?= icon('history') ?> No transactions in this period for this account.</div>
    <?php endif; ?>
</div>
<?php else: ?>
<div class="card"><div class="empty-state"><?= icon('history') ?> Select an account to view its ledger statement.</div></div>
<?php endif; ?>

<?php endif; ?>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
