<?php
class CashbookController extends Controller
{
    public function indexAction()
    {
        $db    = new DB();
        $banks = $db->mySelect(
            "SELECT b.c0d, b.account_name, b.bank_name, b.account_number, b.currency, b.opening_balance, b.opening_on, b.coa_id
               FROM bank_accounts b WHERE b.is_active = 1 ORDER BY b.bank_name, b.account_name",
            []
        ) ?: [];

        $selectedId = (int)($_GET['bank_id'] ?? ($banks[0]['c0d'] ?? 0));
        $from       = (string)($_GET['from'] ?? '');
        $to         = (string)($_GET['to']   ?? '');

        $lines   = [];
        $selBank = [];
        if ($selectedId > 0) {
            foreach ($banks as $b) if ((int)$b['c0d'] === $selectedId) { $selBank = $b; break; }
            $jp    = new JournalPosting();
            $lines = $jp->cashbookForBank($selectedId, $from, $to);
        }

        // Compute running balance ------------------------------------------
        $running = (float)($selBank['opening_balance'] ?? 0);
        $enriched = [];
        foreach ($lines as $ln) {
            // For a bank account, an incoming payment is a DEBIT, outgoing is a CREDIT (accounting convention)
            $running += (float)$ln['debit'] - (float)$ln['credit'];
            $ln['running_balance'] = $running;
            $enriched[] = $ln;
        }
        $closing = $running;

        $this->view->setLayout($this->roleLayout());
        $this->view->render('Cashbook/index', [
            'page_title'   => 'Cashbook',
            'banks'        => $banks,
            'selected_id'  => $selectedId,
            'sel_bank'     => $selBank,
            'lines'        => $enriched,
            'closing'      => $closing,
            'from'         => $from,
            'to'           => $to,
        ]);
    }
}
