<?php

namespace Modules\Accounting\Controllers;

use App\Controllers\BaseController;
use App\Models\CashAccountModel;
use App\Models\ChartOfAccountModel;
use Modules\Accounting\Services\CashAccountService;

class CashAccountController extends BaseController
{
    protected CashAccountModel $accounts;
    protected ChartOfAccountModel $glAccounts;
    protected CashAccountService $service;

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

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

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

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

    public function createForm()
    {
        return view('Modules\Accounting\Views\cash_accounts\create', array_merge($this->baseViewData(), [
            'title'      => 'Add Cash 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/cash-accounts')->with('success', 'Cash account created.');
    }

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

        return view('Modules\Accounting\Views\cash_accounts\show', array_merge($this->baseViewData(), [
            'title'   => 'Cash 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/cash-accounts')->with('error', 'Cash account not found.');
        }

        return view('Modules\Accounting\Views\cash_accounts\edit', array_merge($this->baseViewData(), [
            'title'      => 'Edit Cash 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/cash-accounts')->with('success', 'Cash account updated.');
    }

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

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

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

        return redirect()->back()->with('success', 'Cash 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/cash-accounts')->with('error', $result['error']);
        }

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