<?php

namespace App\Services;

use App\Entities\Configuracion\Maquina;
use App\Models\Configuracion\MaquinaModel;
use App\Models\Configuracion\MaquinasCallesModel;
use App\Models\Configuracion\MaquinasDefectoModel;
use App\Models\Configuracion\MaquinasPapelesImpresionModel;
use App\Models\Configuracion\MaquinasTarifasImpresionModel;
use CodeIgniter\Config\BaseService;



class MaquinaService extends BaseService
{

    


    protected Maquina $maquina;
    protected MaquinaModel $maquinaModel;
    protected MaquinasDefectoModel $maquinaDefectoModel;
    protected MaquinasCallesModel $maquinaCalleModel;
    protected MaquinasPapelesImpresionModel $maquinaPapelesImpresionModel;
    protected MaquinasTarifasImpresionModel $maquinaTarifaImpresionModel;

    public function __construct()
    {
        $this->maquinaModel = model(MaquinaModel::class);
        $this->maquinaDefectoModel = model(MaquinasDefectoModel::class);
        $this->maquinaCalleModel = model(MaquinasCallesModel::class);
        $this->maquinaPapelesImpresionModel = model(MaquinasPapelesImpresionModel::class);
        $this->maquinaTarifaImpresionModel = model(MaquinasTarifasImpresionModel::class);


    }
    public function setMaquina(int $maquina_id): self
    {
        $this->maquina = $this->maquinaModel->find($maquina_id);
        return $this;
    }
    public function duplicate(string $newName): ?Maquina
    {

        $maquina_array = $this->maquina->toArray();
        $maquina_array['nombre'] = $newName;
        $maquinaDuplicatedId = $this->maquinaModel->insert($maquina_array);
        $maquinaWithAllRelations = $this->maquina->withAll()->toArray();

        $maquina_defecto = $maquinaWithAllRelations['maquina_defecto'];
        $maquina_papeles_impresion = $maquinaWithAllRelations['papeles_impresion'];
        $maquina_calles = $maquinaWithAllRelations['maquina_calles'];
        $maquina_tarifas_impresion = $maquinaWithAllRelations['tarifas_impresion'];


        foreach ($maquina_defecto as $md) 
        {
            unset($md['id']);
            $md['maquina_id'] = $maquinaDuplicatedId;   
            $this->maquinaDefectoModel->insert($md);
             
        }
        foreach ($maquina_papeles_impresion as $mpi) 
        {
            unset($mpi['id']);
            $mpi['maquina_id'] = $maquinaDuplicatedId;   
            $this->maquinaPapelesImpresionModel->insert($mpi); 
        }
        foreach ($maquina_calles as $mc) 
        {
            unset($mc['id']);
            $mc['maquina_id'] = $maquinaDuplicatedId;    
            $this->maquinaCalleModel->insert($mc);
        }
        foreach ($maquina_tarifas_impresion as $mti) 
        {
            unset($mti['id']);
            $mti['maquina_id'] = $maquinaDuplicatedId;    
            $this->maquinaTarifaImpresionModel->insert($mti);
        }
        return $this->maquinaModel->find($maquinaDuplicatedId)->withAll();
    }
}
