<?php

namespace App\Http\Controllers\Website;

use App\Http\Controllers\Controller;
use App\Models\Currency;
use App\Models\Movie;
use App\Models\StripeSession;
use App\Models\Package;
use App\Models\TvShow;
use App\Repositories\Interfaces\Admin\PackageInterface;
use App\Repositories\Interfaces\Website\SubscriptionRepositoryInterface;
use Flasher\Toastr\Laravel\Facade\Toastr;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Illuminate\Http\RedirectResponse;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Routing\Redirector;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Http;
use Exception;
use Flasher\Toastr\Prime\Toastr as PrimeToastr;
use Illuminate\Contracts\View\Factory;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\Log;
use Stripe\Stripe;
use Stripe\Checkout\Session as StripeCheckout;

class SubscriptionController extends Controller
{
    protected $packageRepo;
    protected $subscriptionRepository;

    public function __construct(PackageInterface $packageRepo, SubscriptionRepositoryInterface $subscriptionRepository)
    {
        $this->packageRepo = $packageRepo;
        $this->subscriptionRepository = $subscriptionRepository;
    }


    public function packages(Request $request)
    {
        $page_data['annually_packages'] = Package::where('status', 1)->where('type', 'annually')->get();
        $page_data['monthly_packages'] = Package::where('status', 1)->where('type', 'monthly')->get();
        if($request->token) {
            $page_data['token'] = $request->token;
            $page_data['payment_type'] = $request->payment_type;
            if($request->payment_type == 'rental') {
                $page_data['video_type'] = $request->video_type;
                if ($request->video_type == 'movie') {
                    $page_data['package_details'] = Movie::where('id', $request->video_id)->first();
                } else {
                    $page_data['package_details'] = TvShow::where('id', $request->video_id)->first();
                }
                
            } else {
                $page_data['package_details'] = Package::where('id', $request->package_id)->first();
            }

            $page_data['trx_id'] = uniqid();

            return view('website.payment.mobile_view', $page_data);
        } else {
            $page_data['token'] = null;
        }

        return view('website.payment.packages', $page_data);
    }

    public function offlineClaim(Request $request)
    {
         if (isDemoMode()) {
           return back()->with('error_message', 'This action is disabled in demo mode.');
        }
        try {
            $trx_id = $request->transaction_key;
            if (!$trx_id) {
                return redirect()->back()->with('error_message', __('transaction_key_missing'));
            }
            if ($request->payment_type == 'rental') {
                $plan = $this->subscriptionRepository->rentVideo($request->all(), 'offline');

                if($plan && isset($request->request_type)) {
                    return redirect()->route('home');
                }
                if ($plan) {
                    return redirect()->back()->with('success_message', __('video_rented_wait_for_admin_approval'));
                } else {
                    return redirect()->back()->with('error_message', __('video_rented_failed'));
                }
            } else {
                $plan   = $this->packageRepo->find($request->plan_id);
                $data = $this->subscriptionRepository->create($plan, $trx_id, '', $request, true);
                if($data && isset($request->request_type)) {
                    return redirect()->route('home');
                }
                if ($data) {
                    return redirect()->route('user.dashboard')->with('success_message', __('purchased_successfully_wait_for_admin_approval'));
                } else {
                    return redirect()->route('user.dashboard')->with('error_message', __('purchased_failed'));
                }
            }
        } catch (\Exception $e) {
            return redirect()->route('user.dashboard')->with('error_message', __('purchase_failed'));
        }
    }

    public function payment_gateway_list($id, $payment_type = null, $video_type = null)
    {
        if ($payment_type == 'rental') {
            if ($video_type == 'movie') {
                $page_data['package_details'] = Movie::where('id', $id)->first();
            } else {
                $page_data['package_details'] = TvShow::where('id', $id)->first();
            }
            $page_data['video_type'] = $video_type;
        } else {
            $page_data['package_details'] = Package::where('id', $id)->first();
        }
        $page_data['trx_id'] = uniqid();
        $page_data['payment_type'] = $payment_type;
        return view('website.payment.gateway_list', $page_data);
    }

