<?php

namespace App\Http\Controllers\Api;

use App\Models\User;
use App\Models\Banner;
use App\Models\Product;
use App\Models\Country;
use App\Models\State;
use App\Models\City;
use App\Models\TempUser;
use App\Models\UserAddress;
use App\Models\OrderDetails;
use App\Models\Orders;
use App\Models\PaymentDetails;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Session;
use DB;
use Illuminate\Support\Str;
use Carbon\Carbon; 
use Mail;
use Auth;

class IndexController extends Controller
{
    
    public function register_send_otp(Request $request)
    {
        // dd($request->all());
        // Check if user already exists
        $checkUser = User::where('email', $request->email)->first();
        if ($checkUser) {
            return [
                'status' => 'failed',
                'message' => 'Email Already Exist!!',
            ];
        }
        \Log::info($checkUser. ' - First');
        // dd($checkUser);
        $checkUser = User::where('phone', $request->phone)->first();
        if ($checkUser) {
            return [
                'status' => 'failed',
                'message' => 'Phone Already Exist!!',
            ];
        }
    
        date_default_timezone_set('Asia/Kolkata');
        $otp = rand(1000, 9999);
        $prefix = 'AMD';
    
        // Check if a temporary user already exists
        $checktempuser = TempUser::where('phone', $request->phone)->where('email', $request->email)->first();
        if ($checktempuser) {
            $checktempuser->delete();
        }
        // dd($checktempuser);
        // Create a new temporary user
        $user = TempUser::create([
            'name'     => $request->name,
            'email'    => $request->email,
            'phone'    => $request->phone,
            'password' => Hash::make($request->password),
        ]);
        \Log::info($user. ' - Second');
        // dd($user);
        $data['token'] = $user->createToken($user->email ?? $user->phone)->plainTextToken;
        $data['user'] = $user;
        // dd($data);
        if ($user->phone || $user->email) {
            $phone = $user->phone;
            $message = $otp;
            $type = 'register_otp';
            
            $response = otp_send($phone, $message, $type);
                
            \Log::info($response);
            
            $user->update([
                'verification_code' => $otp,
                'user_unique_id' => $prefix . str_pad($user->id, 6, '0', STR_PAD_LEFT),
            ]);
            $data['verification_code'] = $otp;
                
            // dd($response);
            // if ($response === true) {
                
            // }
    
            
            $userdata = [
                'email' => $user->email,
                'otp' => $otp,
            ];
            
            try{
                Mail::send('email.otp', $userdata, function($message)use($userdata) {
                    $message->to($userdata['email'])
                        ->from('noreplywebbitech@gmail.com', 'noreplay')
                    ->subject('Verification code');
                });
                
            }
            catch(\Exception $e){
                \Log::info($e);
                // dd($e);
            }
            
            return response()->json([
                'status' => 'success',
                'message'=> 'OTP sent successfully.',
                'data' => $data
            ]);
    
        }
        
        return response()->json([
            'status' => 'failed',
            'message'=> 'OTP sent failed.'
        ]);
    
        // return [
        //     'status' => 'failed',
        //     'message' => 'OTP send failed.',
        // ];
    }
    
    public function verification_code(Request $request)
    {
        
        $verifyuser = TempUser::where('id',$request->user_id)->where('verification_code',$request->verification_code)->first();

        if ($verifyuser)
        {
            date_default_timezone_set('Asia/Kolkata');
            $prefix = 'AMD';
            
            $user               = new User();
            $user->name         = $verifyuser->name;
            $user->email        = $verifyuser->email;
            $user->phone        = $verifyuser->phone;
            $user->password     = $verifyuser->password;
            $user->user_type    = "user";
            $user->status       = "active";
            $user->email_verified_at = Carbon::now();
            $user->save();
            
            $user->uni_number = $prefix . str_pad($user->id, 6, '0', STR_PAD_LEFT);
            $user->save();
            
            $tempUser = TempUser::where('id',$request->user_id)->first();
            $tempUser->delete();
            
            return $this->loginSuccess($user);
        }
        else
        {
            return response()->json([
                'status' => 'failed',
                'message'=> 'Verification code does not match!!'
            ]);
        }

    }
    
