<?php

namespace Modules\Accounting\Controllers;

use App\Controllers\BaseController;
use App\Models\AssetCategoryModel;
use App\Models\ChartOfAccountModel;
use Modules\Accounting\Services\AssetCategoryService;

class AssetCategoryController extends BaseController
{
    protected AssetCategoryModel $categories;
    protected AssetCategoryService $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->categories = new AssetCategoryModel();
        $this->service    = new AssetCategoryService();
        $this->accounts   = new ChartOfAccountModel();
    }

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

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

        return view('Modules\Accounting\Views\asset_categories\index', array_merge($this->baseViewData(), [
            'title'      => 'Asset Categories',
            'categories' => $categories,
            'filters'    => compact('search', 'status'),
        ]));
    }

    public function createForm()
    {
        return view('Modules\Accounting\Views\asset_categories\create', array_merge($this->baseViewData(), [
            'title'    => 'Add Asset Category',
            'accounts' => $this->accounts->getActivePostable(),
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'code'               => 'required|max_length[30]',
            'name'               => 'required|min_length[2]|max_length[150]',
            'useful_life_months' => '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/asset-categories')->with('success', 'Asset category created.');
    }

    public function editForm(int $id)
    {
        $category = $this->categories->find($id);
        if (! $category) {
            return redirect()->to('/accounting/asset-categories')->with('error', 'Asset category not found.');
        }

        return view('Modules\Accounting\Views\asset_categories\edit', array_merge($this->baseViewData(), [
            'title'    => 'Edit Asset Category',
            'category' => $category,
            'accounts' => $this->accounts->getActivePostable(),
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'code'               => 'required|max_length[30]',
            'name'               => 'required|min_length[2]|max_length[150]',
            'useful_life_months' => '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/asset-categories')->with('success', 'Asset category updated.');
    }

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

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

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

        return redirect()->back()->with('success', 'Asset category deactivated.');
    }

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

        return redirect()->to('/accounting/asset-categories')->with('success', 'Asset category deleted.');
    }
}
