<?php

namespace Modules\Accounting\Controllers;

use App\Controllers\BaseController;
use App\Models\DepreciationRunLineModel;
use App\Models\DepreciationRunModel;
use Modules\Accounting\Services\DepreciationService;

class DepreciationController extends BaseController
{
    protected DepreciationRunModel $runs;
    protected DepreciationRunLineModel $lines;
    protected DepreciationService $service;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->runs    = new DepreciationRunModel();
        $this->lines   = new DepreciationRunLineModel();
        $this->service = new DepreciationService();
    }

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

        $runs = $this->runs
            ->scopeForList($search ?: null, $status)
            ->orderBy('run_date', 'DESC')
            ->orderBy('id', 'DESC')
            ->findAll();

        return view('Modules\Accounting\Views\depreciation\index', array_merge($this->baseViewData(), [
            'title'   => 'Depreciation',
            'runs'    => $runs,
            'filters' => compact('search', 'status'),
        ]));
    }

    public function createForm()
    {
        return view('Modules\Accounting\Views\depreciation\create', array_merge($this->baseViewData(), [
            'title' => 'New Depreciation Run',
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'period_start' => 'required|valid_date',
            'period_end'   => 'required|valid_date',
            'run_date'     => 'required|valid_date',
        ])) {
            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/depreciation/' . $result['id'])->with('success', 'Depreciation run created.');
    }

    public function show(int $id)
    {
        $run = $this->runs->find($id);
        if (! $run) {
            return redirect()->to('/accounting/depreciation')->with('error', 'Depreciation run not found.');
        }

        return view('Modules\Accounting\Views\depreciation\show', array_merge($this->baseViewData(), [
            'title' => 'Depreciation Run',
            'run'   => $run,
            'lines' => $this->lines->getForRun($id),
        ]));
    }

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

        return view('Modules\Accounting\Views\depreciation\edit', array_merge($this->baseViewData(), [
            'title' => 'Edit Depreciation Run',
            'run'   => $run,
            'lines' => $this->lines->getForRun($id),
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'period_start' => 'required|valid_date',
            'period_end'   => 'required|valid_date',
            'run_date'     => 'required|valid_date',
        ])) {
            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/depreciation/' . $id)->with('success', 'Depreciation run 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', 'Depreciation run posted.');
    }

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

        return redirect()->to('/accounting/depreciation')->with('success', 'Depreciation run deleted.');
    }
}
