<?php

namespace App\Livewire;

use Livewire\Component;
use App\Models\Order;
use App\Models\OrderItem;
use Illuminate\Support\Collection;

class KitchenOrders extends Component
{
    public Collection $kitchenItems;

    protected $listeners = [
        'orderStatusUpdated' => 'loadKitchenOrders', // Jika ada event dari luar yang memicu refresh
        'refreshKitchenOrders' => 'loadKitchenOrders', // Event kustom untuk refresh manual
    ];

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

    public function loadKitchenOrders()
    {
        $orders = Order::with(['items'])
            ->whereIn('transaction_status', ['settlement', 'confirmed']) // ✅ Tambahkan 'confirmed'
            ->get();
        $items = [];

        foreach ($orders as $order) {
            foreach ($order->items as $item) {
                $items[] = [
                    'id' => $item->order_id,
                    'name' => $item->item_name,
                    'quantity' => $item->quantity ?? 1,
                    'table_id' => $order->table_id,
                    'customer_name' => $order->customer_name,
                    'order_id' => $order->id,
                    'updated_at' => $order->updated_at,
                    'cooked' => $item->cooked ?? false,
                ];
            }
        }

        $this->kitchenItems = collect($items)->groupBy('order_id');
    }

    public function markAsCooked($orderItemId) // Mengubah parameter menjadi orderItemId
    {
        $orderItem = OrderItem::find($orderItemId);

        if (!$orderItem) {
            $this->dispatch('notify', message: 'Item pesanan tidak ditemukan.', type: 'error');
            return;
        }

        $orderItem->cooked = true;
        $orderItem->save();

        $this->loadKitchenOrders();
        $this->dispatch('notify', message: 'Item "' . $orderItem->item_name . '" pada pesanan #' . $orderItem->order_id . ' ditandai sebagai sudah dimasak.', type: 'success');
    }

    public function markAllAsCooked($orderId)
    {
        $order = Order::with('items')->find($orderId);

        if (!$order) return;

        foreach ($order->items as $item) {
            // Akses properti 'cooked' langsung dari objek $item OrderItem
            if (!$item->cooked) { // <-- PERUBAHAN PENTING DI SINI
                $item->cooked = true;
                $item->save(); // Simpan perubahan pada setiap OrderItem
            }
        }

        $this->loadKitchenOrders();
        $this->dispatch('notify', message: 'Semua item pada pesanan #' . $orderId . ' ditandai sebagai sudah dimasak.', type: 'success');
    }

    public function render()
    {
        return view('livewire.kitchen-orders');
    }
}
