<?php

namespace Modules\Leave\Controllers;

use App\Controllers\BaseController;
use App\Models\BranchModel;
use App\Models\HolidayModel;
use Modules\Leave\Services\HolidayService;

class HolidayController extends BaseController
{
    protected HolidayModel $holidays;
    protected BranchModel $branches;
    protected HolidayService $service;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->holidays  = new HolidayModel();
        $this->branches  = new BranchModel();
        $this->service   = new HolidayService();
    }

    public function index()
    {
        $search   = trim((string) $this->request->getGet('q'));
        $year     = (int) ($this->request->getGet('year') ?: date('Y'));
        $branchId = $this->request->getGet('branch_id') ?: null;

        $holidayList = $this->holidays
            ->scopeForList($search ?: null, $year, $branchId ? (int) $branchId : null)
            ->orderBy('date', 'ASC')
            ->findAll();

        return view('Modules\Leave\Views\holidays\index', array_merge($this->baseViewData(), [
            'title'    => 'Holiday Calendar',
            'holidays' => $holidayList,
            'branches' => $this->branches->orderBy('name', 'ASC')->findAll(),
            'filters'  => compact('search', 'year', 'branchId'),
        ]));
    }

    public function createForm()
    {
        return view('Modules\Leave\Views\holidays\create', array_merge($this->baseViewData(), [
            'title'    => 'Add Holiday',
            'branches' => $this->branches->orderBy('name', 'ASC')->findAll(),
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'name' => 'required|min_length[2]|max_length[150]',
            'date' => 'required|valid_date[Y-m-d]',
        ])) {
            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('/holidays')->with('success', 'Holiday created.');
    }

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

        return view('Modules\Leave\Views\holidays\edit', array_merge($this->baseViewData(), [
            'title'    => 'Edit Holiday',
            'holiday'  => $holiday,
            'branches' => $this->branches->orderBy('name', 'ASC')->findAll(),
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'name' => 'required|min_length[2]|max_length[150]',
            'date' => 'required|valid_date[Y-m-d]',
        ])) {
            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('/holidays')->with('success', 'Holiday updated.');
    }

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

        return redirect()->to('/holidays')->with('success', 'Holiday deleted.');
    }
}
