<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'title', 'description', 'priority', 'status',
        'due_date', 'completed_at', 'assignee_employee_id',
        'created_by', 'updated_by',
    ];

    public const STATUSES = ['open', 'in_progress', 'completed', 'cancelled'];

    public const OPEN_STATUSES = ['open', 'in_progress'];

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

    public const PRIORITY_ORDER = ['urgent' => 1, 'high' => 2, 'normal' => 3, 'low' => 4];

    public function scopeForList(?string $search = null, ?string $status = null, ?string $priority = null): self
    {
        $this->select('operations_tasks.*, employees.full_name AS assignee_name, employees.employee_number AS assignee_number')
            ->join('employees', 'employees.id = operations_tasks.assignee_employee_id', 'left');

        if ($search) {
            $this->groupStart()
                ->like('operations_tasks.number', $search)
                ->orLike('operations_tasks.title', $search)
                ->orLike('operations_tasks.description', $search)
                ->groupEnd();
        }

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

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

        return $this;
    }

    public function nextNumber(): string
    {
        $prefix = 'OT-' . 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 getOpenForChecklist(): array
    {
        return $this->whereIn('status', self::OPEN_STATUSES)
            ->orderBy('due_date', 'ASC')
            ->orderBy('id', 'DESC')
            ->findAll();
    }

    /**
     * @return list<array>
     */
    public function getByPriorityView(?string $search = null): array
    {
        return $this->scopeForList($search, null, null)
            ->whereIn('operations_tasks.status', self::OPEN_STATUSES)
            ->orderBy("FIELD(operations_tasks.priority, 'urgent', 'high', 'normal', 'low')", '', false)
            ->orderBy('operations_tasks.due_date', 'ASC')
            ->orderBy('operations_tasks.id', 'DESC')
            ->findAll();
    }

    /**
     * @return list<array>
     */
    public function getDeadlinesView(?string $search = null): array
    {
        return $this->scopeForList($search, null, null)
            ->whereIn('operations_tasks.status', self::OPEN_STATUSES)
            ->where('operations_tasks.due_date IS NOT NULL', null, false)
            ->orderBy('operations_tasks.due_date', 'ASC')
            ->orderBy('operations_tasks.id', 'DESC')
            ->findAll();
    }
}
