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

// Summary stats
$totalBankBalance = $pdo->query("SELECT COALESCE(SUM(current_balance),0) FROM accounts WHERE account_subtype IN ('bank','cash') AND is_active=1")->fetchColumn();
$totalReceivable  = $pdo->query("SELECT COALESCE(SUM(current_balance),0) FROM accounts WHERE account_subtype='receivable'")->fetchColumn();
$totalPayable     = $pdo->query("SELECT COALESCE(ABS(SUM(current_balance)),0) FROM accounts WHERE account_subtype='payable'")->fetchColumn();

// This month P&L
$from = date('Y-m-01'); $to = date('Y-m-d');
$monthIncome  = $pdo->prepare("SELECT COALESCE(SUM(jl.credit-jl.debit),0) FROM journal_lines jl JOIN journal_entries je ON je.id=jl.journal_id JOIN accounts a ON a.id=jl.account_id WHERE a.account_type='income' AND je.entry_date BETWEEN ? AND ?");
$monthIncome->execute([$from,$to]); $monthIncome = $monthIncome->fetchColumn();
$monthExpense = $pdo->prepare("SELECT COALESCE(SUM(jl.debit-jl.credit),0) FROM journal_lines jl JOIN journal_entries je ON je.id=jl.journal_id JOIN accounts a ON a.id=jl.account_id WHERE a.account_type='expense' AND je.entry_date BETWEEN ? AND ?");
$monthExpense->execute([$from,$to]); $monthExpense = $monthExpense->fetchColumn();
$monthProfit = $monthIncome - $monthExpense;

// Recent journal entries
$recentJournals = $pdo->query("SELECT je.*, u.name as created_by_name FROM journal_entries je LEFT JOIN users u ON u.id=je.created_by ORDER BY je.created_at DESC LIMIT 10")->fetchAll();

// Bank accounts list
$bankAccounts = $pdo->query("SELECT * FROM accounts WHERE account_subtype IN ('bank','cash','credit_card') AND is_active=1 ORDER BY account_code")->fetchAll();

$pageTitle = 'Accounts & Finance';
require_once __DIR__ . '/../../includes/header.php';
?>

<div class="page-header">
    <div>
        <div class="eyebrow">Finance</div>
        <h2 class="mb-0">Accounts & Finance</h2>
    </div>
    <div class="flex gap-8">
        <a href="accounts_list.php" class="btn"><?= icon('files') ?> Chart of Accounts</a>
        <a href="journal.php" class="btn btn-primary"><?= icon('plus') ?> New Journal Entry</a>
    </div>
</div>

<!-- Summary cards -->
<div class="stat-grid">
    <div class="stat-card info">
        <div class="stat-label"><?= icon('building-bank') ?> Total Bank & Cash</div>
        <div class="stat-value mono" style="font-size:22px"><?= formatMoney($totalBankBalance) ?></div>
    </div>
    <div class="stat-card success">
        <div class="stat-label"><?= icon('arrow-down-circle') ?> Receivable (Customers Owe)</div>
        <div class="stat-value mono" style="font-size:22px"><?= formatMoney($totalReceivable) ?></div>
    </div>
    <div class="stat-card danger">
        <div class="stat-label"><?= icon('arrow-up-circle') ?> Payable (We Owe Vendors)</div>
        <div class="stat-value mono" style="font-size:22px"><?= formatMoney($totalPayable) ?></div>
    </div>
    <div class="stat-card <?= $monthProfit >= 0 ? 'success' : 'danger' ?>">
        <div class="stat-label"><?= icon('report-money') ?> This Month Net Profit</div>
        <div class="stat-value mono" style="font-size:22px"><?= formatMoney($monthProfit) ?></div>
        <div class="text-sm text-faint">Income: <?= formatMoney($monthIncome) ?> | Expense: <?= formatMoney($monthExpense) ?></div>
    </div>
</div>

