<?php
class BankRecController extends Controller
{
    public function indexAction()
    {
        $m = new BankRec();
        $this->view->setLayout($this->roleLayout());
        $this->view->render('BankRec/index', [
            'page_title' => 'Bank Reconciliation',
            'statements' => $m->listAll(),
        ]);
    }

    public function importAction()
    {
        $m = new BankRec();
        $this->view->setLayout($this->roleLayout());
        $this->view->render('BankRec/import', [
            'page_title' => 'Import Bank Statement',
            'banks'      => $m->bankAccounts(),
        ]);
    }

    public function viewAction($id = 0)
    {
        $id = (int)$id;
        $m  = new BankRec();
        $stmt = $m->findStatement($id);
        if (!$stmt) { header('HTTP/1.1 404 Not Found'); echo 'Statement not found'; return; }

        $this->view->setLayout($this->roleLayout());
        $this->view->render('BankRec/view', [
            'page_title' => 'Reconcile · ' . htmlspecialchars($stmt['account_code']),
            'stmt'       => $stmt,
            'lines'      => $m->statementLines($id),
            'book'       => $m->unmatchedBookLines($id),
        ]);
    }

    /* ── AJAX endpoints ─────────────────────────────────────────────────── */

    public function importAjAction()
    {
        header('Content-Type: application/json');
        try {
            $bankAccountId = (int)($_POST['bank_account_id'] ?? 0);
            $statementDate = trim((string)($_POST['statement_date'] ?? ''));
            $opening       = (float)($_POST['opening_balance'] ?? 0);
            $closing       = (float)($_POST['closing_balance'] ?? 0);
            $filename      = trim((string)($_POST['filename'] ?? 'statement.xlsx'));
            $linesJson     = (string)($_POST['lines_json'] ?? '[]');
            $lines         = json_decode($linesJson, true) ?: [];

            if ($bankAccountId <= 0 || $statementDate === '' || empty($lines)) {
                throw new InvalidArgumentException('Missing bank account, statement date or lines.');
            }

            $userId   = (int)($_SESSION['user_id']   ?? 0);
            $userName = (string)($_SESSION['full_name'] ?? '');

            $m = new BankRec();
            $stmtId = $m->importStatement($bankAccountId, $statementDate, $opening, $closing, $filename, $lines, $userId, $userName);

            echo json_encode(['ok' => true, 'statement_id' => $stmtId, 'lines' => count($lines)]);
        } catch (Throwable $e) {
            echo json_encode(['ok' => false, 'msg' => $e->getMessage()]);
        }
    }

    public function autoMatchAjAction($id = 0)
    {
        header('Content-Type: application/json');
        try {
            $id = (int)$id;
            $userId = (int)($_SESSION['user_id'] ?? 0);
            $m = new BankRec();
            $n = $m->autoMatch($id, $userId);
            echo json_encode(['ok' => true, 'matched' => $n]);
        } catch (Throwable $e) {
            echo json_encode(['ok' => false, 'msg' => $e->getMessage()]);
        }
    }

    public function matchAjAction()
    {
        header('Content-Type: application/json');
        try {
            $sl = (int)($_POST['statement_line_id'] ?? 0);
            $jl = (int)($_POST['journal_line_id']   ?? 0);
            $userId = (int)($_SESSION['user_id'] ?? 0);
            if ($sl <= 0 || $jl <= 0) throw new InvalidArgumentException('Missing IDs.');
            (new BankRec())->manualMatch($sl, $jl, $userId);
            echo json_encode(['ok' => true]);
        } catch (Throwable $e) {
            echo json_encode(['ok' => false, 'msg' => $e->getMessage()]);
        }
    }

    public function unmatchAjAction()
    {
        header('Content-Type: application/json');
        try {
            $sl = (int)($_POST['statement_line_id'] ?? 0);
            if ($sl <= 0) throw new InvalidArgumentException('Missing ID.');
            (new BankRec())->unmatch($sl);
            echo json_encode(['ok' => true]);
        } catch (Throwable $e) {
            echo json_encode(['ok' => false, 'msg' => $e->getMessage()]);
        }
    }

    public function ignoreAjAction()
    {
        header('Content-Type: application/json');
        try {
            $sl = (int)($_POST['statement_line_id'] ?? 0);
            if ($sl <= 0) throw new InvalidArgumentException('Missing ID.');
            (new BankRec())->ignore($sl);
            echo json_encode(['ok' => true]);
        } catch (Throwable $e) {
            echo json_encode(['ok' => false, 'msg' => $e->getMessage()]);
        }
    }

    public function markReconciledAjAction($id = 0)
    {
        header('Content-Type: application/json');
        try {
            $id = (int)$id;
            $userId   = (int)($_SESSION['user_id']   ?? 0);
            $userName = (string)($_SESSION['full_name'] ?? '');
            (new BankRec())->markReconciled($id, $userId, $userName);
            echo json_encode(['ok' => true]);
        } catch (Throwable $e) {
            echo json_encode(['ok' => false, 'msg' => $e->getMessage()]);
        }
    }
}
