<?php

namespace App\Http\Controllers\Frontend;

use App\Exceptions\CartException;
use App\Http\Controllers\Controller;
use App\Http\Requests\Frontend\CheckoutRequest;
use App\Models\Cart;
use App\Models\Product;
use App\Services\CartService;
use App\Services\OrderService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class CheckoutController extends Controller
{
    public function __construct(
        private readonly CartService $cartService,
        private readonly OrderService $orders,
    ) {}

    public function index(): View|RedirectResponse
    {
        $cart = Cart::current();

        if (! $cart || $cart->items->isEmpty()) {
            return redirect()->route('cart.index')->with('error', 'Your cart is empty.');
        }

        $cart->load(['items.product.primaryImage', 'items.variant.color', 'items.variant.size', 'coupon']);
        $totals = $this->cartService->totals($cart);

        return view('frontend.checkout.index', compact('cart', 'totals'));
    }

    public function store(CheckoutRequest $request): RedirectResponse
    {
        $cart = Cart::current();

        if (! $cart || $cart->items->isEmpty()) {
            return redirect()->route('cart.index')->with('error', 'Your cart is empty.');
        }

        $data = $request->validated();

        if ($request->hasFile('payment_proof')) {
            $data['payment_proof'] = $request->file('payment_proof')->store('payments', 'public');
        }

        try {
            $order = $this->orders->placeOrder($cart, $data);
        } catch (CartException $e) {
            return redirect()->route('cart.index')->with('error', $e->getMessage());
        }

        // Lets a guest view their own just-placed receipt without an
        // account — OrderController::show checks this before ownership.
        session(['last_order_id' => $order->id]);

        return redirect()->route('orders.show', $order)->with('success', 'Order placed successfully!');
    }

    /**
     * "Buy Now" from the product page (Step 8): add the single item then
     * jump straight to checkout, skipping a trip through the cart page.
     */
    public function buyNow(Request $request, Product $product): RedirectResponse
    {
        $request->validate([
            'variant_id' => ['required', 'exists:product_variants,id'],
            'quantity' => ['required', 'integer', 'min:1'],
        ]);

        $variant = $product->variants()->findOrFail($request->integer('variant_id'));

        try {
            $this->cartService->addItem($product, $variant, $request->integer('quantity'));
        } catch (CartException $e) {
            return back()->with('error', $e->getMessage());
        }

        return redirect()->route('checkout.index');
    }
}
