<?php

namespace App\Http\Controllers;

use App\Models\Product;
use Illuminate\Http\Request;
use Laravel\Cashier\Checkout;

class CheckoutController extends Controller
{
    /**
     * One-off product purchase via Stripe Checkout — guest friendly,
     * price comes straight from the auto-synced catalogue.
     */
    public function product(Request $request, Product $product)
    {
        abort_unless($product->active && $product->stripe_price_id, 404);

        $quantity = max(1, min(20, (int) $request->input('quantity', 1)));

        return Checkout::guest()->create(
            [$product->stripe_price_id => $quantity],
            [
                'success_url' => route('checkout.success').'?session_id={CHECKOUT_SESSION_ID}',
                'cancel_url'  => route('store.show', $product),
                'metadata'    => [
                    'product_id' => $product->id,
                    'quantity'   => $quantity,
                ],
            ],
        );
    }

    public function success(Request $request)
    {
        return view('store.success');
    }
}
