<?php

namespace App\Livewire;

use App\Models\Line;
use App\Models\Plant;
use App\Models\ProductionQuantity;
use Carbon\Carbon;
use Livewire\Component;

class SelectPlant extends Component
{

    protected $listeners = [
        'plant-line-updated' => 'updatePlantLine',
        'productionUpdated' => '$refresh'
    ];

    public $plantId;
    public $lineId;

    public $hourlyData = [];

    public function updatePlantLine($plantId, $lineId)
    {
        session(['plantId' => $plantId, 'lineId' => $lineId]);
        $this->plantId = $plantId;
        $this->lineId = $lineId;
        $this->loadData();
    }

    // Method to load hourly production data
    public function loadData()
    {
        // Define the time range from today 8:00 AM to the next day 8:00 AM
        $today = now()->startOfDay()->addHours(8);  // Today 8:00 AM
        $nextDay = $today->copy()->addDay();  // Next day 8:00 AM

        // Initialize the array to hold the hourly data
        $productionCounts = [];

        // Loop through each hour from today 8:00 AM to the next day 8:00 AM
    for ($i = 0; $i < 24; $i++) {
        // Define the start and end time for the current hour
        $startOfHour = $today->copy()->addHours($i);  // Start of the hour
        $endOfHour = $startOfHour->copy()->addHour()->subSeconds(1);  // End of the hour

        // Query the production counts for the current hour (between start and end time)
        $count = ProductionQuantity::query()
            ->where('plant_id', $this->plantId)
            ->where('line_id', $this->lineId)
            ->whereBetween('created_at', [$startOfHour, $endOfHour])
            ->count();  // Count the number of records in the current hour

        // Store the count for the current hour in the production counts array
        $productionCounts[$i] = $count;

    }

        // Set the hourly data to be used in the component's view
        $this->hourlyData = $productionCounts;

    }

    // public function render()
    // {
    //     return view('livewire.select-plant', [
    //         'hourlyData' => $this->hourlyData,
    //     ]);
    // }

    public function mount()
    {
        $this->plantId = session('plantId');
        $this->lineId = session('lineId');

        if ($this->plantId && $this->lineId) {
            $this->loadData();
        }
    }

}