    public function resend_code(Request $request) 
    {
        $user = TempUser::where('id', $request->user_id)->first();
          
        if($user)
        {
            $otp        = rand(1000,9999);
            $phone      = $user->phone_number;
            $email      = $user->email;
            $message    = $otp;
            $type       = "forget_password";
            
            $response   = otp_send($phone, $message, $type);
            
            if ($response === true) {
                $user->verification_code = $otp;
                $user->save();
            } else {
                $user->verification_code = $otp;
                $user->save();
            }
            
            $userdata = [
                'email' => $user->email,
                'otp' => $otp,
            ];
            try{
                Mail::send('email.otp', $userdata, function($message)use($userdata) {
                    $message->to($userdata['email'])
                        ->from('noreplywebbitech@gmail.com', 'noreplay')
                    ->subject('Verification code');
                });
            }
            catch(\Exception $e){
                dd($e);
            }
                    
            return response()->json(['success' => 'OTP resent successfully', 'user' => $user]);
        }
        else
        {
            return response()->json(['result' => false, 'message' => 'User not found', 'user' => null]);
        }
        
    }

    public function login(Request $request)
    {
        
        $user = User::whereIn('user_type', ['user'])
                ->where('email', $request->email)
                ->orWhere('phone', $request->email)
                ->first();
    
        if ($user != null) {
            if (Hash::check($request->password, $user->password)) {
                return $this->loginSuccess($user);
            }
            else
            {
                return response()->json(['result' => false, 'message' => 'Unauthorized', 'user' => null]);
            }
        }
        else
        {
            return response()->json(['result' => false, 'message' => 'User not found', 'user' => null]);
        }
        
    }

    protected function loginSuccess($user)
    {
        $token = $user->createToken('API Token')->plainTextToken;
        return response()->json([
            'result' => true,
            'message' => 'Successfully logged in',
            'access_token' => $token,
            'token_type' => 'Bearer',
            'expires_at' => null,
            'user' => [
                'id' => $user->id,
                'type' => $user->user_type,
                'name' => $user->name,
                'email' => $user->email,
                'phone' => $user->phone
            ]
        ]);
    }

    public function getbannerImage()
    {
        $banner_images = Banner::where('status', 'active')->get();
        // dd($banner_images);
        
        if($banner_images->isNotEmpty()) {
            $data = [];
            
            foreach ($banner_images as $banner) {
                $data[] = [
                    'image' => $banner->image ? url('public/banner/' . $banner->image) : ''
                ];
            }
            // dd($data);
            return response()->json([
                'result' => true,
                'data' => $data
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => 'No data'
            ]);
        }
    }

    public function get_product()
    {
        $product = Product::where('status', 'active')->latest()->take(3)->get();
        // dd($product);

        $baseImageUrl = url('public/product');
        
        if($product->isNotEmpty()) {
            $data = [];
            
            foreach ($product as $banner) {
                if ($banner->image) {
                    $banner->image = $baseImageUrl . '/' . $banner->image;
                }
                else
                {
                    $banner->image = $baseImageUrl . '/dummy_product.png';
                }
                $image_decode = json_decode($banner->multiple_image);
                if ($image_decode) {
                    foreach ($image_decode as $key => $value) {
                        $image_details[] = $baseImageUrl . '/' . $value;
                    }
                    $banner->multiple_image =  $image_details;
                }

            }
            return response()->json([
                'result' => true,
                'data' => $product
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => 'No data'
            ]);
        }
    }
    
    public function get_all_product()
    {
        $product = Product::where('status', 'active')->latest()->get();
        // dd($product);

        $baseImageUrl = url('public/product');
        
        if($product->isNotEmpty()) {
            $data = [];
            
            foreach ($product as $banner) {
                if ($banner->image) {
                    $banner->image = $baseImageUrl . '/' . $banner->image;
                }
                else
                {
                    $banner->image = $baseImageUrl . '/dummy_product.png';
                }
                $image_decode = json_decode($banner->multiple_image);
                if ($image_decode) {
                    foreach ($image_decode as $key => $value) {
                        if($value)
                        {
                            $image_details[] = $baseImageUrl . '/' . $value;
                        }
                        else
                        {
                            $image_details[] = $baseImageUrl . '/dummy_product.png';
                        }
                    }
                    $banner->multiple_image =  $image_details;
                }

            }
            return response()->json([
                'result' => true,
                'data' => $product
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => 'No data'
            ]);
        }
    }
    
