<?php

namespace App\Http\Controllers\APIs\Customer_API;

use App\Http\Controllers\Controller;
use App\Models\CustomReferralCode;
use App\Models\Faq;
use App\Models\IamPrincipal;
use App\Models\SubscriptionProducts;
use App\Models\Subscriptions;
use App\Services\APIs\CustomerAPIs\RulesApiServices;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;


use Illuminate\Support\Facades\Validator;

use Illuminate\Support\Facades\Redirect;

class SubscriptionController extends Controller
{


    //created by; Hritik
    //On - 28th June ,2024
    //use - to get Data of User in Webview and show list of product
    public function mySubscription(Request $request)
    {
        try {
            $token = readHeaderToken();
        $getCustomToken = CustomReferralCode::where('is_active',1)->first();
            // $token = true;

            // dd($token, Session::get('vendorToken'));
            if ($token) {
                // $user_id = 104;
                $user_id = $token['sub'];

                $dateTime = now();
                $formattedDateTime = $dateTime->format('Y-m-d H:i:s');
                $isSubscribedUser = Subscriptions::where('iam_principal_xid', $user_id)
                    ->where('next_payment_date', '>=', $formattedDateTime)
                    ->first();

                $userData = IamPrincipal::where('id', $user_id)->first();

                // $request['iam_principal_id'] = $user_id;


                $products = SubscriptionProducts::where('is_active', '1')->get();

                if ($isSubscribedUser) {

                    return view("Admin.pages.subscriptions.my-subscription", compact('user_id', 'userData', 'isSubscribedUser', 'products'));
                }
                $productList = SubscriptionProducts::where('is_active', 1)->first();
                $faqs = Faq::where('faq_category_id',3)->where('is_active','1')->get(); //getting only subscription faqS

                return view('Admin.pages.subscriptions.list-of-products', compact('productList', 'userData','faqs','getCustomToken'));
            } else {
                return jsonResponseWithErrorMessageApi(__('auth.user_deleted'), 409);
            }

        } catch (\Exception $e) {
            Log::error("An error occurred in " . __METHOD__ . ": " . $e->getMessage(), ['exception' => $e]);

            return jsonResponseWithErrorMessage(__('auth.something_went_wrong'));
        }
    }


    //created by; Hritik
    //On - 28th June ,2024
    //use - to get Data of User in Webview and show list of product


    public function listOfProduct(Request $request)
    {
        try {
            $productList = SubscriptionProducts::where('is_active', 1)->first();

            return view('Admin.pages.subscriptions.list-of-products', compact('productList'));

        } catch (\Exception $e) {
            Log::error("An error occurred in " . __METHOD__ . ": " . $e->getMessage(), ['exception' => $e]);

            return jsonResponseWithErrorMessage(__('auth.something_went_wrong'));
        }
    }



    //created by; Hritik
    //On - 02th July ,2024
    //use - to Create Subscription Product & price for  Monthly

    public function createStripeProduct(Request $request)
    {


        try {

            DB::beginTransaction();

            $stripeSecret = (config('constants.subscription.stripe_secret_key'));


            // $stripeSecret = env('STRIPE_SECRET');
            $stripe = new \Stripe\StripeClient($stripeSecret);
            // dd($stripeSecret,$stripe,$request->all());

            $validator = $this->validateSubscriptionsproductForm($request);

            if ($validator->fails()) {
                $validationErrors = $validator->errors()->all();
                Log::error("Stripe subscriptions plan validation error: " . implode(", ", $validationErrors));
                return jsonResponseWithErrorMessageApi($validationErrors, 203);
            }

            $id = SubscriptionProducts::create([
                'product_name' => $request->product_name,
                'product_value' => $request->product_value,
                'product_details' => $request->product_details,
            ]);

            $productCreate = $stripe->products->create([
                'name' => $request->product_name,
            ]);

            $updateCreatedPlan = SubscriptionProducts::where('id', $id->id)->update([
                'stripe_product_id' => $productCreate->id
            ]);


            $totalPrice = $request->product_value;
            if ($totalPrice && $totalPrice != 0 && $totalPrice != null) {
                $productPrice1 = $stripe->prices->create([
                    'unit_amount' => $totalPrice * 100,
                    // amount entered by Admin (in cents)
                    'currency' => 'usd',
                    'recurring' => ['interval' => 'month'],
                    'product' => $productCreate->id,
                    'nickname' => 'Monthly Price',

                ]);

                $updateCreatedPlan = SubscriptionProducts::where('id', $id->id)->update([
                    'stripe_price_id' => $productPrice1->id
                ]);
            }

            DB::commit();
            return jsonResponseWithSuccessMessage(__('success.save_data'), 200);
        } catch (\Exception $ex) {
            DB::rollBack();
            Log::error('Favourite Restaurant service failed: ' . $ex->getMessage());
            return jsonResponseWithErrorMessageApi(__('auth.something_went_wrong'), 500);
        }




    }



