<?php

namespace Modules\Accounting\Controllers;

use App\Controllers\BaseController;
use App\Models\FiscalYearModel;
use Modules\Accounting\Services\FiscalYearService;

class FiscalYearController extends BaseController
{
    protected FiscalYearModel $periods;
    protected FiscalYearService $service;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->periods = new FiscalYearModel();
        $this->service = new FiscalYearService();
    }

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

        $periods = $this->periods
            ->scopeForList($search ?: null, $status)
            ->orderBy('start_date', 'DESC')
            ->findAll();

        return view('Modules\Accounting\Views\fiscal_years\index', array_merge($this->baseViewData(), [
            'title'   => 'Fiscal Years',
            'periods' => $periods,
            'filters' => compact('search', 'status'),
        ]));
    }

    public function createForm()
    {
        return view('Modules\Accounting\Views\fiscal_years\create', array_merge($this->baseViewData(), [
            'title' => 'Add Fiscal Year',
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'name'       => 'required|min_length[2]|max_length[100]',
            'code'       => 'required|max_length[30]',
            'start_date' => 'required|valid_date',
            'end_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('/settings/fiscal-years')->with('success', 'Financial period created.');
    }

    public function editForm(int $id)
    {
        $period = $this->periods->find($id);
        if (! $period) {
            return redirect()->to('/settings/fiscal-years')->with('error', 'Financial period not found.');
        }

        return view('Modules\Accounting\Views\fiscal_years\edit', array_merge($this->baseViewData(), [
            'title'  => 'Edit Fiscal Year',
            'period' => $period,
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'name'       => 'required|min_length[2]|max_length[100]',
            'code'       => 'required|max_length[30]',
            'start_date' => 'required|valid_date',
            'end_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('/settings/fiscal-years')->with('success', 'Financial period updated.');
    }

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

        return redirect()->back()->with('success', 'Financial period closed.');
    }

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

        return redirect()->back()->with('success', 'Financial period reopened.');
    }

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

        return redirect()->to('/settings/fiscal-years')->with('success', 'Financial period deleted.');
    }
}
