<?php

namespace App\Models\OrdenTrabajo;

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

class OrdenTrabajoDate extends Model
{
    protected $table            = 'orden_trabajo_dates';
    protected $primaryKey       = 'orden_trabajo_id';
    protected $useAutoIncrement = false;
    protected $returnType       = OrdenTrabajoDateEntity::class;
    protected $useSoftDeletes   = true;
    protected $protectFields    = true;
    protected $allowedFields    = [
        "orden_trabajo_id",
        "fecha_entrada_at",
        "fecha_entrega_at",
        "fecha_entrega_real_at",
        "fecha_entrega_change_at",
        "fecha_impresion_at",
        "fecha_encuadernado_at",
        "fecha_externo_at",
        "pendiente_ferro_at",
        "ferro_en_cliente_at",
        "ferro_ok_at",
        "interior_bn_at",
        "interior_color_at",
        "preparacion_interiores_at",
        "cubierta_at",
        "plastificado_at",
        "encuadernacion_at",
        "corte_at",
        "embalaje_at",
        "envio_at",
        "entrada_manipulado_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    = ["updateOrdenTrabajoUser"];
    protected $beforeUpdate   = ["updateOrdenTrabajoUser"];
    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["data"]);
        }
        return $data;
    }
    protected function updateUserDateMap($data){
        $mapping = [
            "fecha_encuadernado_at" => "encuadernacion_user_id",
            // "fecha_externo_at" => "null",
            "fecha_impresion_at" => "null",
            "pendiente_ferro_at" => "pendiente_ferro_user_id",
            "ferro_en_cliente_at" => "ferro_en_cliente_user_id",
            "ferro_ok_at" => "ferro_ok_user_id",
            "interior_bn_at" => "interior_bn_user_id",
            "interior_color_at" => "interior_color_user_id",
            "preparacion_interiores_at" => "preparacion_interior_user_id",
            "cubierta_at" => "cubierta_user_id",
            "plastificado_at" => "plastificado_user_id",
            "corte_at" => "corte_user_id",
            "embalaje_at" => "embalaje_user_id",
            "entrada_manipulado_at" => "entrada_manipulado_user_id"  
        ];
        $otUser = model(OrdenTrabajoUser::class);
        $auth_user_id = auth()->user()->id;
        foreach ($data as $key => $value) {
            if(isset($mapping[$key])){
                if($value){
                    $otUser->update($data["orden_trabajo_id"],[$mapping[$key] => $auth_user_id]);
                }
            }
        }
    }
}
