<?php

namespace Modules\Accounting\Controllers;

use App\Controllers\BaseController;
use App\Models\ChartOfAccountModel;
use Modules\Accounting\Services\ChartOfAccountService;

class ChartOfAccountController extends BaseController
{
    protected ChartOfAccountModel $accounts;
    protected ChartOfAccountService $service;

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

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

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

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

    public function createForm()
    {
        return view('Modules\Accounting\Views\chart_of_accounts\create', array_merge($this->baseViewData(), [
            'title'    => 'Add Account',
            'parents'  => $this->accounts->getActive(),
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'code' => 'required|max_length[30]',
            'name' => 'required|min_length[2]|max_length[150]',
            'type' => 'required|in_list[asset,liability,equity,revenue,expense]',
        ])) {
            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/chart-of-accounts')->with('success', 'Account created.');
    }

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

        $parent = ! empty($account['parent_id']) ? $this->accounts->find((int) $account['parent_id']) : null;

        return view('Modules\Accounting\Views\chart_of_accounts\show', array_merge($this->baseViewData(), [
            'title'   => 'Account Details',
            'account' => $account,
            'parent'  => $parent,
        ]));
    }

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

        $parents = array_values(array_filter(
            $this->accounts->getActive(),
            static function (array $row) use ($id): bool {
                return (int) $row['id'] !== $id;
            }
        ));

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

    public function update(int $id)
    {
        if (! $this->validate([
            'code' => 'required|max_length[30]',
            'name' => 'required|min_length[2]|max_length[150]',
            'type' => 'required|in_list[asset,liability,equity,revenue,expense]',
        ])) {
            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/chart-of-accounts')->with('success', 'Account updated.');
    }

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

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

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

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

        return redirect()->to('/accounting/chart-of-accounts')->with('success', 'Account deleted.');
    }
}
