<?php

namespace App\Livewire\Articulado;

use App\Models\ElementalTasks;
use Livewire\Component;

use App\Models\Equipment;

use App\Models\EquipmentAssociationAmbit;
use App\Models\TasksAssociationAmbits;
use App\Models\FurtherTasks;

// Chama o Repositorio para amazenar as variaveis e depois conseguir chamar facilmente sem precisar de sessao. 
use App\Repositories\ReceiveTasksRepository;

class SelectElementalTasksInWonkstation extends Component
{
    public $workstation;

    // recebe todos os equipamentos e pode filtros por tipos de equipamentos.
    public $receiveAllEquipments = [];

    // Recebe todos os Ambitos nao repetidos, apos filtrar por todos os equipamentos.
    public $uniqueAmbitsIds = [];

    public $receiveAllFurtherTasks = [];

    public $receiveElementalTasks = [];

    public $dataElementalTasks;

    public $receiveAllAmbits = [];

    public $elementalTasksDetails = [];

    public $test;

    public function mount($workstation)
    {
        $this->workstation = $workstation;

        $this->receiveAllEquipments = Equipment::where('company_projects_id', $this->workstation->company_projects_id)
            ->join('equipment_association_ambits', 'equipments.equipment_id', '=', 'equipment_association_ambits.equipment_id')
            ->select('equipments.equipment_id', 'equipments.equipment_type_id', 'equipment_association_ambits.ambits_id')
            ->get()
            ->toArray();

        $this->receiveAllFurtherTasks = FurtherTasks::where('company_projects_id', $this->workstation->company_projects_id)
            ->get();

        // Inicializar a matriz
        $this->receiveElementalTasks = [
            'geral' => [],
            '1' => [],
            '2' => [],
            '3' => []
        ];

        // Coletar todos os elemental_tasks_id para cada equipment_type_id
        foreach ($this->receiveAllEquipments as $equipment) {
            $elementalTasksIds = TasksAssociationAmbits::where('ambits_equipment_id', $equipment['ambits_id'])
                ->pluck('elemental_tasks_id')
                ->toArray();

            // Inicializar cada ID como uma chave com um array vazio como valor
            foreach ($elementalTasksIds as $id) {
                $this->receiveElementalTasks[$equipment['equipment_type_id']][$id] = [];
            }
        }

        // Mover elemental_tasks_id que aparecem em mais de um equipment_type_id para 'geral'
        foreach ($this->receiveElementalTasks as $key1 => $values1) {
            foreach ($this->receiveElementalTasks as $key2 => $values2) {
                if ($key1 !== $key2 && $key1 !== 'geral' && $key2 !== 'geral') {
                    $commonValues = array_intersect_key($values1, $values2);
                    if (!empty($commonValues)) {
                        foreach ($commonValues as $value => $emptyArray) {
                            $this->receiveElementalTasks['geral'][$value] = [];
                            unset($this->receiveElementalTasks[$key1][$value]);
                            unset($this->receiveElementalTasks[$key2][$value]);
                        }
                    }
                }
            }
        }

        // Iterar sobre $receiveElementalTasks
        foreach ($this->receiveElementalTasks as $key => $ids) {
            // Para cada ID em uma chave específica, buscar os detalhes na tabela ElementalTasks
            $details = ElementalTasks::whereIn('elemental_tasks_id', array_keys($ids))
                ->select(['elemental_tasks_id', 'elemental_tasks_code', 'elemental_tasks_description'])
                ->get()
                ->toArray();

            // Atualizar o array $receiveElementalTasks com os detalhes
            foreach ($details as $detail) {
                $this->receiveElementalTasks[$key][$detail['elemental_tasks_id']] = [
                    'code' => $detail['elemental_tasks_code'],
                    'description' => $detail['elemental_tasks_description']
                ];
            }
        }

        // Armazenar os dados na sessão
        session([
            'receiveAllFurtherTasks' => $this->receiveAllFurtherTasks,
            'receiveElementalTasks' => $this->receiveElementalTasks,
        ]);
        
        $receiveTasksRepository = app(ReceiveTasksRepository::class);
        // Chama a variavel do Repositorio para amazenar a variavel e depois conseguir chamar facilmente. 
        $receiveTasksRepository->setElementalTasks($this->receiveElementalTasks);
        $receiveTasksRepository->setFurtherTasks($this->receiveAllFurtherTasks);
    }

    public function render()
    {
        return view('livewire.articulado.select-elemental-tasks-in-wonkstation');
    }
}
