<?php

namespace Modules\Transport\Controllers;

use App\Controllers\BaseController;
use App\Models\ActivityLogModel;
use App\Models\EmployeeModel;
use App\Models\TransportEmployeePickupModel;
use Modules\Transport\Services\MapSettingsService;

class EmployeePickupController extends BaseController
{
    protected TransportEmployeePickupModel $pickups;

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

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

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

        // Active employees still missing a pickup point, so planners can see coverage gaps.
        $missing = (new EmployeeModel())
            ->select('employees.id, employees.full_name, employees.employee_number')
            ->join('transport_employee_pickups tep', 'tep.employee_id = employees.id', 'left')
            ->where('employees.status', 'active')
            ->where('tep.id IS NULL')
            ->orderBy('employees.full_name', 'ASC')
            ->findAll(50);

        return view('Modules\Transport\Views\ai\pickups\index', array_merge($this->baseViewData(), [
            'title'   => 'Employee Pickup Points',
            'entries' => $entries,
            'pager'   => $this->pickups->pager,
            'filters' => compact('search', 'status'),
            'missing' => $missing,
        ]));
    }

    public function createForm()
    {
        return view('Modules\Transport\Views\ai\pickups\create', array_merge($this->baseViewData(), [
            'title'       => 'Add Pickup Point',
            'pickup'      => [],
            'employees'   => $this->employeesWithoutPickup(),
            'mapSettings' => (new MapSettingsService())->getSettings(),
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'employee_id' => 'required|integer',
            'latitude'    => 'required|decimal',
            'longitude'   => 'required|decimal',
            'status'      => 'permit_empty|in_list[active,inactive]',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $employeeId = (int) $this->request->getPost('employee_id');
        if ($this->pickups->getForEmployee($employeeId)) {
            return redirect()->back()->withInput()->with('errors', ['employee_id' => 'This employee already has a pickup point. Edit the existing one instead.']);
        }

        $userId = (int) $this->session->get('user_id');
        $this->pickups->insert($this->mapInput($userId) + ['employee_id' => $employeeId, 'created_by' => $userId], true);
        $id = (int) $this->pickups->getInsertID();
        (new ActivityLogModel())->log('transport_ai', 'pickup_created', $userId, "Created pickup point #{$id} for employee #{$employeeId}", (string) $id);

        return redirect()->to('/transport/ai/pickups')->with('success', 'Pickup point saved.');
    }

    public function editForm(int $id)
    {
        $pickup = $this->pickups->scopeForList()->where('transport_employee_pickups.id', $id)->first();
        if (! $pickup) {
            return redirect()->to('/transport/ai/pickups')->with('error', 'Pickup point not found.');
        }

        return view('Modules\Transport\Views\ai\pickups\edit', array_merge($this->baseViewData(), [
            'title'       => 'Edit Pickup Point',
            'pickup'      => $pickup,
            'mapSettings' => (new MapSettingsService())->getSettings(),
        ]));
    }

    public function update(int $id)
    {
        if (! $this->pickups->find($id)) {
            return redirect()->to('/transport/ai/pickups')->with('error', 'Pickup point not found.');
        }

        if (! $this->validate([
            'latitude'  => 'required|decimal',
            'longitude' => 'required|decimal',
            'status'    => 'permit_empty|in_list[active,inactive]',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $userId = (int) $this->session->get('user_id');
        $this->pickups->update($id, $this->mapInput($userId));
        (new ActivityLogModel())->log('transport_ai', 'pickup_updated', $userId, "Updated pickup point #{$id}", (string) $id);

        return redirect()->to('/transport/ai/pickups')->with('success', 'Pickup point updated.');
    }

    public function destroy(int $id)
    {
        if (! $this->pickups->find($id)) {
            return redirect()->to('/transport/ai/pickups')->with('error', 'Pickup point not found.');
        }

        $userId = (int) $this->session->get('user_id');
        $this->pickups->delete($id);
        (new ActivityLogModel())->log('transport_ai', 'pickup_deleted', $userId, "Deleted pickup point #{$id}", (string) $id);

        return redirect()->to('/transport/ai/pickups')->with('success', 'Pickup point deleted.');
    }

    protected function mapInput(int $userId): array
    {
        $status = (string) $this->request->getPost('status');

        return [
            'address'    => trim((string) $this->request->getPost('address')) ?: null,
            'latitude'   => $this->request->getPost('latitude'),
            'longitude'  => $this->request->getPost('longitude'),
            'status'     => in_array($status, TransportEmployeePickupModel::STATUSES, true) ? $status : 'active',
            'notes'      => trim((string) $this->request->getPost('notes')) ?: null,
            'updated_by' => $userId,
        ];
    }

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

        $builder = (new EmployeeModel())
            ->select('employees.id, employees.full_name, employees.employee_number')
            ->join('transport_employee_pickups tep', 'tep.employee_id = employees.id', 'left')
            ->where('employees.status', 'active')
            ->where('employees.deleted_at', null)
            ->where('tep.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();
    }
}
