<?php

namespace App\Livewire\ManagementDashboard;

use Livewire\Component;

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


class WorkManagement extends Component
{
    public $totalEquipments;
    public $type1Count;
    public $type2Count;
    public $type3Count;

    public function mount()
    {
        $this->refreshData();
    }

    public function refreshData()

    {
        $this->totalEquipments = Equipment::count();

        // Inicializar type3Count como 0
        $this->type3Count = 0;

        // Obter todos os equipamentos
        $equipments = Equipment::all();
        
        foreach ($equipments as $equipment) {

            // conta quantos dados existem na model OrderEquipmentTasks, referente ao equipamento indicado
            $tasksCount = OrderEquipmentTasks::where('equipment_id', $equipment->equipment_id)->count();
            // Verifica quantos dados tem ao mesmo equipamento
            $controlCount = ControlEquipmentWorkstation::where('equipment_id', $equipment->equipment_id)->count();

            if ($controlCount >= $tasksCount) {
                $isValid = ControlEquipmentWorkstation::where('equipment_id', $equipment->equipment_id)
                    ->whereNotNull('entry_date')
                    ->whereNotNull('departure_date')
                    ->count() >= $tasksCount;

                if ($isValid) {
                    $this->type3Count++;
                    $type3EquipmentIds[] = $equipment->equipment_id;
                }
            }
        }

        // Atualizar type2Count
        $this->type2Count = Equipment::whereIn('equipment_id', ControlEquipmentWorkstation::select('equipment_id'))
            ->whereNotIn('equipment_id', $type3EquipmentIds)
            ->count();

        // Contar equipamentos que NÃO estão em ControlEquipmentWorkstation
        $this->type1Count = Equipment::whereNotIn('equipment_id', ControlEquipmentWorkstation::select('equipment_id'))->count();

    }
    public function render()
    {
        return view('livewire.management-dashboard.work-management');
    }
}
