<?php

namespace App\Http\Controllers;

use App\Models\Receipt;
use App\Models\Subscription;
use App\Models\SubscriptionProduct;
use App\Models\UserCourse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Stripe\Checkout\Session;
use Stripe\Customer;
use Stripe\Stripe;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class PaymentController extends Controller
{
    public function checkout() {

        $user = Auth::user();
        $courses = $user->courses()->wherePivot('status_id', 1)->get();

        if ($courses->isEmpty()) {
            return back()->with('error', 'Your cart is empty.');
        }

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

        $lineItems = [];

        foreach ($courses as $course) {
            $lineItems[] = [
                'price_data' => [
                    'currency' => 'eur',
                    'product_data' => [
                        'name' => $course->title,
                    ],
                    'unit_amount' => $course->price * 100,
                ],
                'quantity' => 1,
            ];
        }

        $session = Session::create([
            'payment_method_types' => ['card'],
            'line_items' => $lineItems,
            'mode' => 'payment',
            'success_url' => route('payment.success'). '?session_id={CHECKOUT_SESSION_ID}',
            'cancel_url' => route('myCartPage'),
        ]);

        return redirect($session->url);
    }

    public function checkoutSubscription($id) {

        $subscription = SubscriptionProduct::findOrFail($id);

        if ($subscription->price <= 0) {
            return back()->with('error', 'This plan is free and does not require payment');
        }

        if (!$subscription->stripe_price_id) {
            return back()->with('error', "The product of this subscription doesn't exist on Stripe");
        }

        // dd($subscription->stripe_price_id);

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

        $session = Session::create([
            'payment_method_types' => ['card'],
            'line_items' => [[
                'price' => $subscription->stripe_price_id,
                'quantity' => 1,
            ]],
            'mode' => 'subscription',
            'success_url' => route('subscription.success') . '?session_id={CHECKOUT_SESSION_ID}&product_id=' . $subscription->id,
            'cancel_url' => route('subscription.cancel'),
        ]);

        return redirect($session->url);
    }

    public function paymentSuccess(Request $request) {

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

        $sessionId = $request->get('session_id');

        try {

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

            if (!$session) {
                throw new NotFoundHttpException;
            }

            $user = Auth::user();

            // Solo si el carrito tenía cursos con status_id = 1 (en carrito)
            $courses = $user->courses()->wherePivot('status_id', 1)->get();

            if ($courses->isEmpty()) {
                return redirect()->route('myCartPage')->with('error', 'No courses found in your cart.');
            }

            // Creamos el recibo
            $receipt = Receipt::create([
                'payment_method' => 'card',
                'session_id' => $session->id,
                'created_at' => now(),
            ]);

            // Actualizamos cada curso como comprado
            foreach ($courses as $course) {
                UserCourse::where('user_id', $user->id)
                    ->where('course_id', $course->id)
                    ->update([
                        'status_id' => 2, // comprado
                        'receipt_id' => $receipt->id,
                        'price_paid' => $course->price,
                        'updated_at' => now(),
                    ]);
            }

            return redirect()->to(url('/receipts/' . $receipt->id . '/details'))->with('success', 'Payment successful! Courses added to your profile');

        } catch (\Exception $e) {

            return redirect()->route('myCartPage')->with('error', 'Something went wrong validating your payment.');
            
        }
    }

    public function subscriptionSuccess(Request $request) {

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

        $sessionId = $request->get('session_id');
        $productId = $request->get('product_id');

        try {

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

            $user = Auth::user();
            $product = SubscriptionProduct::findOrFail($productId);

            $receipt = Receipt::create([
                'payment_method' => 'card',
                'session_id' => $session->id,
                'created_at' => now(),
            ]);

            Subscription::create([
                'user_id' => $user->id,
                'subscription_product_id' => $product->id,
                'price_paid' => $product->price,
                'subscription_date' => now(),
                'receipt_id' => $receipt->id,
            ]);

            return redirect()->route('homePage')->with('success', 'Subscription successful! Welcome to ' . $product->name);

        } catch (\Exception $e) {

            return redirect()->route('subscription.cancel');

        }

    }

    public function paymentCancel() {
        return redirect()->route('myCartPage')->with('error', 'Payment cancelled');
    }

    public function subscriptionCancel() {
        return redirect()->route('homePage')->with('error', 'Subscription cancelled.');
    }

}
