<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'title', 'description', 'company_id', 'work_order_id',
        'technician_employee_id', 'priority', 'status', 'location',
        'scheduled_date', 'scheduled_start', 'scheduled_end',
        'arrived_at', 'completed_at', 'notes', 'created_by', 'updated_by',
    ];

    public const STATUSES = ['draft', 'scheduled', 'en_route', 'on_site', 'completed', 'cancelled'];

    public const OPEN_STATUSES = ['draft', 'scheduled', 'en_route', 'on_site'];

    public const PRIORITIES = ['low', 'normal', 'high', 'urgent'];

    public function scopeForList(?string $search = null, ?string $status = null, ?string $priority = null): self
    {
        $this->select(
            'fs_service_visits.*,
             companies.name AS company_name,
             technician.full_name AS technician_name,
             technician.employee_number AS technician_number,
             work_orders.number AS work_order_number'
        )
            ->join('companies', 'companies.id = fs_service_visits.company_id', 'left')
            ->join('employees AS technician', 'technician.id = fs_service_visits.technician_employee_id', 'left')
            ->join('work_orders', 'work_orders.id = fs_service_visits.work_order_id', 'left');

        if ($search) {
            $this->groupStart()
                ->like('fs_service_visits.number', $search)
                ->orLike('fs_service_visits.title', $search)
                ->orLike('fs_service_visits.location', $search)
                ->orLike('companies.name', $search)
                ->groupEnd();
        }

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

        if ($priority) {
            $this->where('fs_service_visits.priority', $priority);
        }

        return $this;
    }

    public function nextNumber(): string
    {
        $prefix = 'SV-' . date('ymd') . '-';
        $row = $this->like('number', $prefix, 'after')
            ->orderBy('id', 'DESC')
            ->first();

        $seq = 1;
        if ($row && preg_match('/-(\d+)$/', $row['number'], $m)) {
            $seq = (int) $m[1] + 1;
        }

        return $prefix . str_pad((string) $seq, 4, '0', STR_PAD_LEFT);
    }

    /**
     * @return list<array>
     */
    public function getOpenForSelect(): array
    {
        return $this->whereIn('status', self::OPEN_STATUSES)
            ->orderBy('scheduled_date', 'ASC')
            ->orderBy('id', 'DESC')
            ->findAll();
    }
}