    public function stripeRedirect(Request $request)
    {
        if (isDemoMode()) {
           return back()->with('error_message', 'This action is disabled in demo mode.');
        }
        try {

            if (@$request->payment_type == 'rental') {

                if ($request->video_type == 'movie') {
                    $video = Movie::where('id', $request->video_id)->first();
                } else {
                    $video = TvShow::where('id', $request->video_id)->first();
                }

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

                if (!$client->stripe_customer_id) {
                    $this->createStripeCustomer($client);
                }
                // 2. Save billing log (optional)
                $this->billingData($request);

                // 3. Create Stripe checkout session
                Stripe::setApiKey(setting('stripe_secret'));

                $checkoutSession = StripeCheckout::create([
                    'customer' => $client->stripe_customer_id,
                    'payment_method_types' => ['card'],
                    'line_items' => [[
                        'price_data' => [
                            'currency' => 'usd',
                            'product_data' => [
                                'name' => 'Video Rental (ID: ' . $request->video_id . ')',
                            ],
                            'unit_amount' => intval($video->rental_price * 100), // Stripe requires amount in cents
                        ],
                        'quantity' => 1,
                    ]],
                    'mode' => 'payment',
                    'success_url' => route('client.stripe.payment.success', [
                        'session_id' => '{CHECKOUT_SESSION_ID}',
                        'payment_type' => $request->payment_type,
                        'trx_id'     => $request->trx_id,
                        'video_id'   => $request->video_id,
                        'video_type' => $request->video_type,
                    ]),
                    'cancel_url' => url()->previous(),
                ]);

                return redirect($checkoutSession->url);
            } else {

                $package        = $this->packageRepo->find($request->package_id);
                $client         = auth()->user()->client;
                if (!$client->stripe_customer_id) {
                    $this->createStripeCustomer($client);
                }
                
                $plan_id  = $this->packageRepo->getPGCredential($request->package_id, 'stripe');

                if (!$plan_id) {
                    return redirect()->route('packages')->with('error_message', __('package_credentials_not_found'));
                }
                // Stripe::setApiKey(setting('stripe_secret'));
                $stripe_session = StripeSession::create([
                    'plan_id'   => $package->id,
                    'client_id' => $client->id,
                ]);
                $this->billingData($request);

                $session        = [
                    'customer'             => $client->stripe_customer_id,
                    'payment_method_types' => ['card'],
                    'line_items'           => [
                        [
                            'price'    => $plan_id,
                            'quantity' => 1,
                        ],
                    ],
                    'mode'                 => 'subscription',
                    'success_url'          => route('client.stripe.payment.success', ['session_id' => $stripe_session->id, 'trx_id' => $request->trx_id]),
                    'cancel_url'           => url()->previous(),
                ];
                $headers        = [
                    'Authorization' => 'Basic ' . base64_encode(setting('stripe_secret') . ':'),
                    'Content-Type'  => 'application/x-www-form-urlencoded',
                ];
                $response       = httpRequest('https://api.stripe.com/v1/checkout/sessions', $session, $headers, true);

                if (isset($response['error']) && isset($response['error']['message'])) {

                    return redirect()->back()->with('error_message', $response['error']['message']);
                }
                $stripe_session->update(['stripe_session_id' => $response['id']]);

                return redirect($response['url']);
            }
        } catch (\Exception $e) {
            Log::error('stripeRedirect', ['error' => $e->getMessage()]);
            return redirect()->back()->with('error_message', $e->getMessage());
        }
    }

    public function stripeSuccess(Request $request): Redirector|RedirectResponse|Application
    {
        try {

            if (@$request->payment_type == 'rental') {
                $session = $request->session_id;
                if (! $session) {
                    return redirect()->back()->with('error_message', __('video_rented_failed'));
                }
                if ($request->video_type == 'movie') {
                    $video = Movie::where('id', $request->video_id)->first();
                    $route = 'movie.details';
                    $slug = $video->slug;
                } else {
                    $video = TvShow::where('id', $request->video_id)->first();
                    $route = 'series.details';
                    $slug = $video->slug;
                }

                $request['plan_id'] = $video->id;
                $rent = $this->subscriptionRepository->rentVideo($request->all(), 'stripe');

                if ($rent) {
                    return redirect()->route($route, ['slug' => $slug])->with('success_message', __('video_rented_successfully'));
                } else {
                    return redirect()->back()->with('error_message', __('video_rented_failed'));
                }
            } else {
                $session = StripeSession::find($request->session_id);
                if (! $session) {
                    Toastr::error('invalid_request');

                    return redirect()->route('packages');
                }
                $headers        = [
                    'Authorization' => 'Basic ' . base64_encode(setting('stripe_secret') . ':'),
                    'Content-Type'  => 'application/x-www-form-urlencoded',
                ];
                $stripe_session = httpRequest('https://api.stripe.com/v1/checkout/sessions/' . $session->stripe_session_id, [], $headers, false, 'GET');
                if (! $stripe_session) {
                    Toastr::error('invalid_request');

                    return redirect()->route('packages');
                }

                if ($stripe_session['payment_status'] != 'paid') {
                    Toastr::error('invalid_request');

                    return redirect()->route('packages');
                }

                $billingInfo    = session('billing_info');
                $package        = $session->plan;

                $this->subscriptionRepository->create($package, $request->trx_id, $stripe_session, $billingInfo);
                return redirect()->route('user.dashboard')->with('success_message', __('purchased_successfully'));
            }
        } catch (\Exception $e) {
            Toastr::error($e->getMessage());
            return redirect()->route('packages')->with('error_message', $e->getMessage());
        }
    }

