<?php

namespace App\Http\Controllers\Frontend;

use App\Enums\UserRole;
use App\Http\Controllers\Controller;
use App\Models\Order;
use Illuminate\View\View;

class OrderController extends Controller
{
    /**
     * Serves the guest's post-checkout receipt, a logged-in customer's
     * "My Orders" detail view, and an admin reviewing any order (linked
     * from the Payments screen, Step 11). A guest can only see the order
     * they just placed (flashed into session at checkout) — there's no
     * account to authenticate a guest against later, and order receipts
     * carry PII (name, phone, address), so this can't be left wide open.
     */
    public function show(Order $order): View
    {
        $ownedByCurrentUser = auth()->check() && $order->user_id === auth()->id();
        $isAdmin = auth()->check() && auth()->user()->role === UserRole::Admin;
        // Scoped to true guest orders (user_id null) only — a stale
        // "last_order_id" flash in a shared/reused session must never be
        // able to authorize viewing an order that belongs to an account.
        $justPlacedAsGuest = is_null($order->user_id) && session('last_order_id') === $order->id;

        abort_unless($ownedByCurrentUser || $isAdmin || $justPlacedAsGuest, 403);

        $order->load(['items.product.primaryImage', 'payments', 'statusHistories']);

        return view('frontend.orders.show', compact('order'));
    }

    public function accountIndex(): View
    {
        $orders = auth()->user()->orders()->latest()->paginate(10);

        return view('frontend.account.orders', compact('orders'));
    }
}
