<?php

namespace App\Livewire\Execução;

use Livewire\Component;
use App\Models\ControlEquipmentWorkstation;
use App\Models\ConstructionWorkstation;

use Illuminate\Support\Facades\DB;

class WorkstationDashboard extends Component
{
    public $receivefnishTasksInWorkstation;

    public $lastUpdated;

    public function mount()
    {
        // Obtendo todos os registros onde entry_date e departure_date não são nulos
        $validWorkstations = ControlEquipmentWorkstation::whereNotNull('entry_date')
            ->whereNotNull('departure_date')
            ->get();


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

        // Inicializando um array para armazenar a contagem
        // $workstationCounts = [];

        // // Iterando sobre os registros válidos
        // foreach ($validWorkstations as $workstation) {
        //     // Obtendo o id_workstations do registro atual
        //     $workstationId = $workstation->id_workstations;

        //     // Se o id_workstations já existe no array, incrementa o contador, senão, inicializa com 1
        //     if (isset($workstationCounts[$workstationId])) {
        //         $workstationCounts[$workstationId]++;
        //     } else {
        //         $workstationCounts[$workstationId] = 1;
        //     }
        // }

        // dump($workstationCounts);

        $workstationCounts = ControlEquipmentWorkstation::select('id_workstations', DB::raw('count(*) as count'))
            ->whereNotNull('id_workstations')
            ->whereNotNull('entry_date')
            ->whereNotNull('departure_date')
            ->groupBy('id_workstations')
            ->get()
            ->pluck('count', 'id_workstations')
            ->toArray();

        $receiveNameWK = [];

        foreach ($workstationCounts as $wkId1 => $count) {
            $wkId1 = ConstructionWorkstation::find($wkId1);
            if ($wkId1) {
                $receiveNameWK[$wkId1->nomenclature_workstation] = $count;
            }
        }

        $this->receivefnishTasksInWorkstation = $receiveNameWK;
    }

    public function updateData()
    {
        // Atualize a variável com os novos dados
        $this->receivefnishTasksInWorkstation = [1, 2, 3];

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

        // Emita um evento com os novos dados
        $this->dispatch('updateChart', $this->receivefnishTasksInWorkstation);
    }

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