    public function forget_password(Request $request)
    {
        // dd($request->phone_or_email);
        
        if (filter_var($request->phone_or_email, FILTER_VALIDATE_EMAIL)) {
            $user = User::where('email', $request->phone_or_email)->first();
        }
        else
        {
            $user = User::where('phone', $request->phone_or_email)->first();
        }
        
        if($user)
        {
            $token = Str::random(64);
            
            DB::table('password_resets')->insert([
                  'email' => $user->email, 
                  'token' => $token, 
                  'created_at' => Carbon::now()
            ]);
            
            // $app_url = 'myapp://reset-password/'. $token;
            
            
            try
            {
                Mail::send('email.forgetPassword', ['token' => $token], function($message) use($user){
                      $message->to($user->email);
                      $message->subject('Reset Password');
                });
            
            }
            catch(\Exception $e){
                return response()->json([
                    'result' => false,
                    'message' => 'Mail Not Sent'
                ]);
            }
            
            return response()->json([
                'result' => true,
                'message' => 'Please check your email'
            ]);
        }
        else
        {
            return response()->json([
                'result' => false,
                'message' => 'User not found'
            ]);
        }
        

    }
    
    public function productdetails(Request $request)
    {
        $productId = $request->product_id;
        $product = Product::find($productId);
        // dd($product);
        if ($product) {
            
            $baseImageUrl = url('public/product');
            
            $image_decode = json_decode($product->multiple_image);
            if ($image_decode) {
                foreach ($image_decode as $key => $value) {
                    $image_details[] = $baseImageUrl . '/' . $value;
                }
                // $banner->multiple_image =  $image_details;
            }
            
            $cart_quantity = 1;
            $cart = Session::get('cart', []);
            
            if (isset($cart[$productId])) {
                $cart_quantity = $cart[$productId]['quantity'];
                // dd($cart[$productId]['quantity']);
            }
            
            $productDetails = [
                'product_id'            => $productId,
                'category_id'           => $product->category_id,
                'name'                  => $product->name,
                'include_product'       => $product->include_product,
                'thumbnail_image'       => url('public/product').'/'.$product->product_img,
                'multiple_image'        => $image_details,
                'description'           => $product->description,
                'original_amount'       => $product->original_amount,
                'discount_amount'       => $product->discount_amount,
                'cart_quantity'         => $cart_quantity,
                'status'                => $product->status,
            ];
            
            return response()->json([
                'result' => true,
                'product_details' => $productDetails
            ]);
        }
        else
        {
            return response()->json([
                'result' => false,
                'message' => 'Product not found'
            ]);
        }
    }
    
    // Cart Section
    public function addToCart(Request $request)
    {
        $productId = $request->product_id;
        $product = Product::findOrFail($productId);
        
        $cart = Session::get('cart', []);
        // dd($cart);
        
        if(isset($cart))
        {
            foreach($cart as $key => $value)
            {
                if($value['product_type'] == $product->product_type)
                {
                    
                }
                else
                {
                    if($value['product_type'] == "discount")
                    {
                        $type_name = "Discount";
                    }
                    else
                    {
                        $type_name = "Business Plan";
                    }
                    return response()->json([
                        
                        'message' => 'Only Add '. $type_name.' Product',
                    ]);
                }
            }
        }
        
        if(isset($cart))
        {
            foreach($cart as $key => $value1)
            {
                if($value1['product_type'] == $product->product_type)
                {
                    if($product->product_type == "discount")
                    {
                        
                    }
                    else
                    {
                        return response()->json([
                            'message' => 'Business Plan Add Only One Product',
                        ]);
                    }
                }
                else
                {
                    return response()->json([
                        'message' => 'Business Plan Add Only One Product',
                    ]);
                }
            }
        }
        
        
        if (isset($cart[$productId])) {
            return response()->json([
                'message' => 'Product is already in cart',
            ]);
        }
        else {
            
            $cart[$productId] = [
                'product_id' => $productId,
                'name' => $product->name,
                'thumbnail_image' => url('public/product').'/'.$product->image,
                'original_amount' => $product->original_amount,
                'discount_amount' => $product->discount_amount,
                'product_type'    => $product->product_type,
                'include_content'    => $product->include_product,
                'quantity' => 1,
            ];
        }
    
        Session::put('cart', $cart);
    
        return response()->json([
            'message' => 'Product added to cart successfully',
            'cart' => $cart
        ]);
        
    }
    
