<?php

namespace App\Livewire\Store;

use App\Enums\OrderStatus;
use App\Models\GuestCustomer;
use App\Models\Order;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;

#[Layout('layouts.store')]
#[Title('Pesanan Saya')]
class Orders extends Component
{
    #[Url(as: 'status')]
    public string $filterStatus = '';

    public function render()
    {
        $sessionId = session()->getId();

        // Ambil guest customer milik session ini
        $guest = GuestCustomer::forSession($sessionId)->latest()->first();

        $orders = collect();

        if ($guest) {
            $query = Order::with(['payment'])
                ->withCount('items')
                ->where('guest_customer_id', $guest->id)
                ->when($this->filterStatus, function ($q) {
                    $status = OrderStatus::tryFrom($this->filterStatus);
                    if ($status) {
                        $q->where('status', $status);
                    }
                })
                ->latest();

            $orders = $query->get();
        }

        $statusTabs = [
            ''           => 'Semua',
            'pending'    => 'Menunggu',
            'paid'       => 'Dibayar',
            'processing' => 'Diproses',
            'delivering' => 'Dikirim',
            'completed'  => 'Selesai',
            'cancelled'  => 'Dibatalkan',
        ];

        return view('livewire.store.orders', compact('orders', 'statusTabs'));
    }
}
