<?php
class ChartOfAccountsController extends Controller
{
    public function indexAction()
    {
        $jp   = new JournalPosting();
        $rows = $jp->balancesForAll();

        // Roll each row into a signed "presentation balance" per account_type
        $enriched = [];
        foreach ($rows as $r) {
            // Normal balance side per accounting: ASSET/EXPENSE = DR normal; LIABILITY/EQUITY/REVENUE = CR normal
            $raw  = (float)$r['raw_balance']; // debit − credit
            $type = strtoupper((string)$r['account_type']);
            $sign = in_array($type, ['ASSET','EXPENSE'], true) ? +1 : -1;
            $r['presentation_balance'] = $sign * $raw;
            $enriched[] = $r;
        }

        // Group by type for a tidy layout
        $groups = [];
        foreach ($enriched as $r) {
            $groups[$r['account_type']][] = $r;
        }
        $order = ['ASSET','LIABILITY','EQUITY','REVENUE','EXPENSE'];

        $this->view->setLayout($this->roleLayout());
        $this->view->render('ChartOfAccounts/index', [
            'page_title' => 'Chart of Accounts',
            'groups'     => $groups,
            'order'      => $order,
        ]);
    }

    public function viewAction($id = 0)
    {
        $db = new DB();
        $rs = $db->mySelect("SELECT * FROM chart_of_accounts WHERE c0d = :id LIMIT 1", [':id' => (int)$id]);
        $acc = $rs[0] ?? null;
        if (!$acc) {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('generals/fb_page', ['fb_msg' => '<div class="alert alert-danger">Account not found.</div>']);
            return;
        }
        $jp    = new JournalPosting();
        $lines = $jp->activityForAccount((int)$id, (string)($_GET['from'] ?? ''), (string)($_GET['to'] ?? ''));
        // Running balance in normal-side terms
        $type = strtoupper($acc['account_type']);
        $sign = in_array($type, ['ASSET','EXPENSE'], true) ? +1 : -1;
        $running = 0.0;
        foreach ($lines as &$ln) {
            $running += $sign * ((float)$ln['debit'] - (float)$ln['credit']);
            $ln['running_balance'] = $running;
        }
        unset($ln);

        $this->view->setLayout($this->roleLayout());
        $this->view->render('ChartOfAccounts/view', [
            'page_title' => $acc['account_code'] . ' · ' . $acc['account_name'],
            'acc'        => $acc,
            'lines'      => $lines,
            'balance'    => $running,
            'from'       => (string)($_GET['from'] ?? ''),
            'to'         => (string)($_GET['to']   ?? ''),
        ]);
    }
}
