<?php

namespace App\Models\Tarifas\Maquinas;

use App\Entities\Tarifas\Maquinas\TarifaAcabadoMaquinaEntity;
use CodeIgniter\Database\BaseBuilder;
use CodeIgniter\Model;

class TarifaAcabadoMaquinaModel extends Model
{
    protected $table            = 'tarifa_acabado_maquinas';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = TarifaAcabadoMaquinaEntity::class;
    protected $useSoftDeletes   = true;
    protected $protectFields    = true;
    protected $allowedFields    = [
        "tarifa_acabado_id",
        "maquina_id",
        "maquina_tarea_id"
    ];

    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 for datatable
     *
     * @param integer|null $tarifa_acabado_id
     * @return BaseBuilder
     */
    public function queryDatatable(?int $tarifa_acabado_id = null) : BaseBuilder
    {
        $query =  $this->builder()->select(
            [
                "tarifa_acabado_maquinas.id",
                "lg_maquinas.nombre as maquinaNombre",
                "maquina_tareas.name as tareaNombre"
            ]
        )->join("lg_maquinas","lg_maquinas.id = tarifa_acabado_maquinas.maquina_id","left")
        ->join("maquina_tareas","maquina_tareas.id = tarifa_acabado_maquinas.maquina_tarea_id","left")
        ->where("tarifa_acabado_maquinas.deleted_at",null);
        if ($tarifa_acabado_id)
            $query->where("tarifa_acabado_maquinas.tarifa_acabado_id", $tarifa_acabado_id);
        return $query;
        
    }
}
