<?php
/**
 * CompanyBankAccountsController — Slice 8Z-m
 *
 * The OUR-side accounts (where money leaves from). FM + Admin manage; Executive views.
 * FM picks one at Payment Schedule approval — currency must match schedule.
 */
class CompanyBankAccountsController extends Controller
{
    public function indexAction()
    {
        $rows = (new CompanyBankAccounts())->all(false);
        $providers = [];
        try { $providers = (new PaymentProviders())->all('', true); } catch (\Throwable $e) { /* PP model always exists */ }
        $this->view->setLayout($this->roleLayout());
        $this->view->render('CompanyBankAccounts/index', [
            'page_title' => 'Company bank accounts',
            'rows'       => $rows,
            'providers'  => $providers,
        ]);
    }

    public function upsertAjAction()
    {
        header('Content-Type: application/json');
        try {
            $r = (new CompanyBankAccounts())->upsert([
                'id'             => (int)   ($_POST['id'] ?? 0),
                'account_name'   => (string)($_POST['account_name'] ?? ''),
                'provider_id'    => (int)   ($_POST['provider_id'] ?? 0),
                'account_number' => (string)($_POST['account_number'] ?? ''),
                'currency'       => (string)($_POST['currency'] ?? 'TZS'),
                'branch_name'    => (string)($_POST['branch_name'] ?? ''),
                'swift_code'     => (string)($_POST['swift_code'] ?? ''),
                'balance_hint'   =>          $_POST['balance_hint'] ?? null,
                'notes'          => (string)($_POST['notes'] ?? ''),
            ], $this->currentUserId());
            echo json_encode($r);
        } catch (\Throwable $e) { echo json_encode(['ok' => false, 'msg' => $e->getMessage()]); }
    }

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