<?php
/**
 * PayeeAccountsController — Slice 8Z-k
 *
 * Two surfaces:
 *   /PayeeAccounts        (index)  — FM + Exec + Admin queue: approve/disable pending accounts.
 *   /PayeeAccounts/my     (my)     — Requester queue: their own accounts + add new.
 *
 * The actual FM/Exec approval happens through the standard fin_chains flow — this controller
 * just seeds/creates the account and lists it. When the chain terminates APPROVED, a hook in
 * FinChainsController::postDecisionHook flips the account to APPROVED via markApproved().
 */
class PayeeAccountsController extends Controller
{
    /** FM/Exec/Admin index — full list with status filter. */
    public function indexAction()
    {
        $status = (string)($_GET['status'] ?? '');
        $method = (string)($_GET['method'] ?? '');
        $rows = (new PayeeAccounts())->list([
            'status' => $status,
            'method' => $method,
        ]);
        $this->view->setLayout($this->roleLayout());
        $this->view->render('PayeeAccounts/index', [
            'page_title'   => 'Payee accounts',
            'rows'         => $rows,
            'filter_status'=> $status,
            'filter_method'=> $method,
        ]);
    }

    /** Requester view — their own accounts (they added) + a "Register account" form. */
    public function myAction()
    {
        $rows = (new PayeeAccounts())->list(['created_by' => $this->currentUserId()]);
        $providers = (new PaymentProviders())->all('', true);
        $this->view->setLayout($this->roleLayout());
        $this->view->render('PayeeAccounts/my', [
            'page_title' => 'My payee accounts',
            'rows'       => $rows,
            'providers'  => $providers,
        ]);
    }

    /**
     * Ajax feed for the account dropdown on request forms.
     * ?payee_type=STAFF&payee_id=42 → JSON list of approved + pending accounts for that payee.
     */
    public function listAjAction()
    {
        header('Content-Type: application/json');
        try {
            $pt = strtoupper((string)($_GET['payee_type'] ?? 'STAFF'));
            $pid = (int)($_GET['payee_id'] ?? $this->currentUserId());
            $rows = (new PayeeAccounts())->accountsFor($pt, $pid);
            $out = [];
            foreach ($rows as $r) {
                if ($r['status'] === 'DISABLED') continue;
                $out[] = [
                    'id'            => (int)$r['c0d'],
                    'method'        => $r['method'],
                    'provider_name' => $r['provider_name'],
                    'account_masked'=> PayeeAccounts::mask((string)$r['account_number']),
                    'holder_name'   => $r['account_holder_name'],
                    'status'        => $r['status'],
                    'is_default'    => (int)$r['is_default'],
                ];
            }
            echo json_encode(['ok' => true, 'rows' => $out]);
        } catch (\Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }

    /**
     * Register a new payee account. Anyone with the perm can create; account starts PENDING and
     * auto-submits an approval chain (FM only up to threshold, FM+Exec above).
     * $intended_max_amount (optional) drives the chain routing.
     */
    public function newAjAction()
    {
        header('Content-Type: application/json');
        try {
            $d = [
                'payee_type'          => (string)($_POST['payee_type'] ?? 'STAFF'),
                'payee_id'            => (int)   ($_POST['payee_id']   ?? $this->currentUserId()),
                'payee_name'          => (string)($_POST['payee_name'] ?? ($_SESSION['full_name'] ?? '')),
                'method'              => (string)($_POST['method'] ?? ''),
                'provider_id'         => (int)   ($_POST['provider_id'] ?? 0),
                'account_number'      => (string)($_POST['account_number'] ?? ''),
                'account_holder_name' => (string)($_POST['account_holder_name'] ?? ''),
                'branch_name'         => (string)($_POST['branch_name'] ?? ''),
                'swift_code'          => (string)($_POST['swift_code'] ?? ''),
                'notes'               => (string)($_POST['notes'] ?? ''),
            ];
            $intended = (float)($_POST['intended_max_amount'] ?? 0);
            $r = (new PayeeAccounts())->create($d, $this->currentUserId(), $_SESSION['full_name'] ?? '', $intended);
            echo json_encode($r);
        } catch (\Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }

    /**
     * FM/Exec direct approval (bypass the chain — used only if the approval was created out of
     * band, e.g. Admin promoted a manually-verified account). In normal flow the chain handles it.
     */
    public function approveAjAction()
    {
        header('Content-Type: application/json');
        try {
            $id = (int)($_POST['id'] ?? 0);
            if ($id <= 0) throw new InvalidArgumentException('id required.');
            $r = (new PayeeAccounts())->markApproved($id, $this->currentUserId(), $_SESSION['full_name'] ?? '');
            echo json_encode($r);
        } catch (\Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }

    public function disableAjAction()
    {
        header('Content-Type: application/json');
        try {
            $id = (int)($_POST['id'] ?? 0);
            $reason = (string)($_POST['reason'] ?? '');
            if ($id <= 0)             throw new InvalidArgumentException('id required.');
            if (trim($reason) === '') throw new InvalidArgumentException('Reason required for audit.');
            $r = (new PayeeAccounts())->disable($id, $this->currentUserId(), $_SESSION['full_name'] ?? '', $reason);
            echo json_encode($r);
        } catch (\Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }

    public function reactivateAjAction()
    {
        header('Content-Type: application/json');
        try {
            $id = (int)($_POST['id'] ?? 0);
            if ($id <= 0) throw new InvalidArgumentException('id required.');
            $r = (new PayeeAccounts())->reactivate($id, $this->currentUserId(), $_SESSION['full_name'] ?? '');
            echo json_encode($r);
        } catch (\Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }
}