<!-- Quick links -->
<div class="form-grid" style="margin-bottom:16px;">
    <a href="bank_accounts.php" class="card" style="text-decoration:none;display:block;padding:16px;cursor:pointer;">
        <div style="font-size:24px;margin-bottom:8px;"><?= icon('building-bank', 24) ?></div>
        <div style="font-weight:700;">Bank Accounts</div>
        <div class="text-sm text-muted">Manage accounts, view statements</div>
    </a>
    <a href="expenses.php" class="card" style="text-decoration:none;display:block;padding:16px;cursor:pointer;">
        <div style="font-size:24px;margin-bottom:8px;"><?= icon('receipt', 24) ?></div>
        <div style="font-weight:700;">Expenses</div>
        <div class="text-sm text-muted">Record rent, electricity, misc expenses</div>
    </a>
    <a href="salaries.php" class="card" style="text-decoration:none;display:block;padding:16px;cursor:pointer;">
        <div style="font-size:24px;margin-bottom:8px;"><?= icon('users', 24) ?></div>
        <div style="font-weight:700;">Salaries</div>
        <div class="text-sm text-muted">Process employee salaries</div>
    </a>
    <a href="journal.php" class="card" style="text-decoration:none;display:block;padding:16px;cursor:pointer;">
        <div style="font-size:24px;margin-bottom:8px;"><?= icon('files', 24) ?></div>
        <div style="font-weight:700;">Journal Entries</div>
        <div class="text-sm text-muted">Manual double-entry bookkeeping</div>
    </a>
    <a href="reports.php?report=pl" class="card" style="text-decoration:none;display:block;padding:16px;cursor:pointer;">
        <div style="font-size:24px;margin-bottom:8px;"><?= icon('report-analytics', 24) ?></div>
        <div style="font-weight:700;">Profit & Loss</div>
        <div class="text-sm text-muted">Income vs expense report</div>
    </a>
    <a href="reports.php?report=bs" class="card" style="text-decoration:none;display:block;padding:16px;cursor:pointer;">
        <div style="font-size:24px;margin-bottom:8px;"><?= icon('stack-2', 24) ?></div>
        <div style="font-weight:700;">Balance Sheet</div>
        <div class="text-sm text-muted">Assets, liabilities, equity</div>
    </a>
    <a href="reports.php?report=tb" class="card" style="text-decoration:none;display:block;padding:16px;cursor:pointer;">
        <div style="font-size:24px;margin-bottom:8px;"><?= icon('report-money', 24) ?></div>
        <div style="font-weight:700;">Trial Balance</div>
        <div class="text-sm text-muted">All account balances</div>
    </a>
    <a href="reports.php?report=ledger" class="card" style="text-decoration:none;display:block;padding:16px;cursor:pointer;">
        <div style="font-size:24px;margin-bottom:8px;"><?= icon('history', 24) ?></div>
        <div style="font-weight:700;">Account Ledger</div>
        <div class="text-sm text-muted">Statement per account</div>
    </a>
</div>

<!-- Bank accounts summary -->
<?php if ($bankAccounts): ?>
<div class="card">
    <div class="card-title"><?= icon('building-bank') ?> Bank & Cash Accounts</div>
    <div class="table-wrap">
        <table>
            <thead>
                <tr><th>Code</th><th>Account Name</th><th>Type</th><th>Bank</th><th>A/C No</th><th class="text-right">Balance</th><th></th></tr>
            </thead>
            <tbody>
            <?php foreach ($bankAccounts as $acc): ?>
            <tr>
                <td class="mono"><?= sanitize($acc['account_code']) ?></td>
                <td><strong><?= sanitize($acc['account_name']) ?></strong></td>
                <td><span class="badge"><?= ucfirst($acc['account_subtype']) ?></span></td>
                <td><?= sanitize($acc['bank_name'] ?? '-') ?></td>
                <td class="mono"><?= sanitize($acc['account_number'] ?? '-') ?></td>
                <td class="num mono <?= $acc['current_balance'] < 0 ? 'text-danger' : 'text-success' ?>">
                    <strong><?= formatMoney($acc['current_balance']) ?></strong>
                </td>
                <td>
                    <a href="reports.php?report=ledger&account_id=<?= $acc['id'] ?>" class="btn btn-sm"><?= icon('history') ?> Statement</a>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <div class="mt-8">
        <a href="bank_accounts.php" class="btn btn-sm"><?= icon('plus') ?> Add Bank Account</a>
    </div>
</div>
<?php endif; ?>

<!-- Recent journal entries -->
<div class="card">
    <div class="card-title"><?= icon('history') ?> Recent Journal Entries</div>
    <?php if ($recentJournals): ?>
    <div class="table-wrap">
        <table>
            <thead>
                <tr><th>Entry No</th><th>Date</th><th>Type</th><th>Narration</th><th class="text-right">Amount</th><th>By</th><th></th></tr>
            </thead>
            <tbody>
            <?php foreach ($recentJournals as $je): ?>
            <tr>
                <td class="mono"><?= sanitize($je['entry_no']) ?></td>
                <td><?= formatDate($je['entry_date']) ?></td>
                <td><span class="badge"><?= ucfirst($je['entry_type']) ?></span></td>
                <td class="text-sm"><?= sanitize(substr($je['narration'] ?? '', 0, 60)) ?><?= strlen($je['narration'] ?? '') > 60 ? '...' : '' ?></td>
                <td class="num mono"><?= formatMoney($je['total_debit']) ?></td>
                <td class="text-sm"><?= sanitize($je['created_by_name'] ?? '-') ?></td>
                <td><a href="journal_view.php?id=<?= $je['id'] ?>" class="btn btn-sm btn-icon"><?= icon('eye') ?></a></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php else: ?>
    <div class="empty-state"><?= icon('files') ?> No journal entries yet. They auto-create when you record sales, purchases and payments.</div>
    <?php endif; ?>
</div>

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