<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'title', 'description', 'priority', 'status',
        'scheduled_date', 'due_date', 'location', 'notes', 'rejection_reason',
        'completion_notes', 'started_at', 'completed_at', 'completed_by',
        'created_by', 'updated_by',
    ];

    public const STATUSES = [
        'draft', 'open', 'in_progress', 'on_hold',
        'pending_approval', 'rejected', 'completed', 'cancelled',
    ];

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

    public const SUBMITTABLE_STATUSES = ['draft', 'open', 'rejected'];

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

    public function scopeForList(?string $search = null, ?string $status = null, ?string $priority = null): self
    {
        $this->select('work_orders.*');

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

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

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

        return $this;
    }

    public function nextNumber(): string
    {
        $prefix = 'WO-' . 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);
    }

    public function countByStatus(): array
    {
        $rows = $this->select('status, COUNT(*) AS total')
            ->groupBy('status')
            ->findAll();

        $counts = array_fill_keys(self::STATUSES, 0);
        foreach ($rows as $row) {
            $counts[$row['status']] = (int) $row['total'];
        }

        return $counts;
    }

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

    /**
     * @return list<array>
     */
    public function getCompletedForReport(?string $from = null, ?string $to = null, ?string $search = null): array
    {
        $this->select('work_orders.*')
            ->where('work_orders.status', 'completed');

        if ($from) {
            $this->where('DATE(work_orders.completed_at) >=', $from);
        }

        if ($to) {
            $this->where('DATE(work_orders.completed_at) <=', $to);
        }

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

        return $this->orderBy('work_orders.completed_at', 'DESC')
            ->orderBy('work_orders.id', 'DESC')
            ->findAll();
    }
}
