<?php

namespace App\Livewire\Execução;

use App\Models\Equipment;
use App\Models\OrderEquipmentTasks;
use App\Models\ControlEquipmentWorkstation;
use App\Models\ElementalTasks;

use Livewire\Component;

use App\Repositories\ReceiveTasksRepository;

class TasksDashboard extends Component
{
    public $datasProject;
    // protected $receiveTasksRepository;

    public $receiveElementalTasks; // Recebe todas as acoes ja feitas atualmente por tarefa
    public $receiveElementalTasksAll;// Recebe o total de tarefas que vamos fazer

    public $countElementalTasks;
    public $countElementalTasksAll;
    public $lastUpdated;
    
    // Por enquanto nao ira usar, vamos deixar  
    // public $receiveAllFurtherTasks;

  

    // Deveria funcionar para receber o Repositorio. 
    // public function initialize()
    // {
    //     // Injetar o repositório
    //     $this->receiveTasksRepository = app(ReceiveTasksRepository::class);

    //     // Agora você pode usar o repositório
    //     $this->receiveElementalTasks = $this->receiveTasksRepository->getElementalTasks();
    //     $this->receiveAllFurtherTasks = $this->receiveTasksRepository->getFurtherTasks();
    // }

    public function updateTimeGrafics()
    {
        // Data atual
        $this->lastUpdated = now()->format('Y-m-d H:i');

        // Chame o método para atualizar os dados dos gráficos
        $this->refreshDataEquipments($this->datasProject);

        // Disparar um evento com os dados atualizados
        $this->dispatch('refreshData', [
            'receiveElementalTasks' => $this->receiveElementalTasks,
            'receiveElementalTasksAll' => $this->receiveElementalTasksAll,
        ]);
    }

    // Graficos de porcentagem entre o valor atual de finalizadas com valor final de quantas faltam
    public function showPercentageElementalTasks()
    {
        // Disparar um evento com os dados atualizados
        $this->dispatch('refreshPercentageElementalTasks', [
            'receiveElementalTasks' => $this->receiveElementalTasks,
            'receiveElementalTasksAll' => $this->receiveElementalTasksAll,
            'countElementalTasksAll'=> $this->countElementalTasksAll
        ]);
    }

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

        // Obter todos os equipamentos relacionados ao projeto
        $receiveEquipmentsProject = Equipment::where('company_projects_id', $datasProject->company_projects_id)->get();

        $elementalTasks = collect();
        $furtherTasks = collect();

        // Total de tarefas na Obra.
        $elementalTasksCountsAll = [];

        foreach ($receiveEquipmentsProject as $equipment) {
            // Obter todas as OrderEquipmentTasks relacionadas a este equipamento
            $relatedTasks = OrderEquipmentTasks::where('equipment_id', $equipment->equipment_id)->get();

            // Filtrar e armazenar os IDs únicos de elemental_tasks_id e further_tasks_id
            $elementalTasks = $elementalTasks->merge($relatedTasks->whereNotNull('elemental_tasks_id')->pluck('elemental_tasks_id'))->unique();
            $furtherTasks = $furtherTasks->merge($relatedTasks->whereNotNull('further_tasks_id')->pluck('further_tasks_id'))->unique();

            // Agrupar as tasks relacionadas por elemental_tasks_id e contar o número de ocorrências
            $groupedTasks = $relatedTasks->whereNotNull('elemental_tasks_id')->groupBy('elemental_tasks_id');

            foreach ($groupedTasks as $taskId => $tasksGroup) {
                if (isset($elementalTasksCountsAll[$taskId])) {
                    $elementalTasksCountsAll[$taskId] += count($tasksGroup);
                } else {
                    $elementalTasksCountsAll[$taskId] = count($tasksGroup);
                }
            }
        }
        $this->receiveElementalTasksAll = $elementalTasksCountsAll;

        // Contar o número de ocorrências de cada ID na tabela ControlEquipmentWorkstation
        $elementalTasksCount1 = ControlEquipmentWorkstation::whereIn('elemental_tasks_id', $elementalTasks)->get()->countBy('elemental_tasks_id');
        $furtherTasksCount1 = ControlEquipmentWorkstation::whereIn('further_tasks_id', $furtherTasks)->get()->countBy('further_tasks_id');

        $newArray = [];

        foreach ($elementalTasksCount1 as $taskId => $count) {
            $task = ElementalTasks::find($taskId);
            if ($task) {
                $newArray[$task->elemental_tasks_code] = $count;
            }
        }

        $this->receiveElementalTasks = $newArray;

        $newArray1 = [];

        foreach ($this->receiveElementalTasksAll as $taskId1 => $count) {
            $task1 = ElementalTasks::find($taskId1);
            if ($task1) {
                $newArray1[$task1->elemental_tasks_code] = $count;
            }
        }

        // Agora, $newArray contém a contagem de tasks por elemental_tasks_code
        $this->receiveElementalTasksAll = $newArray1;

        
        // Criar o contador para receber o valor total. 
       $this->countElementalTasksAll =array_sum($this->receiveElementalTasksAll);


       $this->lastUpdated = now()->format('Y-m-d H:i');
    }



    public  function refreshDataEquipments($datasProject)
    {
    }

    public function render()
    {
        return view('livewire.execução.tasks-dashboard');
    }
}
