<?php

namespace Modules\Transport\Controllers;

use App\Controllers\BaseController;
use App\Models\EmployeeModel;
use App\Models\TransportDriverModel;
use Modules\Transport\Services\DriverService;

class DriverController extends BaseController
{
    protected TransportDriverModel $drivers;
    protected DriverService $service;

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

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

        $entries = $this->drivers
            ->scopeForList($search ?: null, $status)
            ->orderBy('employees.full_name', 'ASC')
            ->paginate(25);

        return view('Modules\Transport\Views\drivers\index', array_merge($this->baseViewData(), [
            'title'   => 'Drivers',
            'entries' => $entries,
            'pager'   => $this->drivers->pager,
            'filters' => compact('search', 'status'),
        ]));
    }

    public function createForm()
    {
        return view('Modules\Transport\Views\drivers\create', array_merge($this->baseViewData(), [
            'title'     => 'Add Driver',
            'driver'    => [],
            'employees' => $this->activeEmployees(),
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'employee_id'    => 'required|is_natural_no_zero',
            'license_number' => 'required|max_length[80]',
            'status'         => 'permit_empty|in_list[active,inactive,suspended]',
        ])) {
            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('/transport/drivers/' . $result['id'])->with('success', 'Driver created.');
    }

    public function show(int $id)
    {
        $driver = $this->drivers->scopeForList()->where('transport_drivers.id', $id)->first();
        if (! $driver) {
            return redirect()->to('/transport/drivers')->with('error', 'Driver not found.');
        }

        return view('Modules\Transport\Views\drivers\show', array_merge($this->baseViewData(), [
            'title'  => $driver['employee_name'] ?? $driver['number'],
            'driver' => $driver,
        ]));
    }

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

        return view('Modules\Transport\Views\drivers\edit', array_merge($this->baseViewData(), [
            'title'     => 'Edit Driver',
            'driver'    => $driver,
            'employees' => $this->activeEmployees(),
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'employee_id'    => 'required|is_natural_no_zero',
            'license_number' => 'required|max_length[80]',
            'status'         => 'permit_empty|in_list[active,inactive,suspended]',
        ])) {
            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('/transport/drivers/' . $id)->with('success', 'Driver updated.');
    }

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

        return redirect()->to('/transport/drivers')->with('success', 'Driver deleted.');
    }

    protected function activeEmployees(): array
    {
        $search = trim((string) $this->request->getGet('employee_q'));

        $builder = (new EmployeeModel())
            ->select('employees.id, employees.full_name, employees.employee_number')
            ->join('transport_drivers td', 'td.employee_id = employees.id', 'left')
            ->where('employees.status', 'active')
            ->where('employees.deleted_at', null)
            ->where('td.id IS NULL');

        if ($search !== '') {
            $builder->groupStart()
                ->like('employees.full_name', $search)
                ->orLike('employees.employee_number', $search)
                ->groupEnd();
        }

        return $builder->orderBy('employees.full_name', 'ASC')->limit(100)->findAll();
    }
}
