<?php

namespace Modules\Accounting\Controllers;

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

class FixedAssetController extends BaseController
{
    protected FixedAssetModel $assets;
    protected FixedAssetService $service;
    protected AssetCategoryModel $categories;
    protected ChartOfAccountModel $accounts;

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

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

        $assets = $this->assets
            ->scopeForList($search ?: null, $status, $categoryId ? (int) $categoryId : null)
            ->orderBy('fixed_assets.purchase_date', 'DESC')
            ->orderBy('fixed_assets.id', 'DESC')
            ->findAll();

        return view('Modules\Accounting\Views\fixed_assets\index', array_merge($this->baseViewData(), [
            'title'      => 'Fixed Assets',
            'assets'     => $assets,
            'categories' => $this->categories->getActive(),
            'filters'    => compact('search', 'status', 'categoryId'),
        ]));
    }

    public function createForm()
    {
        return view('Modules\Accounting\Views\fixed_assets\create', array_merge($this->baseViewData(), [
            'title'      => 'New Fixed Asset',
            'categories' => $this->categories->getActive(),
            'accounts'   => $this->accounts->getActivePostable(),
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'name'          => 'required|min_length[2]|max_length[200]',
            'category_id'   => 'required|is_natural_no_zero',
            'purchase_date' => 'required|valid_date',
            'cost'          => 'required|decimal',
        ])) {
            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/fixed-assets/' . $result['id'])->with('success', 'Fixed asset created.');
    }

    public function show(int $id)
    {
        $asset = $this->assets->scopeForList()->where('fixed_assets.id', $id)->first();
        if (! $asset) {
            return redirect()->to('/accounting/fixed-assets')->with('error', 'Fixed asset not found.');
        }

        return view('Modules\Accounting\Views\fixed_assets\show', array_merge($this->baseViewData(), [
            'title' => 'Fixed Asset',
            'asset' => $asset,
        ]));
    }

    public function editForm(int $id)
    {
        $asset = $this->assets->find($id);
        if (! $asset) {
            return redirect()->to('/accounting/fixed-assets')->with('error', 'Fixed asset not found.');
        }
        if ($asset['status'] !== 'active') {
            return redirect()->to('/accounting/fixed-assets/' . $id)->with('error', 'Only active assets can be edited.');
        }

        return view('Modules\Accounting\Views\fixed_assets\edit', array_merge($this->baseViewData(), [
            'title'      => 'Edit Fixed Asset',
            'asset'      => $asset,
            'categories' => $this->categories->getActive(),
            'accounts'   => $this->accounts->getActivePostable(),
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'name'          => 'required|min_length[2]|max_length[200]',
            'category_id'   => 'required|is_natural_no_zero',
            'purchase_date' => 'required|valid_date',
            'cost'          => 'required|decimal',
        ])) {
            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/fixed-assets/' . $id)->with('success', 'Fixed asset updated.');
    }

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

        return redirect()->to('/accounting/fixed-assets')->with('success', 'Fixed asset deleted.');
    }
}
