<?php

namespace Modules\Accounting\Controllers;

use App\Controllers\BaseController;
use App\Models\BankAccountModel;
use App\Models\ChartOfAccountModel;
use Modules\Accounting\Services\BankAccountService;

class BankAccountController extends BaseController
{
    protected BankAccountModel $accounts;
    protected ChartOfAccountModel $glAccounts;
    protected BankAccountService $service;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->accounts   = new BankAccountModel();
        $this->glAccounts = new ChartOfAccountModel();
        $this->service    = new BankAccountService();
    }

    public function index()
    {
        $search = trim((string) $this->request->getGet('q'));
        $status = $this->request->getGet('status') ?: null;

        $accounts = $this->accounts
            ->scopeForList($search ?: null, $status)
            ->orderBy('bank_accounts.code', 'ASC')
            ->findAll();

        return view('Modules\Accounting\Views\bank_accounts\index', array_merge($this->baseViewData(), [
            'title'    => 'Bank Accounts',
            'accounts' => $accounts,
            'filters'  => compact('search', 'status'),
        ]));
    }

    public function createForm()
    {
        return view('Modules\Accounting\Views\bank_accounts\create', array_merge($this->baseViewData(), [
            'title'      => 'Add Bank Account',
            'glAccounts' => $this->glAccounts->getActivePostable(),
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'code'       => 'required|max_length[30]',
            'name'       => 'required|min_length[2]|max_length[150]',
            'account_id' => 'required|is_natural_no_zero',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $result = $this->service->create($this->request->getPost(), (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->withInput()->with('errors', $result['errors']);
        }

        return redirect()->to('/accounting/bank-accounts')->with('success', 'Bank account created.');
    }

    public function show(int $id)
    {
        $account = $this->accounts->scopeForList()->where('bank_accounts.id', $id)->first();
        if (! $account) {
            return redirect()->to('/accounting/bank-accounts')->with('error', 'Bank account not found.');
        }

        return view('Modules\Accounting\Views\bank_accounts\show', array_merge($this->baseViewData(), [
            'title'   => 'Bank Account Details',
            'account' => $account,
            'balance' => (float) $account['opening_balance'],
        ]));
    }

    public function editForm(int $id)
    {
        $account = $this->accounts->find($id);
        if (! $account) {
            return redirect()->to('/accounting/bank-accounts')->with('error', 'Bank account not found.');
        }

        return view('Modules\Accounting\Views\bank_accounts\edit', array_merge($this->baseViewData(), [
            'title'      => 'Edit Bank Account',
            'account'    => $account,
            'glAccounts' => $this->glAccounts->getActivePostable(),
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'code'       => 'required|max_length[30]',
            'name'       => 'required|min_length[2]|max_length[150]',
            'account_id' => 'required|is_natural_no_zero',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $result = $this->service->update($id, $this->request->getPost(), (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->withInput()->with('errors', $result['errors']);
        }

        return redirect()->to('/accounting/bank-accounts')->with('success', 'Bank account updated.');
    }

    public function activate(int $id)
    {
        $this->service->activate($id, (int) $this->session->get('user_id'));

        return redirect()->back()->with('success', 'Bank account activated.');
    }

    public function deactivate(int $id)
    {
        $this->service->deactivate($id, (int) $this->session->get('user_id'));

        return redirect()->back()->with('success', 'Bank account deactivated.');
    }

    public function destroy(int $id)
    {
        $result = $this->service->delete($id, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->to('/accounting/bank-accounts')->with('error', $result['error']);
        }

        return redirect()->to('/accounting/bank-accounts')->with('success', 'Bank account deleted.');
    }
}
