<?php

namespace Modules\Accounting\Controllers;

use App\Controllers\BaseController;
use App\Models\ChartOfAccountModel;
use App\Models\TaxRateModel;
use Modules\Accounting\Services\TaxRateService;

class TaxRateController extends BaseController
{
    protected TaxRateModel $rates;
    protected TaxRateService $service;
    protected ChartOfAccountModel $accounts;

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

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

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

        return view('Modules\Accounting\Views\tax_rates\index', array_merge($this->baseViewData(), [
            'title'   => 'Tax Rates',
            'rates'   => $rates,
            'filters' => compact('search', 'status', 'taxType'),
        ]));
    }

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

    public function store()
    {
        if (! $this->validate([
            'code'     => 'required|max_length[30]',
            'name'     => 'required|min_length[2]|max_length[150]',
            'rate'     => 'required|decimal',
            'tax_type' => 'required|in_list[vat,sales,withholding,other]',
        ])) {
            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/tax-rates')->with('success', 'Tax rate created.');
    }

    public function editForm(int $id)
    {
        $rate = $this->rates->find($id);
        if (! $rate) {
            return redirect()->to('/accounting/tax-rates')->with('error', 'Tax rate not found.');
        }

        return view('Modules\Accounting\Views\tax_rates\edit', array_merge($this->baseViewData(), [
            'title'    => 'Edit Tax Rate',
            'rate'     => $rate,
            'accounts' => $this->accounts->getActive(),
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'code'     => 'required|max_length[30]',
            'name'     => 'required|min_length[2]|max_length[150]',
            'rate'     => 'required|decimal',
            'tax_type' => 'required|in_list[vat,sales,withholding,other]',
        ])) {
            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/tax-rates')->with('success', 'Tax rate updated.');
    }

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

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

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

        return redirect()->back()->with('success', 'Tax rate deactivated.');
    }

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

        return redirect()->to('/accounting/tax-rates')->with('success', 'Tax rate deleted.');
    }
}
