<?php

namespace App\Livewire\Kot;

// use App\Events\FoodStatusChanged; // Temporarily disabled
use App\Models\Kot;
use Livewire\Component;

class KotCard extends Component
{
    public $kot;
    public $confirmDeleteKotModal = false;

    public function changeKotStatus($status)
    {
        // Store the previous status
        $previousStatus = $this->kot->status;
        
        // Update the KOT status
        Kot::where('id', $this->kot->id)->update([
            'status' => $status
        ]);
        
        // Refresh the kot model to get updated data
        $this->kot->refresh();
        
        // If status changed to food_ready, reset session count to trigger notification
        if ($previousStatus !== $status && $status === 'food_ready') {
            // Reset the session count so the notification component detects the change
            $currentCount = Kot::where('status', 'food_ready')->count();
            session(['food_ready_count' => $currentCount - 1]); // Set to one less to trigger increase detection
        }
        
        // Temporarily disable event dispatch to avoid 500 errors
        // if ($previousStatus !== $status) {
        //     event(new FoodStatusChanged($this->kot, $previousStatus, $status));
        // }

        $this->dispatch('refreshKots');
    }

    public function deleteKot($id)
    {
        $order = Kot::find($id)->order;
        $kotCounts = $order->kot->count();
        
        if ($kotCounts == 1) {
            $order->status = 'canceled';
            $order->save();

            if ($order->table) {
                $order->table->update(['available_status' => 'available']);
            }
        }

        Kot::destroy($id);
        $this->confirmDeleteKotModal = false;
        
        $this->dispatch('refreshKots');

        if ($kotCounts == 1) {
            $order->delete();
        }
    }

    public function render()
    {
        return view('livewire.kot.kot-card');
    }

}
