<?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\Component;

#[Layout('layouts.store')]
#[Title('Detail Pesanan')]
class OrderShow extends Component
{
    public Order $order;

    public function mount(string $orderNumber): void
    {
        $sessionId = session()->getId();

        // Pastikan order ini milik session yang sama
        $guest = GuestCustomer::forSession($sessionId)->latest()->first();

        abort_unless($guest !== null, 404);

        $this->order = Order::with([
                'items',
                'payment',
                'deliveryArea',
            ])
            ->where('order_number', $orderNumber)
            ->where('guest_customer_id', $guest->id)
            ->firstOrFail();
    }

    public function render()
    {
        // Bangun timeline status (urutan tetap, sama dengan Admin Panel)
        $statusOrder = [
            OrderStatus::Pending,
            OrderStatus::Paid,
            OrderStatus::Processing,
            OrderStatus::Delivering,
            OrderStatus::Completed,
        ];

        $currentStatus = $this->order->status;
        $isCancelled   = $currentStatus === OrderStatus::Cancelled;

        $timeline = [];

        // Step 0: Pesanan Dibuat
        $timeline[] = [
            'label'  => 'Pesanan Dibuat',
            'done'   => true,
            'active' => false,
            'time'   => $this->order->created_at,
        ];

        foreach ($statusOrder as $status) {
            $isActive = $currentStatus === $status;
            $isDone   = $this->isDone($status, $currentStatus, $isCancelled);

            $timeline[] = [
                'label'  => $status->label(),
                'done'   => $isDone && ! $isActive,
                'active' => $isActive,
                'time'   => null, // timestamp detail tersedia di Admin Panel
            ];
        }

        if ($isCancelled) {
            $timeline[] = [
                'label'  => OrderStatus::Cancelled->label(),
                'done'   => false,
                'active' => true,
                'time'   => null,
            ];
        }

        return view('livewire.store.order-show', compact('timeline'));
    }

    private function isDone(OrderStatus $check, OrderStatus $current, bool $isCancelled): bool
    {
        if ($isCancelled) {
            return in_array($check, [OrderStatus::Pending]);
        }

        $order = [
            OrderStatus::Pending,
            OrderStatus::Paid,
            OrderStatus::Processing,
            OrderStatus::Delivering,
            OrderStatus::Completed,
        ];

        $checkIdx   = array_search($check,   $order);
        $currentIdx = array_search($current, $order);

        return $checkIdx !== false && $currentIdx !== false && $checkIdx <= $currentIdx;
    }
}