    //update trial Period
    public function updateTrialPeriod(Request $request)
    {


        try {

            DB::beginTransaction();

            $stripeSecret = config('constants.subscription.stripe_secret_key');

            $validator = Validator::make(
                $request->all(),
                [

                    'stripe_id' => 'required',
                    'timestamp_to_update' => 'required',

                ]
            );

            if ($validator->fails()) {
                $validationErrors = $validator->errors()->all();
                Log::error("Stripe subscriptions plan validation error: " . implode(", ", $validationErrors));
                return jsonResponseWithErrorMessageApi($validationErrors, 203);
            }

            // $stripeSecret = env('STRIPE_SECRET');
            $stripe = new \Stripe\StripeClient($stripeSecret);
            // dd($stripeSecret,$stripe,$request->all());

            $stripeId = $request->stripe_id;
            $timestamp = $request->timestamp_to_update;


            $updateSubscription = $stripe->subscriptions->update(
                $stripeId,
                ['trial_end' => $timestamp] //8 RD aUG
            );
            //8 sept

            // 13th aug

            DB::commit();
            return jsonResponseWithSuccessMessage('success.save_data', $updateSubscription);
        } catch (\Exception $ex) {
            DB::rollBack();
            Log::error('Favourite Restaurant service failed: ' . $ex->getMessage());
            return jsonResponseWithErrorMessageApi(__('auth.something_went_wrong'), 500);
        }




    }


    public function validateSubscriptionsproductForm(Request $request)
    {
        return Validator::make(
            $request->all(),
            [

                'product_name' => 'required',
                'product_value' => 'required',
                'product_details' => 'required',
            ]
        );
    }



    //created by; Hritik
    //On - 02th July ,2024
    //use - to Create Subscription

    public function subscriptionToPlan(Request $request)
    {
  
        try {
            $isCustomReferralCodeApplied = 0;
            $customReferralCode =  CustomReferralCode::where('referral_code', $request->referral_code_to_check)->where('is_active',1)->first();

            if($customReferralCode && $customReferralCode->referral_code && 
            $customReferralCode->referral_code == $request->referral_code_to_check){
                $isCustomReferralCodeApplied = 1;
            }else{
                $isCustomReferralCodeApplied = 0;
            }
            $isReferralSubscription = 0;
            $referralUserId = $request->referral_user_id;
            if ($referralUserId && $referralUserId != null) {
                $isReferralSubscription = 1;
            } else {
                $isReferralSubscription = 0;
            }

            $userId = $request->user_id;
            $subscriptionProductXid = $request->subscription_product_xid;

            $stripeSecret = (config('constants.subscription.stripe_secret_key'));

            $stripe = new \Stripe\StripeClient($stripeSecret);
            //  $taxId = (config('services.stripe.tax_id'));

            $userData = IamPrincipal::where('id', $userId)->first();

            if ($userData) {

                $subscriptionPlan = SubscriptionProducts::where('id', $subscriptionProductXid)->first();


                if ($subscriptionPlan && $subscriptionPlan->stripe_price_id && $subscriptionPlan->stripe_price_id != null) {
                    $checkout = $stripe->checkout->sessions->create([
                        'customer_email' => $userData->email_address,
                        'line_items' => [
                            [
                                'price' => $subscriptionPlan->stripe_price_id,
                                'quantity' => 1,
                                // 'tax_rates'=>[$taxId],
                            ],
                        ],
                        'mode' => 'subscription',
                        // 'allow_promotion_codes' => true,
                        // 'tax_id_collection' => ['enabled' => true],
                        'metadata' => [
                            'userId' => $userData->id,
                            'userEmail' => $userData->email_address,
                            'subscriptionProductXid' => $subscriptionProductXid,

                            'is_referral_subscription' => $isReferralSubscription,
                            'referral_user_id' => $referralUserId,
                            'isCustomReferralCodeApplied'=> $isCustomReferralCodeApplied

                        ],
                        'success_url' => route('thankyou'),

                        // 'cancel_url' => "http://localhost/cheerstothe_season_2_o/my-subscription-page",
                    ]);

                    return Redirect::away($checkout->url);
                    //note:-for now i am just sending the cveonly=0 and lmacve=1 for reference .'&lmacve=1&cveonly=0'
                } else {
                    return redirect()->back()->with(['error' => "Something went wrong while subscription!"]);

                }

            }


        } catch (\Exception $e) {
            Log::error("An error occurred in " . __METHOD__ . ": " . $e->getMessage(), ['exception' => $e]);

            return jsonResponseWithErrorMessage(__('auth.something_went_wrong'));
            // return redirect()->back()->with(['error' => "Something went wrong while subscription!" . $e->getMessage()]);

        }

    }