    public function removeFromCart(Request $request)
    {
        $productId = $request->product_id;
        
        $cart = Session::get('cart', []);
    
        if (isset($cart[$productId])) {
            unset($cart[$productId]);
    
            Session::put('cart', $cart);
    
            return response()->json([
                'message' => 'Product removed from cart successfully',
                'cart' => $cart
            ]);
        } else {
            return response()->json([
                'message' => 'Product not found in cart',
            ]);
        }
    }
    
    public function getCartCount()
    {
        $cart = Session::get('cart', []);
        
        $cartCount = count($cart);
        
        return response()->json([
            'cart_count' => $cartCount
        ]);
    }
    
    public function getCart()
    {
        $cart = Session::get('cart', []);
        $cartDetails = [];
    
        foreach ($cart as $productId => $item) {
            $product = Product::find($productId);
    
            if ($product) {
                $cartDetails[] = [
                    'product_id' => $productId,
                    'name' => $product->name,
                    'thumbnail_image' => url('public/product').'/'.$product->image,
                    'original_amount' => $product->original_amount,
                    'discount_amount' => $product->discount_amount,
                    'product_type'    => $product->product_type,
                    'include_content'    => $product->include_product,
                    'quantity' => $item['quantity'],
                ];
            } else {
                
            }
        }
    
        return response()->json([
            'cart' => $cartDetails
        ]);
    }
    
    public function CartUpdate(Request $request)
    {
        $productId = $request->product_id;
        $status    = $request->action;
        // dd($status);
        $product = Product::findOrFail($productId);
        
        $cart = Session::get('cart', []);

        if ($status == "plus") {
            if (isset($cart[$productId])) {
                $cart[$productId]['quantity'] = $cart[$productId]['quantity'] + 1;
                session()->put('cart', $cart);
                return response()->json(['result' => true, 'message' => 'Product Quantity Updated']);
            }
        }
        elseif($status == "minus")
        {
            if (isset($cart[$productId])) {
                $cart[$productId]['quantity'] = $cart[$productId]['quantity'] - 1;
                session()->put('cart', $cart);
                return response()->json(['result' => true, 'message' => 'Product Quantity Updated']);
            }
        }
        else
        {
            return response()->json(['result' => false, 'message' => 'Something Wrong']);
        }
        
        
    }
    
    public function getCountry(Request $request)
    {
        $country = Country::all();
        return response()->json([
            'countries' => $country
        ]);
    }
    
    
    public function getStates(Request $request)
    {
        $states = State::where('country_id', 101)->get();
        return response()->json([
            'states' => $states
        ]);
    }


