<?php

namespace App\Models\OrdenTrabajo;

use App\Entities\Produccion\OrdenTrabajoDateEntity;
use CodeIgniter\Database\MySQLi\Builder;
use CodeIgniter\Model;
use Config\OrdenTrabajo;

class OrdenTrabajoDate extends Model
{
    protected $table            = 'orden_trabajo_dates';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = OrdenTrabajoDateEntity::class;
    protected $useSoftDeletes   = true;
    protected $protectFields    = true;
    protected $allowedFields    = [
        "orden_trabajo_id",
        "fecha_entrada_at",
        //IMPRESION
        "interior_bn_at",
        "interior_color_at",
        "cubierta_at",
        //ACABADO
        "plastificado_at",
        "encuadernacion_at",
        "corte_at",
        "preparacion_interiores_at",
        "entrada_manipulado_at",
        "cosido_at",
        "solapa_at",
        "grapado_at",
        "retractilado_at",
        "retractilado5_at",
        "prototipo_at",
        "marcapaginas_at",
        "espiral_at",
        //FERRO
        "pendiente_ferro_at",
        "ferro_en_cliente_at",
        "ferro_ok_at",
        //ENVIO
        "embalaje_at",
        "envio_at",
        //PREIMPRESION
        "pre_formato_at",
        "pre_lomo_at",
        "pre_solapa_at",
        "pre_codbarras_at",
        "pre_imposicion_at"
    ];

    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;
    }

    protected function updateOrdenTrabajoUser(array $data) : array
    {
        if(!isset($data["data"])){
            return $data;
        }else{
            $this->updateUserDateMap($data["id"],$data["data"]);
        }
        return $data;
    }
    public function updateUserDateMap($orden_trabajo_id,$data){
        $ordenTrabajoConfig  = new OrdenTrabajo();
        $mapping = $ordenTrabajoConfig->DATE_USER_MAPPING;
        $otUser = model(OrdenTrabajoUser::class);
        $auth_user_id = auth()->user()->id;
        foreach ($data as $key => $value) {
            if(isset($mapping[$key])){
                if($value){
                    $otUser->where('orden_trabajo_id',$orden_trabajo_id)
                    ->set([$mapping[$key] => $auth_user_id])
                    ->update();
                }
            }
        }
        return $data;
    }
}