    public function paddleRedirect(Request $request): View|Factory|Application|RedirectResponse
    {
 if (isDemoMode()) {
           return back()->with('error_message', 'This action is disabled in demo mode.');
        }
        try {
            $this->billingData($request);
            $data = [
                'plan'     => $this->packageRepo->find($request->package_id),
                'price_id' => $this->packageRepo->getPGCredential($request->package_id, 'paddle'),
                'trx_id'   => $request->trx_id,
                'client'   => auth()->user()->client,
            ];
            return view('website.payment.paddle', $data);   
        } catch (\Exception $e) {
            return redirect()->back()->with('error_message', __('something_went_wrong_please_try_again'));
        }
    }

    public function paddleSuccess(Request $request): JsonResponse
    {
        try {
            $payment_details                = $request->data;
            $package                        = $this->packageRepo->find($request->plan_id);
            if (getArrayValue('status', $payment_details) != 'completed') {
                Toastr::error('invalid_request');

                return response()->json([
                    'error' => 'invalid_request',
                    'route' => route('client.available.plans'),
                ]);
            }
            $client                         = auth()->user()->client;

            if (getArrayValue('id', $payment_details['customer']) && ! $client->paddle_customer_id) {
                $client->update(['paddle_customer_id' => getArrayValue('id', $payment_details['customer'])]);
            }

            $payment_data['id']             = getArrayValue('id', $payment_details);
            $payment_data['transaction_id'] = getArrayValue('transaction_id', $payment_details);
            $billingInfo                    = session('billing_info');
            $this->subscriptionRepository->create($package, $request->trx_id, $payment_data, $billingInfo, false, 'paddle');
            Toastr::success('purchased_successfully');

            return response()->json([
                'error' => 'invalid_request',
                'route' => route('client.dashboard'),
            ]);
        } catch (\Exception $e) {
            Toastr::error($e->getMessage());
            logError('paddleSuccess: ', $e);

            return response()->json([
                'error' => 'invalid_request',
                'route' => route('client.available.plans'),
            ]);
        }
    }

    public function createStripeCustomer($client)
    {
        $data     = [
            'name'     => $client->name,
            'email'    => $client->email,
            'metadata' => $client,
        ];
        $headers  = [
            'Authorization' => 'Basic ' . base64_encode(setting('stripe_secret') . ':'),
            'Content-Type'  => 'application/x-www-form-urlencoded',
        ];
        $response = httpRequest('https://api.stripe.com/v1/customers', $data, $headers, true);
        return $client->update(['stripe_customer_id' => $response['id']]);
    }

    private function billingData($request): array
    {
        $billingInfo = [
            'billing_name'          => $request->billing_name,
            'billing_email'         => $request->billing_email,
            'billing_address'       => $request->billing_address,
            'billing_city'          => $request->billing_city,
            'billing_state'         => $request->billing_state,
            'billing_zipcode'       => $request->billing_zipcode,
            'billing_country'       => $request->billing_country,
            'country_selector_code' => $request->country_selector_code,
            'billing_phone'         => $request->billing_phone,
            'full_number'           => $request->full_number,
            'plan_id'               => $request->plan_id,
            'trx_id'                => $request->trx_id,
        ];
        Session::put('billing_info', $billingInfo);

        return $billingInfo;
    }

