<?php

namespace App\Http\Controllers;

use App\Models\Package;
use App\Models\Subscription;
use App\Models\Transaction;
use App\Models\User;
// use App\Trait\NotificationTrait;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Stripe\Customer;
use Stripe\EphemeralKey;
use Stripe\Exception\ApiErrorException;
use Stripe\PaymentIntent;
use Stripe\SetupIntent;
use Stripe\Stripe;
use Stripe\StripeClient;
use Yajra\DataTables\Facades\DataTables;

class SubscriptionController extends Controller
{
    // use NotificationTrait;

    function buySubscription()
    {
        $packages = Package::where('is_active', 1)->get();
        return view('pages.subscription.BuySubscription', compact('packages'));
    }


    public function index()
    {
        if (request()->ajax()) {
            $subscriptions = Subscription::whereHas('user')
                ->with([
                    'plan',
                    'user' => function ($q) {
                        $q->select('id', 'full_name');
                    }
                ])
                ->latest();
            return DataTables::of($subscriptions)
                ->addIndexColumn()
                ->make(true);
        }
        return view('subscription.SubscriptionIndex');
    }





    public function createSetupIntent(Request $request)
    {
        Stripe::setApiKey(env('STRIPE_SECRET'));

        $user = auth()->user();

        // Create Stripe customer if not exist
        if (!$user->customer_stripe_id) {
            $customer = \Stripe\Customer::create([
                'email' => $user->email,
            ]);
            $user->customer_stripe_id = $customer->id;
            $user->save();
        }

        $setupIntent = SetupIntent::create([
            'customer' => $user->customer_stripe_id,
            'payment_method_types' => ['card'],
        ]);

        return response()->json([
            'client_secret' => $setupIntent->client_secret,
        ]);
    }
    public function cardSaved(Request $request)
    {
        Stripe::setApiKey(env('STRIPE_SECRET'));
        $packageId = $request->query('package_id');
        $setupIntentId = $request->query('setup_intent');
        Log::info($setupIntentId);

        if (!$setupIntentId) {
            return redirect()->back()->with('error', 'Setup Intent ID is missing.');
        }
        DB::beginTransaction(); // Begin DB transaction
        try {
            $setupIntent = SetupIntent::retrieve($setupIntentId);

            if ($setupIntent->status !== 'succeeded') {
                return redirect()->back()->with('error', 'Setup Intent did not succeed.');
            }
            $paymentMethodId = $setupIntent->payment_method;
            $customerId = $setupIntent->customer;
            $package = Package::findOrFail($packageId);
            $user = auth()->user();
            $paymentIntent = PaymentIntent::create([
                'amount' => $package->price * 100,
                'currency' => 'usd',
                'customer' => $customerId,
                'payment_method' => $paymentMethodId,
                'off_session' => true,
                'confirm' => true,
                'metadata' => [
                    'package_id' => $package->id,
                    'user_id' => $user->id,
                ]
            ]);
            // Create Subscription
            $startDate = Carbon::now();
            $endDate = $startDate->copy()->addMonth();
            $subscription = Subscription::create([
                'user_id' => $user->id,
                'package_id' => $package->id,
                'start_date' => $startDate,
                'end_date' => $endDate,
                'is_active' => 1,
            ]);
            // Create Transaction
            $transaction = Transaction::create([
                'user_id' => $user->id,
                'subscription_id' => $subscription->id,
                'amount' => $package->price,
                'payment_method' => 'card',
                'status' => 'paid',
                'transaction_reference' => $paymentIntent->id,
            ]);
            // Notify Admins
            // $userIds = User::where('user_role', 'admin')->pluck('id')->toArray();
            // $this->sendNotification(
            //     $userIds,
            //     'Subscription Purchased',
            //     'A new subscription has been purchased successfully.',
            //     $transaction,
            //     'subscription'
            // );
            DB::commit(); // Commit transaction
            return redirect()->route('dashboard')->with('success', 'Subscription and payment completed successfully.');
        } catch (ApiErrorException $e) {
            DB::rollBack();
            return redirect()->back()->with('error', 'Stripe error: ' . $e->getMessage());
        } catch (\Exception $e) {
            DB::rollBack();
            return redirect()->back()->with('error', 'Something went wrong: ' . $e->getMessage());
        }
    }

    // public function cardSaved(Request $request)
    // {
    //     Stripe::setApiKey(env('STRIPE_SECRET'));
    //     $packageId = $request->query('package_id');
    //     $setupIntentId = $request->query('setup_intent');
    //     if (!$setupIntentId) {
    //         return redirect()->back()->with('error', 'Setup Intent ID is missing.');
    //     }
    //     try {
    //         $setupIntent = SetupIntent::retrieve($setupIntentId);
    //         if ($setupIntent->status !== 'succeeded') {
    //             return redirect()->back()->with('error', 'Setup Intent did not succeed.');
    //         }
    //         $paymentMethodId = $setupIntent->payment_method;
    //         $customerId = $setupIntent->customer;
    //         $package = Package::findOrFail($packageId);
    //         $user = auth()->user();
    //         $paymentIntent = PaymentIntent::create([
    //             'amount' => $package->price * 100, // in cents
    //             'currency' => 'usd',
    //             'customer' => $customerId,
    //             'payment_method' => $paymentMethodId,
    //             'off_session' => true,
    //             'confirm' => true,
    //             'metadata' => [
    //                 'package_id' => $package->id,
    //                 'user_id' => $user->id,
    //             ]
    //         ]);
    //         // 4. Create Subscription Record
    //         $startDate = Carbon::now();
    //         $endDate = $startDate->copy()->addMonth(); // adjust for your billing cycle
    //         $subscription = Subscription::create([
    //             'user_id' => $user->id,
    //             'package_id' => $package->id,
    //             'start_date' => $startDate,
    //             'end_date' => $endDate,
    //             'is_active' => 1,
    //         ]);
    //         // 5. Create Transaction Record
    //        $transaction = Transaction::create([
    //             'user_id' => $user->id,
    //             'subscription_id' => $subscription->id,
    //             'amount' => $package->price,
    //             'payment_method' => 'card',
    //             'status' => 'paid',
    //             'transaction_reference' => $paymentIntent->id,
    //         ]);
    //         $userIds = User::where('user_role', 'admin')->pluck('id')->toArray();
    //         $this->sendNotification(
    //             $userIds,
    //             'Subscription Purchased',
    //             'A new subscription has been purchased successfully.',
    //             $transaction,
    //             'subscription'
    //         );

    //         // 6. Redirect with success
    //         return redirect()->route('home')->with('success', 'Subscription and payment completed successfully.');

    //     } catch (ApiErrorException $e) {
    //         return redirect()->back()->with('error', 'Stripe error: ' . $e->getMessage());
    //     } catch (\Exception $e) {
    //         return redirect()->back()->with('error', 'Something went wrong: ' . $e->getMessage());
    //     }
    // }

}
