<?php

namespace Modules\Accounting\Controllers;

use App\Controllers\BaseController;
use App\Models\CostCenterModel;
use Modules\Accounting\Services\CostCenterService;

class CostCenterController extends BaseController
{
    protected CostCenterModel $centers;
    protected CostCenterService $service;

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

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

        $centers = $this->centers
            ->scopeForList($search ?: null, $status)
            ->orderBy('cost_centers.code', 'ASC')
            ->findAll();

        return view('Modules\Accounting\Views\cost_centers\index', array_merge($this->baseViewData(), [
            'title'   => 'Cost Centers',
            'centers' => $centers,
            'filters' => compact('search', 'status'),
        ]));
    }

    public function createForm()
    {
        return view('Modules\Accounting\Views\cost_centers\create', array_merge($this->baseViewData(), [
            'title'   => 'Add Cost Center',
            'parents' => $this->centers->getActive(),
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'code' => 'required|max_length[30]',
            'name' => 'required|min_length[2]|max_length[150]',
        ])) {
            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/cost-centers')->with('success', 'Cost center created.');
    }

    public function editForm(int $id)
    {
        $center = $this->centers->find($id);
        if (! $center) {
            return redirect()->to('/settings/cost-centers')->with('error', 'Cost center not found.');
        }

        $parents = array_values(array_filter(
            $this->centers->getActive(),
            static fn (array $row): bool => (int) $row['id'] !== $id
        ));

        return view('Modules\Accounting\Views\cost_centers\edit', array_merge($this->baseViewData(), [
            'title'   => 'Edit Cost Center',
            'center'  => $center,
            'parents' => $parents,
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'code' => 'required|max_length[30]',
            'name' => 'required|min_length[2]|max_length[150]',
        ])) {
            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/cost-centers')->with('success', 'Cost center updated.');
    }

    public function activate(int $id)
    {
        $this->service->activate($id, (int) $this->session->get('user_id'));

        return redirect()->back()->with('success', 'Cost center activated.');
    }

    public function deactivate(int $id)
    {
        $this->service->deactivate($id, (int) $this->session->get('user_id'));

        return redirect()->back()->with('success', 'Cost center deactivated.');
    }

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

        return redirect()->to('/settings/cost-centers')->with('success', 'Cost center deleted.');
    }
}
