<?php

namespace App\Models\OrdenTrabajo;

use App\Entities\Produccion\OrdenTrabajoTareaEntity;
use App\Entities\Produccion\OrdenTrabajoTareaProgressDateEntity;
use CodeIgniter\Database\MySQLi\Builder;
use CodeIgniter\Model;

class OrdenTrabajoTareaProgressDate extends Model
{
    protected $table            = 'orden_trabajo_tarea_progress_dates';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = OrdenTrabajoTareaProgressDateEntity::class;
    protected $useSoftDeletes   = true;
    protected $protectFields    = true;
    protected $allowedFields    = [
        "ot_tarea_id",
        "action_at",
        "action_user_id",
        "estado"
    ];

    protected bool $allowEmptyInserts = false;
    protected bool $updateOnlyChanged = true;

    protected array $casts = [];
    protected array $castHandlers = [];

    // Dates
    protected $useTimestamps = true;
    protected $dateFormat    = 'datetime';
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    protected $deletedField  = 'deleted_at';

    // Validation
    protected $validationRules      = [];
    protected $validationMessages   = [];
    protected $skipValidation       = false;
    protected $cleanValidationRules = true;

    // Callbacks
    protected $allowCallbacks = true;
    protected $beforeInsert   = [];
    protected $afterInsert    = ['updateTiempoReal'];
    protected $beforeUpdate   = [];
    protected $afterUpdate    = [];
    protected $beforeFind     = [];
    protected $afterFind      = [];
    protected $beforeDelete   = [];
    protected $afterDelete    = [];


    protected function updateTiempoReal(array $data)
    {
        if (!isset($data['data']['estado']) && !isset($data['data']['ot_tarea_id']) ) {
            return $data;
        }
        $m = model(OrdenTrabajoTarea::class);
        $ot_tarea = $m->find($data['data']['ot_tarea_id']);
        if($ot_tarea){
            $tiempo_real = $ot_tarea->tiempo_trabajado();
            $m->update($data['data']['ot_tarea_id'],['tiempo_real' => $tiempo_real]);
        }

        return $data;
    }
    
}
