<?php

namespace App\Models;

use CodeIgniter\Model;

class MaintenanceInterventionTaskModel extends Model
{
    protected $table         = 'maintenance_intervention_tasks';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $useTimestamps = true;
    protected $allowedFields = [
        'maintenance_intervention_id',
        'maintenance_task_id',
        'sequence_no',
        'task_label',
        'task_description_snapshot',
        'status',
        'notes',
        'performed_by_user_id',
        'due_at',
        'completed_at',
    ];

    public function withRelations()
    {
        return $this->select(
            'maintenance_intervention_tasks.*, maintenance_tasks.task_code, maintenance_tasks.category,' .
            ' users.name AS performed_by_name'
        )
            ->join('maintenance_tasks', 'maintenance_tasks.id = maintenance_intervention_tasks.maintenance_task_id')
            ->join('users', 'users.id = maintenance_intervention_tasks.performed_by_user_id', 'left');
    }

    public function forIntervention(int $interventionId): array
    {
        return $this->withRelations()
            ->where('maintenance_intervention_tasks.maintenance_intervention_id', $interventionId)
            ->orderBy('maintenance_intervention_tasks.sequence_no', 'ASC')
            ->findAll();
    }
}