    public function getCities(Request $request)
    {
        $cities = City::where('state_id', $request->state_id)->get();
        return response()->json([
            'cities' => $cities
        ]);
    }
    
        
    public function InstaSuccess(Request $request)
    {
        
        $request_data = $request->all();
        $payment_id = $request_data['payment_id'];
        $payment_status = $request_data['payment_status'];
        $payment_request_id = $request_data['payment_request_id'];
        
        if ($payment_status == 'Credit') {
            
            $sess_user_id           = Session::get('user_id');
            $sess_discount_type     = Session::get('discount_type');
            $sess_discount_code     = Session::get('discount_code');
            $sess_address_id        = Session::get('address_id');
            $sess_payment_type      = Session::get('payment_type');
            
            $cart                         = Session::get('cart', []);
        
            if($cart)
            {
                $total_amount                 = total_cart_amount($cart);
                $discount                     = discount_calculate($total_amount['discount_amount'], $sess_discount_type);
                $address                      = UserAddress::where('user_id', $sess_user_id)->first();
                $check_user_id                = User::where('id', $sess_user_id)->first();
                // dd($address);
                $orders                        = new Orders();
                $orders->user_id               = $sess_user_id;
                $orders->total_original_amount = $total_amount['original_amount'];
                $orders->total_discount_amount = $total_amount['discount_amount'];
                $orders->discount_type         = $sess_discount_type;
                $orders->discount_percentage   = $discount['discount_per'];
                $orders->discount_amount       = $discount['discount'];
                $orders->status                = "pending";
                $orders->name                  = $address->name;
                $orders->email                 = $address->email;
                $orders->phone                 = $address->phone;
                $orders->address               = $address->address;
                $orders->city                  = $address->city;
                $orders->state                 = $address->state;
                $orders->country               = $address->country;
                $orders->pincode               = $address->pincode;
                $orders->landmark              = $address->landmark;
                $orders->payment_id            = $payment_id;
                $orders->payment_status        = $payment_status;
                $orders->payment_request_id    = $payment_request_id;
                
                if($orders->save())
                {
                    
                    $OrderSave = Orders::find($orders->id);
                    $OrderSave->order_id = '#'.str_pad($orders->id, 6, "0", STR_PAD_LEFT);
                    $OrderSave->save();
                    
                    if($cart)
                    {
                        foreach($cart as $key => $value)
                        {
                            $product = Product::findOrFail($value['product_id']);
                            
                            $order_details                  = new OrderDetails();
                            $order_details->order_id        = $orders->id;
                            $order_details->user_id         = $sess_user_id;
                            $order_details->product_id      = $value['product_id'];
                            $order_details->product_name    = $value['name'];
                            $order_details->thumbnail_image = $product->image;
                            $order_details->original_amount = $value['original_amount'];
                            $order_details->discount_amount = $value['discount_amount'];
                            $order_details->quantity        = $value['quantity'];
                            $order_details->save();
                            
                        }
                    }
                    
                    $order_details = Orders::with(['orderitems'])->where('id', $orders->id)->first();
        
                    $data['name'] = $order_details->name;
                    $data['email'] = $order_details->email;
                    $data['order_details'] = $order_details;
            
                    try{
                        Mail::send('email.order_details', $data, function($message)use($data) {
                            $message->to($data['email'], $data['name'])
                                ->from("noreplywebbitech@gmail.com", 'no-reply')
                            ->subject('Order Details from Amirdham');
                        });
                    }
                    catch(\Exception $e){
                        // dd($e);
                    }
                    
                    if($sess_discount_type == 2)
                    {
                        $code_1 = $sess_discount_code;
                        $user_details = User::where('uni_number', $sess_discount_code)->first();
                        
                        if($user_details)
                        {
                            $level_status = $user_details->level;
                            
                            if($level_status == 1 || $level_status == "")
                            {
                                // Main Admin Earn Payment
                                $level_percentage               = 5;
                                $user_amount                    = $total_amount['discount_amount'] * $level_percentage/100;
                                
                                $payment_details                = new PaymentDetails();
                                $payment_details->user_id       = $user_details->id;
                                $payment_details->order_id      = $orders->id;
                                $payment_details->refer_id      = $check_user_id->uni_number;
                                $payment_details->order_user_id = $sess_user_id;
                                $payment_details->total_amount  = $total_amount['discount_amount'];
                                $payment_details->discount      = $user_amount;
                                $payment_details->discount_per  = $level_percentage;
                                $payment_details->save();
                                
                                $wallet_amount = $user_details->wallet_amount;
                                if($wallet_amount)
                                {
                                    $user_wall = User::find($user_details->id);
                                    $user_wall->wallet_amount += $user_amount;
                                    $user_wall->level      = 1;
                                    $user_wall->save();
                                    
                                    $user_update             = User::find($sess_user_id);
                                    $user_update->level      = 2;
                                    $user_update->admin_id   = $sess_discount_code;
                                    $user_update->save();
                                }
                                else
                                {
                                    $user_wall = User::find($user_details->id);
                                    $user_wall->wallet_amount = $user_amount;
                                    $user_wall->level      = 1;
                                    $user_wall->save();
                                    
                                    $user_update             = User::find($sess_user_id);
                                    $user_update->level      = 2;
                                    $user_update->admin_id   = $sess_discount_code;
                                    $user_update->save();
                                }
                                
                            }
                            elseif($level_status == 2)
                            {
                                // Main Admin and 2 admin Earn Payment
                                $level_percentage1               = 5;
                                $user_amount1                    = $total_amount['discount_amount'] * $level_percentage1 /100;
                                
                                $payment_details1                = new PaymentDetails();
                                $payment_details1->user_id       = $user_details->id;
                                $payment_details1->order_id       = $orders->id;
                                $payment_details1->refer_id       = $check_user_id->uni_number;
                                $payment_details1->order_user_id = $sess_user_id;
                                $payment_details1->total_amount  = $total_amount['discount_amount'];
                                $payment_details1->discount      = $user_amount1;
                                $payment_details1->discount_per  = $level_percentage1;
                                $payment_details1->save();
                                
                                $wallet_amount1 = $user_details->wallet_amount;
                                if($wallet_amount1)
                                {
                                    $user_wall1 = User::find($user_details->id);
                                    $user_wall1->wallet_amount += $user_amount1;
                                    $user_wall1->save();
                                    
                                    $user_update1             = User::find($sess_user_id);
                                    $user_update1->level      = 3;
                                    $user_update1->admin_id   = $sess_discount_code;
                                    $user_update1->save();
                                }
                                else
                                {
                                    $user_wall1 = User::find($user_details->id);
                                    $user_wall1->wallet_amount = $user_amount1;
                                    $user_wall1->save();
                                    
                                    $user_update1             = User::find($sess_user_id);
                                    $user_update1->level      = 3;
                                    $user_update1->admin_id   = $sess_discount_code;
                                    $user_update1->save();
                                }
                                
                                $main_admin = User::where('uni_number', $user_details->admin_id)->first();
                                
                                if($main_admin)
                                {
                                    $level_percentage               = 5;
                                    $user_amount                    = $total_amount['discount_amount'] * $level_percentage/100;
                                    
                                    $payment_details                = new PaymentDetails();
                                    $payment_details->user_id       = $main_admin->id;
                                    $payment_details->order_id      = $orders->id;
                                    $payment_details->refer_id      = $check_user_id->uni_number;
                                    $payment_details->order_user_id = $sess_user_id;
                                    $payment_details->total_amount  = $total_amount['discount_amount'];
                                    $payment_details->discount      = $user_amount;
                                    $payment_details->discount_per  = $level_percentage;
                                    $payment_details->save();
                                    
                                    $wallet_amount = $main_admin->wallet_amount;
                                    if($wallet_amount)
                                    {
                                        $user_wall = User::find($main_admin->id);
                                        $user_wall->wallet_amount += $user_amount;
                                        $user_wall->save();
                                    }
                                    else
                                    {
                                        $user_wall = User::find($main_admin->id);
                                        $user_wall->wallet_amount = $user_amount;
                                        $user_wall->save();
                                    }
                                    
                                }
                                
                                
                                
                            }
                            elseif($level_status >= 3)
                            {
                                // Main Admin, 1 and 2 admin Earn Payment
                                
                                $level_percentage1               = 5;
                                $user_amount1                    = $total_amount['discount_amount'] * $level_percentage1 /100;
                                
                                $payment_details1                = new PaymentDetails();
                                $payment_details1->user_id       = $user_details->id;
                                $payment_details1->order_id       = $orders->id;
                                $payment_details1->refer_id       = $check_user_id->uni_number;
                                $payment_details1->order_user_id = $sess_user_id;
                                $payment_details1->total_amount  = $total_amount['discount_amount'];
                                $payment_details1->discount      = $user_amount1;
                                $payment_details1->discount_per  = $level_percentage1;
                                $payment_details1->save();
                                
                                $wallet_amount1 = $user_details->wallet_amount;
                                if($wallet_amount1)
                                {
                                    $user_wall1 = User::find($user_details->id);
                                    $user_wall1->wallet_amount += $user_amount1;
                                    $user_wall1->save();
                                    
                                    $user_update1             = User::find($sess_user_id);
                                    $user_update1->level      = $user_details->level + 1;
                                    $user_update1->admin_id   = $sess_discount_code;
                                    $user_update1->save();
                                }
                                else
                                {
                                    $user_wall1 = User::find($user_details->id);
                                    $user_wall1->wallet_amount = $user_amount1;
                                    $user_wall1->save();
                                    
                                    $user_update1             = User::find($sess_user_id);
                                    $user_update1->level      = $user_details->level + 1;
                                    $user_update1->admin_id   = $sess_discount_code;
                                    $user_update1->save();
                                }
                                
                                $sub_admin = User::where('uni_number', $user_details->admin_id)->first();
                                
                                if($sub_admin)
                                {
                                    $level_percentage               = 5;
                                    $user_amount                    = $total_amount['discount_amount'] * $level_percentage/100;
                                    
                                    $payment_details                = new PaymentDetails();
                                    $payment_details->user_id       = $sub_admin->id;
                                    $payment_details->order_id      = $orders->id;
                                    $payment_details->refer_id      = $check_user_id->uni_number;
                                    $payment_details->order_user_id = $sess_user_id;
                                    $payment_details->total_amount  = $total_amount['discount_amount'];
                                    $payment_details->discount      = $user_amount;
                                    $payment_details->discount_per  = $level_percentage;
                                    $payment_details->save();
                                    
                                    $wallet_amount = $sub_admin->wallet_amount;
                                    if($wallet_amount)
                                    {
                                        $user_wall = User::find($sub_admin->id);
                                        $user_wall->wallet_amount += $user_amount;
                                        $user_wall->save();
                                    }
                                    else
                                    {
                                        $user_wall = User::find($sub_admin->id);
                                        $user_wall->wallet_amount = $user_amount;
                                        $user_wall->save();
                                    }
                                    
                                    $main_admin = User::where('uni_number', $sub_admin->admin_id)->first();
                                    
                                    if($main_admin)
                                    {
                                        $level_percentage2               = 10;
                                        $user_amount2                    = $total_amount['discount_amount'] * $level_percentage2/100;
                                        
                                        $payment_details2                = new PaymentDetails();
                                        $payment_details2->user_id       = $main_admin->id;
                                        $payment_details2->order_id       = $orders->id;
                                        $payment_details2->refer_id       = $check_user_id->uni_number;
                                        $payment_details2->order_user_id = $sess_user_id;
                                        $payment_details2->total_amount  = $total_amount['discount_amount'];
                                        $payment_details2->discount      = $user_amount2;
                                        $payment_details2->discount_per  = $level_percentage2;
                                        $payment_details2->save();
                                        
                                        $wallet_amount2 = $main_admin->wallet_amount;
                                        if($wallet_amount2)
                                        {
                                            $user_wall2 = User::find($main_admin->id);
                                            $user_wall2->wallet_amount += $user_amount2;
                                            $user_wall2->save();
                                        }
                                        else
                                        {
                                            $user_wall2 = User::find($main_admin->id);
                                            $user_wall2->wallet_amount = $user_amount2;
                                            $user_wall2->save();
                                        }
                                        
                                    }
                                    
                                }
                                
                                
                                
                            }
                            else
                            {
                                $user_wall_1 = User::find($user_details->id);
                                $user_wall_1->level = 1;
                                $user_wall_1->save();
                            }
                            
                        }
                        else
                        {
                            $user_wall_1 = User::find($sess_user_id);
                            $user_wall_1->level = 1;
                            $user_wall_1->save();
                        }
                        
                    }
                    
                    
                    session()->put('user_id', "");
                    session()->put('discount_type', "");
                    session()->put('discount_code', "");
                    session()->put('address_id', "");
                    session()->put('payment_type', "");
                    session()->put('cart', []);
            
                    $data['order_id'] = $orders->id;
                    
                    return redirect()->route('front.payment.success');
                    // return response()->json(['result' => true, 'message' => $data], 200);
                    // return response()->json(['result' => true, 'message' => $data]);
                    
                }
                else
                {
                    return response()->json(['result' => false, 'message' => 'Something Wrong'], 401);
                }
            }
            else
            {
                return response()->json(['result' => false, 'message' => 'No Product Available in Cart'], 401);
            }
        }
        
    }
    
    
}