    public function thankyou(Request $request)
    {

        return view('Admin.pages.subscriptions.thank-you');
    }

    //created by; Hritik
    //On - 28th May ,2024
    //use - To cancel the subscription of user on end of subscription end period

    public function cancelSubscription(Request $request)
    {
        try {
            DB::beginTransaction();
            $stripeSecret = (config('constants.subscription.stripe_secret_key'));
            //   $stripeSecret = env('STRIPE_SECRET');

            $stripe = new \Stripe\StripeClient($stripeSecret);
            $userId = $request->iam_principal_xid;

            // dd($request->all(),$stripeSecret);

            $getSubscriptionData = Subscriptions::where('iam_principal_xid', $userId)->where('subscription_status', 'active')->first();

            $subscriptionId = $getSubscriptionData->subscription_id;

            $cancelledSubscription = $stripe->subscriptions->update(
                $subscriptionId,
                ['cancel_at_period_end' => true]
            );

            $subscriptionFromDatabase = Subscriptions::where('subscription_id', $subscriptionId)->first();
            $subscriptionFromDatabase->cancelled_at = date('Y-m-d H:i:s', $cancelledSubscription->canceled_at);

            $subscriptionFromDatabase->subscription_status = $cancelledSubscription->status;
            $subscriptionFromDatabase->is_cancelled_subscription = 1;  //2 for cancelled
            $subscriptionFromDatabase->status = "cancelled";

            $subscriptionFromDatabase->save();


            $getSubscription = $stripe->subscriptions->retrieve($subscriptionFromDatabase->subscription_id, []);


            $getSubscribeCustomer = $stripe->customers->retrieve(
                $subscriptionFromDatabase->stripe_customer_id,
                []
            );


            DB::commit();
            return redirect()->route('cancel-subscription-thank-you');

        } catch (\Exception $e) {
            DB::rollBack();
            Log::error("An error occurred in " . __METHOD__ . ": " . $e->getMessage(), ['exception' => $e]);

            return redirect()->back()->with(['error' => "Something went wrong while cancelling subscription!" . $e->getMessage()]);
            // return jsonResponseWithErrorMessage(__('auth.something_went_wrong'), 500);
        }
    }
    /**
     * Created By : Hritik
     * Created at : 05 Jult 2024
     * Use : To get Cancel Subscription Success page.
     */



    public function cancelSubscriptionThankYou(Request $request)
    {


        return view('Admin.pages.subscriptions.cancel-thank-you');
    }

    /**
     * Created By : Hritik
     * Created at : 05 Jult 2024
     * Use : To Apply Referral Code and return the User Id.
     */




    public function applyReferralCode(Request $request)
    {
        try {

            $referralCode = $request->input('referral_code');
            $currentUserId = $request->input('current_iam_principal_xid');
            $code = IamPrincipal::where('referral_code', $referralCode)->where('id', '!=', $currentUserId)->where('principal_type_xid', 3)->first();
            $customCode = CustomReferralCode::where('is_active',1)->where('referral_code',$referralCode)->first();
            if ($code ) {
                return response()->json(['success' => true, 'message' => 'Successfully applied referral code!', 'referralUserId' => $code->id ,'referral_code'=>$referralCode]);
            } else if( $customCode) {
                return response()->json(['success' => true, 'message' => 'Successfully applied referral code!', 'referralUserId' => 2 ,'referral_code'=>$referralCode]); //2 is admin Id //need to change when principal typr_xid = 1
              
            }else{
                return response()->json(['success' => false, 'message' => 'Invalid referral code.']);
            }

        } catch (\Exception $e) {
            Log::error("An error occurred in " . __METHOD__ . ": " . $e->getMessage(), ['exception' => $e]);
            return jsonResponseWithErrorMessage(__('auth.something_went_wrong'));
        }
    }

}