    public function paypalRedirect(Request $request): Redirector|RedirectResponse|Application
    {
         if (isDemoMode()) {
           return back()->with('error_message', 'This action is disabled in demo mode.');
        }
        try {
            if (@$request->payment_type == 'rental') {
                // Single Payment for Rental (Movie or Series)
                if ($request->video_type === 'movie') {
                    $video = Movie::find($request->video_id);
                } else {
                    $video = TvShow::find($request->video_id);
                }

                if (!$video) {
                    return back()->with('error', 'Video not found');
                }

                $amount = $video->rental_price ?? 1; // fallback to $1 if not set

                $base_url = setting('is_paypal_sandbox_mode_activated')
                    ? 'https://api-m.sandbox.paypal.com'
                    : 'https://api-m.paypal.com';

                $headers = [
                    'Content-Type'  => 'application/json',
                    'Authorization' => $this->paypalTokenGenerator($base_url),
                ];

                $order_data = [
                    'intent' => 'CAPTURE',
                    'purchase_units' => [[
                        'reference_id' => 'VIDEO-' . $request->video_id,
                        'description' => 'Rental Payment for ' . ($video->title ?? 'Video'),
                        'amount' => [
                            'currency_code' => 'USD',
                            'value' => number_format($amount, 2, '.', ''),
                        ],
                    ]],
                    'application_context' => [
                        'brand_name'          => setting('system_name'),
                        'locale'              => 'en-US',
                        'return_url'          => route('client.paypal.payment.success', [
                            'trx_id' => $request->trx_id,
                            'video_id' => $request->video_id,
                            'video_type' => $request->video_type,
                        ]),
                        'cancel_url'          => url()->previous(),
                        'user_action'         => 'PAY_NOW',
                    ],
                ];

                $response = httpRequest($base_url . '/v2/checkout/orders', $order_data, $headers);

                if (isset($response['links'])) {
                    $approvalLink = collect($response['links'])->firstWhere('rel', 'approve')['href'] ?? null;
                    if ($approvalLink) {
                        return redirect($approvalLink);
                    }
                }

                return back()->with('error', 'Unable to create PayPal order.');
            }

            // Subscription Payment (Default)
            $base_url = setting('is_paypal_sandbox_mode_activated')
                ? 'https://api-m.sandbox.paypal.com'
                : 'https://api-m.paypal.com';

            $plan_id = $this->packageRepo->getPGCredential($request->package_id, 'paypal');

            if (!$plan_id) {
                return redirect()->route('packages')->with('error_message', __('paypal_plan_id_not_found'));
            }

            $headers = [
                'Content-Type'  => 'application/json',
                'Authorization' => $this->paypalTokenGenerator($base_url),
            ];

            $this->billingData($request);

            $subscription_data = [
                'plan_id'             => $plan_id,
                'custom_id'           => $request->package_id,
                'application_context' => [
                    'brand_name'          => setting('system_name'),
                    'locale'              => 'en-US',
                    'shipping_preference' => 'SET_PROVIDED_ADDRESS',
                    'user_action'         => 'SUBSCRIBE_NOW',
                    'payment_method'      => [
                        'payer_selected'  => 'PAYPAL',
                        'payee_preferred' => 'IMMEDIATE_PAYMENT_REQUIRED',
                    ],
                    'return_url'          => route('client.paypal.payment.success', ['trx_id' => $request->trx_id]),
                    'cancel_url'          => url()->previous(),
                ],
            ];

            $response = httpRequest($base_url . '/v1/billing/subscriptions', $subscription_data, $headers);

            return redirect($response['links'][0]['href']);
        } catch (Exception) {
            return redirect()->back()->with('error_message', __('something_went_wrong_please_try_again'));
        }
    }


    public function paypalSuccess(Request $request): RedirectResponse
    {
        try {
            if (setting('is_paypal_sandbox_mode_activated')) {
                $base_url = 'https://api-m.sandbox.paypal.com';
            } else {
                $base_url = 'https://api-m.paypal.com';
            }
            $headers     = [
                'Content-Type'  => 'application/json',
                'Authorization' => $this->paypalTokenGenerator($base_url),
            ];
            $response    = httpRequest($base_url . '/v1/billing/subscriptions/' . $request->subscription_id, [], $headers, false, 'GET');
            $package     = $this->packageRepo->find(getArrayValue('custom_id', $response));
            if (! $package) {
                Toastr::error('invalid_request');

                return redirect()->route('packages');
            }
            $billingInfo = session('billing_info');
            $this->subscriptionRepository->create($package, $request->trx_id, $response, $billingInfo, false, 'paypal');
            Toastr::success('purchased_successfully');

            return redirect()->route('client.dashboard')->with('success_message', __('purchased_successfully'));
        } catch (\Exception $e) {
            Toastr::error('something_went_wrong_please_try_again');

            return redirect()->route('packages')->with('error_message', __('something_went_wrong_please_try_again'));
        }
    }

