<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'subject_type', 'subject_id', 'subject_label',
        'metric_code', 'metric_name', 'score', 'max_score',
        'period_start', 'period_end', 'status', 'notes',
        'scored_by', 'created_by', 'updated_by',
    ];

    public const SUBJECT_TYPES = ['employee', 'work_order', 'service_visit', 'inspection'];

    public const STATUSES = ['draft', 'published'];

    public function scopeForList(
        ?string $search = null,
        ?string $status = null,
        ?string $subjectType = null
    ): self {
        $this->select('qc_performance_scores.*, employees.full_name AS scored_by_name')
            ->join('employees', 'employees.id = qc_performance_scores.scored_by', 'left');

        if ($search) {
            $this->groupStart()
                ->like('qc_performance_scores.number', $search)
                ->orLike('qc_performance_scores.metric_code', $search)
                ->orLike('qc_performance_scores.metric_name', $search)
                ->orLike('qc_performance_scores.subject_label', $search)
                ->groupEnd();
        }

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

        if ($subjectType) {
            $this->where('qc_performance_scores.subject_type', $subjectType);
        }

        return $this;
    }

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