<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'schedule_id', 'stop_order', 'employee_id', 'latitude', 'longitude',
        'address', 'pickup_time', 'leg_distance_km', 'leg_duration_minutes',
    ];

    public function getForSchedule(int $scheduleId): array
    {
        return $this->select(
            'transport_schedule_stops.*,
             employees.full_name AS employee_name,
             employees.employee_number,
             employees.phone AS employee_phone'
        )
            ->join('employees', 'employees.id = transport_schedule_stops.employee_id', 'left')
            ->where('schedule_id', $scheduleId)
            ->orderBy('stop_order', 'ASC')
            ->findAll();
    }

    /**
     * @param list<int> $scheduleIds
     *
     * @return array<int, list<array>>
     */
    public function getForSchedulesGrouped(array $scheduleIds): array
    {
        if ($scheduleIds === []) {
            return [];
        }

        $rows = $this->select(
            'transport_schedule_stops.*,
             employees.full_name AS employee_name,
             employees.employee_number'
        )
            ->join('employees', 'employees.id = transport_schedule_stops.employee_id', 'left')
            ->whereIn('schedule_id', $scheduleIds)
            ->orderBy('schedule_id', 'ASC')
            ->orderBy('stop_order', 'ASC')
            ->findAll();

        $grouped = [];
        foreach ($rows as $row) {
            $grouped[(int) $row['schedule_id']][] = $row;
        }

        return $grouped;
    }

    public function replaceForSchedule(int $scheduleId, array $stops): void
    {
        $this->where('schedule_id', $scheduleId)->delete();

        foreach ($stops as $index => $stop) {
            $employeeId = (int) ($stop['employee_id'] ?? 0);
            if ($employeeId <= 0) {
                continue;
            }

            $this->insert([
                'schedule_id'          => $scheduleId,
                'stop_order'           => (int) ($stop['stop_order'] ?? ($index + 1)),
                'employee_id'          => $employeeId,
                'latitude'             => $stop['latitude'],
                'longitude'            => $stop['longitude'],
                'address'              => $stop['address'] ?? null,
                'pickup_time'          => $stop['pickup_time'] ?? null,
                'leg_distance_km'      => $stop['leg_distance_km'] ?? 0,
                'leg_duration_minutes' => $stop['leg_duration_minutes'] ?? 0,
            ]);
        }
    }

    public function deleteForSchedule(int $scheduleId): void
    {
        $this->where('schedule_id', $scheduleId)->delete();
    }
}
