<?php

namespace App\Models;

use CodeIgniter\Model;

class TransportEmployeePickupModel extends Model
{
    protected $table         = 'transport_employee_pickups';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $useTimestamps = true;
    protected $dateFormat    = 'datetime';

    protected $allowedFields = [
        'employee_id', 'address', 'latitude', 'longitude',
        'status', 'notes', 'created_by', 'updated_by',
    ];

    public const STATUSES = ['active', 'inactive'];

    public function scopeForList(?string $search = null, ?string $status = null): self
    {
        $this->select(
            'transport_employee_pickups.*,
             employees.employee_number,
             employees.full_name AS employee_name,
             employees.phone AS employee_phone'
        )
            ->join('employees', 'employees.id = transport_employee_pickups.employee_id', 'left');

        if ($search) {
            $this->groupStart()
                ->like('employees.full_name', $search)
                ->orLike('employees.employee_number', $search)
                ->orLike('transport_employee_pickups.address', $search)
                ->groupEnd();
        }

        if ($status) {
            $this->where('transport_employee_pickups.status', $status);
        }

        return $this;
    }

    public function getForEmployee(int $employeeId): ?array
    {
        return $this->where('employee_id', $employeeId)->first();
    }

    /**
     * Active pickup points keyed by employee id for a set of employees.
     *
     * @param int[] $employeeIds
     *
     * @return array<int, array>
     */
    public function getActiveForEmployees(array $employeeIds): array
    {
        if ($employeeIds === []) {
            return [];
        }

        $rows = $this->select(
            'transport_employee_pickups.*,
             employees.full_name AS employee_name,
             employees.employee_number'
        )
            ->join('employees', 'employees.id = transport_employee_pickups.employee_id', 'left')
            ->whereIn('transport_employee_pickups.employee_id', $employeeIds)
            ->where('transport_employee_pickups.status', 'active')
            ->findAll();

        $byEmployee = [];
        foreach ($rows as $row) {
            $byEmployee[(int) $row['employee_id']] = $row;
        }

        return $byEmployee;
    }
}
