<?php

namespace App\Models\OrdenTrabajo;

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

class OrdenTrabajoTarea extends Model
{
    protected $table            = 'orden_trabajo_tareas';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = OrdenTrabajoTareaEntity::class;
    protected $useSoftDeletes   = true;
    protected $protectFields    = true;
    protected $allowedFields    = [
        "orden_trabajo_id",
        "presupuesto_linea_id",
        "presupuesto_acabado_id",
        "presupuesto_preimpresion_id",
        "presupuesto_encuadernado_id",
        "presupuesto_extra_id",
        "presupuesto_manipulado_id",
        "nombre",
        "orden",
        "maquina_id",
        "imposicion_id",
        "tiempo_estimado",
        "tiempo_real",
        "is_corte",
        "tipo_corte",
        "comment"
    ];

    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    = [];
    protected $beforeUpdate   = [];
    protected $afterUpdate    = [];
    protected $beforeFind     = [];
    protected $afterFind      = [];
    protected $beforeDelete   = [];
    protected $afterDelete    = [];

    /**
     * Query datatable
     *
     * @return Builder
     */
    protected function getQueryDatatable() : Builder
    {
        $q = $this->builder()
        ->select([
            "orden_trabajo_tareas.orden",
            "mp.nombre as maquina_presupuesto",
            "m.nombre as maquina_tarea",
            "orden_trabajo_tareas.tiempo_estimado",
            "orden_trabajo_tareas.tiempo_real"
        ])
        ->join("presupuesto_linea","presupuesto_linea.id = orden_trabajo_tareas.presupuesto_linea_id","left")
        ->join("lg_maquinas m","lg_maquinas.id = orden_trabajo_tareas.maquina_id","left")
        ->join("lg_maquinas mp","lg_maquinas.id = presupuesto_linea.maquina_id","left")
        ->join("lg_imposiciones", "lg_imposiciones.id = orden_trabajo_tareas.imposicion_id" , "left")
        ->where("orden_trabajo_tareas.deleted_at" , NULL);

        return $q;
    }
 

    
}