    public function paypalTokenGenerator($base_url): string
    {

        // generate access token
        $headers  = [
            'Content-Type'  => 'application/x-www-form-urlencoded',
            'Authorization' => 'Basic ' . base64_encode(setting('paypal_client_id') . ':' . setting('paypal_client_secret')),
        ];
        $data     = [
            'grant_type' => 'client_credentials',
        ];
        $response = httpRequest($base_url . '/v1/oauth2/token', $data, $headers, true);

        return $response['token_type'] . ' ' . $response['access_token'];
    }

    public function razorPayRedirect(Request $request)
    {
         if (isDemoMode()) {
           return back()->with('error_message', 'This action is disabled in demo mode.');
        }
        try {

            $image = setting('light_logo') && @is_file_exists(setting('light_logo')['original_image'])
                ? get_media(setting('light_logo')['original_image'])
                : getFileLink('80x80', []);

            $this->billingData($request);
            $plan             = $this->packageRepo->find($request->plan_id);

            $subscriptionData = [
                'plan_id'         => $this->packageRepo->getPGCredential($request->plan_id, 'razor_pay'),
                'customer_notify' => 1,
                'total_count'     => 12,
            ];

            $response         = Http::withBasicAuth(setting('razor_pay_key'), setting('razor_pay_secret'))
                ->withHeaders(['Content-Type' => 'application/json'])
                ->post('https://api.razorpay.com/v1/subscriptions', $subscriptionData)
                ->json();

            // Check for error in the response
            if (isset($response['error'])) {
                
                return redirect()->back()->with('error_message', __('an_error_occurred'));
            }

            // Prepare data for successful response
            $data             = [
                'key'             => setting('razor_pay_key'),
                'success'         => true,
                'name'            => setting('system_name'),
                'description'     => $plan->name,
                'image'           => $image,
                'subscription_id' => $response['id'],
                'callback_url'    => route('client.razor.pay.payment.success'),
                'prefill'         => [
                    'name'    => auth()->user()->name,
                    'email'   => auth()->user()->email,
                    'contact' => auth()->user()->phone,
                ],
                'notes'           => [
                    'address' => 'Subscribed to plan ' . $plan->name,
                ],
                'theme'           => [
                    'color' => setting('primary_color'),
                ],
            ];

            return response()->json($data);
        } catch (Exception) {
           return redirect()->back()->with('error_message', __('something_went_wrong_please_try_again'));
        }
    }

    public function razorPaySuccess(Request $request): RedirectResponse
    {
        try {
            $subscription_id = $request->razorpay_subscription_id;
            $response        = Http::withBasicAuth(setting('razor_pay_key'), setting('razor_pay_secret'))->withHeaders([
                'Content-Type' => 'application/json',
            ])->get("https://api.razorpay.com/v1/subscriptions/$subscription_id")->json();
            $payment_details = $response;
            $billingInfo     = session('billing_info');
            $package         = $this->packageRepo->find($billingInfo['plan_id']);
            if (! in_array($payment_details['status'], ['created', 'active'])) {
                Toastr::error('invalid_request');

                return redirect()->back();
            }
            $this->subscriptionRepository->create($package, $billingInfo['trx_id'], $payment_details, $billingInfo, false, 'razor_pay');
            session()->forget('billing_info');
            Toastr::success('purchased_successfully');

            return redirect()->route('client.dashboard');
        } catch (Exception $e) {
            Toastr::error($e->getMessage());

            return redirect()->back();
        }
    }

