<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Stripe\Stripe;
use Stripe\Checkout\Session;
use App\Models\WalletTransaction;

class StripeCheckoutController extends Controller
{


public function checkout(Request $request)
{
    // ✅ validate inline
    $data = $request->validate([
        'amount' => ['required', 'numeric', 'min:1'],
        'transaction_id' => ['required', 'exists:wallet_transactions,id'],
    ]);

    $transaction = WalletTransaction::findOrFail($data['transaction_id']);

    // 🔐 safety check
    abort_if(
        $transaction->status !== 'pending' ||
        $transaction->pm_type !== 'stripe',
        403,
        'Invalid transaction'
    );

    Stripe::setApiKey(config('services.stripe.secret'));

    $session = Session::create([
        'mode' => 'payment',
        'payment_method_types' => ['card'],
        'line_items' => [[
            'price_data' => [
                'currency' => 'usd',
                'unit_amount' => (int) round($data['amount'] * 100),
                'product_data' => [
                    'name' => 'Wallet Top-up',
                ],
            ],
            'quantity' => 1,
        ]],
        'success_url' => route('stripe.success') . '?session_id={CHECKOUT_SESSION_ID}',
        'cancel_url'  => route('stripe.cancel'),
        'metadata' => [
            'transaction_id' => $transaction->id,
            'user_id'        => auth()->id(),
            'amount'         => $data['amount'],
        ],
    ]);

    return redirect()->away($session->url);
}



public function success(Request $request)
{
    $sessionId = $request->query('session_id');

    if (! $sessionId) {
        abort(400, 'Missing session ID');
    }

    Stripe::setApiKey(config('services.stripe.secret'));

    $session = Session::retrieve($sessionId);

    // ✅ Ensure payment is completed
    if ($session->payment_status !== 'paid') {
        abort(400, 'Payment not completed');
    }

    // ✅ Get transaction_id from Stripe metadata
    $transactionId = $session->metadata->transaction_id ?? null;

    if (! $transactionId) {
        abort(400, 'Missing transaction metadata');
    }

    // ✅ Find related wallet transaction
    $transaction = WalletTransaction::where('id', $transactionId)
        ->where('status', 'pending')
        ->first();

    if (! $transaction) {
        abort(404, 'Wallet transaction not found or already processed');
    }

    // ✅ Store Stripe session ID (recommended)
    $transaction->update([
        'status'        => 'completed',
        'stripe_pm_id'  => $session->id,
    ]);

    // 🔔 wallet balance updates via observer

    return redirect()->route('filament.admin.pages.stripe-success', [
        'session_id' => $session->id,
    ]);
}



    public function checkoutApi(Request $request)
    {
        $request->validate([
            'amount' => ['required', 'numeric', 'min:1'],
        ]);

        $user = $request->user();
        $amount = (float) $request->amount;

        Stripe::setApiKey(config('services.stripe.secret'));

        $session = Session::create([
            'mode' => 'payment',
            'payment_method_types' => ['card'],

            'line_items' => [[
                'price_data' => [
                    'currency' => 'usd',
                    'unit_amount' => (int) round($amount * 100), // cents
                    'product_data' => [
                        'name' => 'Wallet Top-Up',
                    ],
                ],
                'quantity' => 1,
            ]],

            'success_url' => config('app.frontend_url') . '/stripe/success?session_id={CHECKOUT_SESSION_ID}',
            'cancel_url'  => config('app.frontend_url') . '/stripe/cancel',

            'metadata' => [
                'user_id' => $user->id,
                'amount'  => $amount,
            ],
        ]);

        return response()->json([
            'success' => true,
            'checkout_url' => $session->url,
            'session_id' => $session->id,
        ]);
    }
}
