<?php

namespace Modules\Accounting\Controllers;

use App\Controllers\BaseController;
use App\Models\BudgetModel;
use App\Models\ChartOfAccountModel;
use App\Models\CostCenterModel;
use Modules\Accounting\Services\BudgetService;

class BudgetController extends BaseController
{
    protected BudgetModel $budgets;
    protected BudgetService $service;
    protected ChartOfAccountModel $accounts;
    protected CostCenterModel $centers;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->budgets  = new BudgetModel();
        $this->service  = new BudgetService();
        $this->accounts = new ChartOfAccountModel();
        $this->centers  = new CostCenterModel();
    }

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

        $budgets = $this->budgets
            ->scopeForList($search ?: null, $status, $fiscalYear)
            ->orderBy('budgets.fiscal_year', 'DESC')
            ->orderBy('budgets.id', 'DESC')
            ->findAll();

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

    public function createForm()
    {
        return view('Modules\Accounting\Views\budgets\create', array_merge($this->baseViewData(), [
            'title'       => 'New Budget',
            'accounts'    => $this->accounts->getActivePostable(),
            'costCenters' => $this->centers->getActive(),
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'name'        => 'required|min_length[2]|max_length[150]',
            'fiscal_year' => 'required|is_natural_no_zero',
            'period_from' => 'required|valid_date',
            'period_to'   => 'required|valid_date',
            'account_id'  => 'required|is_natural_no_zero',
            'amount'      => '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/budgets')->with('success', 'Budget created.');
    }

    public function show(int $id)
    {
        $budget = $this->budgets
            ->scopeForList()
            ->where('budgets.id', $id)
            ->first();

        if (! $budget) {
            return redirect()->to('/accounting/budgets')->with('error', 'Budget not found.');
        }

        return view('Modules\Accounting\Views\budgets\show', array_merge($this->baseViewData(), [
            'title'  => 'Budget ' . $budget['number'],
            'budget' => $budget,
        ]));
    }

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

        return view('Modules\Accounting\Views\budgets\edit', array_merge($this->baseViewData(), [
            'title'       => 'Edit Budget',
            'budget'      => $budget,
            'accounts'    => $this->accounts->getActivePostable(),
            'costCenters' => $this->centers->getActive(),
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'name'        => 'required|min_length[2]|max_length[150]',
            'fiscal_year' => 'required|is_natural_no_zero',
            'period_from' => 'required|valid_date',
            'period_to'   => 'required|valid_date',
            'account_id'  => 'required|is_natural_no_zero',
            'amount'      => 'required|decimal',
            'status'      => 'required|in_list[draft,active,closed]',
        ])) {
            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/budgets/' . $id)->with('success', 'Budget updated.');
    }

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

        return redirect()->to('/accounting/budgets')->with('success', 'Budget deleted.');
    }
}