    public function mercadopagoRedirect(Request $request): Redirector|RedirectResponse|Application|null
    {
        if (isDemoMode()) {
            return redirect()->back()->with('danger', __('this_function_is_disabled_in_demo_server'));
        }
        try {
            $this->billingData($request);
            $plan               = $this->packageRepo->find($request->plan_id);
            $data['amount']     = $plan->price;
            $active_currency    = $this->activeCurrencyCheck();
            $brazilianCurrency  = $this->getCurrency('BRL');
            // Check if Brazilian currency is set
            if (empty($brazilianCurrency)) {
                return redirect()->back()->with('danger', __('please_set_brazilian_currency'));
            }

            $currency_converter = $this->currencyAmountCalculator(null, $data, $active_currency, $brazilianCurrency);
            $payload            = [
                'auto_recurring' => [
                    'frequency'          => 1,
                    'frequency_type'     => 'months',
                    'transaction_amount' => round($currency_converter['total_amount'], 2),
                    'currency_id'        => 'BRL',
                ],
                'back_url'       => url()->previous(),
                'reason'         => 'Yoga classes',
            ];

            $headers            = [
                'Authorization' => 'Bearer ' . setting('mercadopago_access_key'),
                'Content-Type'  => 'application/json',
            ];

            $response           = httpRequest('https://api.mercadopago.com/checkout/preferences', $payload, $headers);

            // Check if response is successful
            if (isset($response['error'])) {
                $errorMessage = $response['error']['message'] ?? $response['message'];

                return redirect()->back()->with('error_message', $errorMessage);
            }

            $url                = $response['init_point'] ?? null;

            if (! $url) {
                return redirect()->back()->with('error_message', __('something_went_wrong_please_try_again'));
            }

            return redirect($url);
        } catch (Exception $e) {
            return redirect()->back()->with('error_message', $e->getMessage());
        }
    }

    public function activeCurrencyCheck()
    {
        $currency = Currency::where('id', setting('default_currency'))->first();
        return $currency->currency;
    }

    public function getCurrency($currency_code = 'BDT')
    {
        $currency = Currency::where('currency', $currency_code)->first();
        return $currency->currency;
    }

    public function currencyAmountCalculator($orders, $data, $active_currency, $currency): array
    {
        $amount = $orders && count($orders) > 0 ? $orders->sum('total_amount') : $data['amount'];
        $rate   = $amount / $active_currency->exchange_rate;

        if (arrayCheck('type', $data) && $data['type'] == 'wallet') {
            if ($active_currency->code != $currency->code) {
                $total_amount = round($rate * $currency->exchange_rate);
                $db_amount    = $rate;
            } else {
                $total_amount = $amount;
                $db_amount    = $amount / $currency->exchange_rate;
            }
        } else {
            if ($active_currency->code != $currency->code) {
                $total_amount = $rate * $currency->exchange_rate;
                $db_amount    = $rate;
            } else {
                $total_amount = $amount * $currency->exchange_rate;
                $db_amount    = $amount / $currency->exchange_rate;
            }
        }

        return [
            'db_amount'    => $db_amount,
            'total_amount' => $total_amount,
        ];
    }

    public function mercadopagoSuccess(Request $request): RedirectResponse
    {
        try {
            $subscription_id = $request->subscription_id;
            $headers         = [
                'Authorization' => 'Bearer ' . setting('mercadopago_access_key'),
                'Content-Type'  => 'application/json',
            ];
            $response        = httpRequest("https://api.mercadopago.com/preapproval_plan/$subscription_id", [], $headers, false, 'GET');
            $payment_details = $response;
            $billingInfo     = session('billing_info');
            $package         = $this->packageRepo->find($billingInfo['plan_id']);
            if (! in_array($payment_details['status'], ['authorized', 'active'])) {
                return redirect()->back()->with('danger', __('invalid_request'));
            }
            $this->subscriptionRepository->create($package, $billingInfo['trx_id'], $payment_details, $billingInfo, false, 'razor_pay');
            session()->forget('billing_info');
            return redirect()->route('client.dashboard')->with('success_message', __('purchased_successfully'));
        } catch (Exception $e) {
            return redirect()->back()->with('error_message', $e->getMessage());
        }
    }

    public function cancelSubscription($id)
    {
        try {
            $this->subscriptionRepository->cancelSubscription($id);

            $data = [
                'status'    => 'success',
                'message'   => __('cancelled_successfully'),
                'title'     => __('success'),
                'is_reload' => true,
            ];
            return redirect()->back()->with('success_message', __('cancelled_successfully'));
        } catch (\Exception $e) {

            $data = [
                'status'    => 'danger',
                'message'   => __('something_went_wrong_please_try_again'),
                'title'     => __('error'),
                'is_reload' => false,
            ];

            return redirect()->back()->with('error_message', __('something_went_wrong_please_try_again'));
        }
    }
}
