<?php

namespace Modules\Accounting\Controllers;

use App\Controllers\BaseController;
use App\Models\AssetDisposalModel;
use App\Models\ChartOfAccountModel;
use App\Models\FixedAssetModel;
use Modules\Accounting\Services\AssetDisposalService;

class AssetDisposalController extends BaseController
{
    protected AssetDisposalModel $disposals;
    protected AssetDisposalService $service;
    protected FixedAssetModel $assets;
    protected ChartOfAccountModel $accounts;

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

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

        $disposals = $this->disposals
            ->scopeForList($search ?: null, $status)
            ->orderBy('asset_disposals.disposal_date', 'DESC')
            ->orderBy('asset_disposals.id', 'DESC')
            ->findAll();

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

    public function createForm()
    {
        return view('Modules\Accounting\Views\asset_disposals\create', array_merge($this->baseViewData(), [
            'title'    => 'New Asset Disposal',
            'assets'   => $this->assets->whereIn('status', ['active', 'fully_depreciated'])->orderBy('name', 'ASC')->findAll(),
            'accounts' => $this->accounts->getActivePostable(),
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'fixed_asset_id' => 'required|is_natural_no_zero',
            'disposal_date'  => 'required|valid_date',
            'proceeds'       => 'permit_empty|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/asset-disposals/' . $result['id'])->with('success', 'Asset disposal created.');
    }

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

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

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

        $assets = $this->assets->whereIn('status', ['active', 'fully_depreciated'])->orderBy('name', 'ASC')->findAll();
        $linked = $this->assets->find((int) $disposal['fixed_asset_id']);
        if ($linked) {
            $found = false;
            foreach ($assets as $a) {
                if ((int) $a['id'] === (int) $linked['id']) {
                    $found = true;
                    break;
                }
            }
            if (! $found) {
                array_unshift($assets, $linked);
            }
        }

        return view('Modules\Accounting\Views\asset_disposals\edit', array_merge($this->baseViewData(), [
            'title'    => 'Edit Asset Disposal',
            'disposal' => $disposal,
            'assets'   => $assets,
            'accounts' => $this->accounts->getActivePostable(),
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'fixed_asset_id' => 'required|is_natural_no_zero',
            'disposal_date'  => 'required|valid_date',
            'proceeds'       => 'permit_empty|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/asset-disposals/' . $id)->with('success', 'Asset disposal updated.');
    }

    public function post(int $id)
    {
        $result = $this->service->post($id, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->with('error', $result['error']);
        }

        return redirect()->back()->with('success', 'Asset disposal posted.');
    }

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

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