<?php
/*
Plugin Name: JShine Woocommerce Addons
Plugin URI:  https://github.com/kantsverma
Description: Used to Add the additional Tabs for Woocommerce My Account
Version:     0.1
Author:      kantsverma
Author URI:  http://kantsverma.com
*/


if ( ! defined( 'ABSPATH' ) ) {
	die( 'Access denied.' );
}

define( 'HSW_NAME', 'JShine Woocommerce Addons' );
define( 'HSW_REQUIRED_PHP_VERSION', '8.0' );                          // because of get_called_class()
define( 'HSW_REQUIRED_WP_VERSION',  '6.0' );                          // because of esc_textarea()

const VERSION    = '0.1';
const PREFIX     = 'hsw_';
const DEBUG_MODE = false;


use Razorpay\Api\Api;
use Razorpay\Api\Errors\SignatureVerificationError;	

/**
 * Checks if the system requirements are met
 *
 * @return bool True if system requirements are met, false if not
 */
function hsw_requirements_met() {
	global $wp_version;
	//require_once( ABSPATH . '/wp-admin/includes/plugin.php' );		// to get is_plugin_active() early

	if ( version_compare( PHP_VERSION, HSW_REQUIRED_PHP_VERSION, '<' ) ) {
		return false;
	}

	if ( version_compare( $wp_version, HSW_REQUIRED_WP_VERSION, '<' ) ) {
		return false;
	}

	/*
	if ( ! is_plugin_active( 'plugin-directory/plugin-file.php' ) ) {
		return false;
	}
	*/

	return true;
}

/**
 * Prints an error that the system requirements weren't met.
 */
function hsw_requirements_error() {
	global $wp_version;

	require_once( dirname( __FILE__ ) . '/views/requirements-error.php' );
}

/*
 * Check requirements and load main class
 * The main program needs to be in a separate file that only gets loaded if the plugin requirements are met. Otherwise older PHP installations could crash when trying to parse it.
 */
if ( hsw_requirements_met() ) {

	// require_once( __DIR__ . '/razorpay/Razorpay.php' );
	// require_once( __DIR__ . '/razorpay/src/Api.php' );
	// require_once( __DIR__ . '/razorpay/src/Errors/SignatureVerificationError.php' );
	


	/* ###################
	*  Author: Kantsverma
	*  Method: Used to add new tab in woocomerce my account section
	*  Date:  29-12-22
	* ###################*/

	// ------------------
	// STEP 1. Add new endpoint to use on the My Account page
	// IMPORTANT*: After uploading Permalinks needs to be rebuilt in order to avoid 404 error on the newly created endpoint
		
	function hsw_add_woo_tabs_endpoint() {
		add_rewrite_endpoint( 'my-plans', EP_ROOT | EP_PAGES );
		add_rewrite_endpoint( 'new-plans', EP_ROOT | EP_PAGES );
		add_rewrite_endpoint( 'reward-points', EP_ROOT | EP_PAGES );
	}
		
	add_action( 'init', 'hsw_add_woo_tabs_endpoint' );
		
		
	/* ###################
	*  Author: Kantsverma
	*  Method: Add new query var
	*  Date:  29-12-22
	* ###################*/
		
	function althemist_premium_support_query_vars( $vars ) {
		$vars[] = 'my-plans';
		$vars[] = 'new-plans';
		$vars[] = 'reward-points';
		return $vars;
	}
		
	add_filter( 'query_vars', 'althemist_premium_support_query_vars', 0 );
		
		
	/* ###################
	*  Author: Kantsverma
	*  Method: Insert the new endpoint into the My Account menu
	*  Date:  29-12-22
	* ###################*/
		
	function hsw_add_woo_tabs_link_my_account( $items ) {
		$items['my-plans'] = 'My Plans';
		$items['new-plans'] = 'Buy New Plan';
		$items['reward-points'] = 'Reward Points';
		return $items;
	}
		
	add_filter( 'woocommerce_account_menu_items', 'hsw_add_woo_tabs_link_my_account' );
		
		
	/* ###################
	*  Author: Kantsverma
	*  Method: Add content to the new endpoint
	*  Date:  29-12-22
	* ###################*/

		
	function hsw_my_plans_content() {
		global $wpdb;
		$bookingData = array();
		if ( is_user_logged_in() ) {
			$current_user = wp_get_current_user();
			$require = 'once';
			$default_template_path   = '';
			$template_path = WP_PLUGIN_DIR  . '/hs_woo_addon/views/my_plans.php';

			if($current_user->roles[0]  == 'administrator'){
				$template_content = '<h5 class="mb-4">My DHS Plans</h5> <p>No found any plan for admin.</p>';
			}else{
				$customerCode = $wpdb->get_var( "SELECT code FROM customer WHERE mobile =".$current_user->user_login);
							
				// check custome detail with old database
				if(!empty($customerCode)){
		
					//$this->render_template('test.php');
					//$variables = array('foo'=>'123','bar'=>'100');
					//echo "SELECT cb.code, cb.order_no, cb.bookfor_mobile, cb.scheme, cb.c_date, cb.total_amount, cb.net_amount, schemes.scheme_name, schemes.min_amount, schemes.max_months  FROM customer_booking as cb LEFT JOIN schemes as schemes on schemes.code = cb.scheme WHERE cb.customer_code=".$customerCode;

					//$customerBookings = $wpdb->get_results( "SELECT cb.code, cb.order_no, cb.bookfor_mobile, cb.scheme, cb.c_date, cb.total_amount, cb.net_amount, cb.payment_status, schemes.title, schemes.min_amount, schemes.max_months  FROM customer_booking as cb LEFT JOIN schemes as schemes on schemes.code = cb.scheme WHERE cb.customer_code=".$customerCode, OBJECT );

					$customerBookings = $wpdb->get_results( "SELECT cb.code, cb.order_no, cb.billing_name, cb.billing_email, cb.billing_mobile, cb.date, cb.scheme, cb.c_date, cb.total_amount, cb.net_amount, cb.payment_status, schemes.title, schemes.min_amount, schemes.max_months  FROM customer_booking as cb JOIN schemes as schemes on schemes.code = cb.scheme 
					LEFT JOIN consolidate_policy_used as used_p on used_p.policy_code = cb.code WHERE cb.customer_code=".$customerCode." AND cb.payment_status = 2 ORDER BY cb.code DESC", OBJECT );
					// echo '<pre>';
					// print_r($customerBookings);
					// echo '</pre>';

					if($wpdb->num_rows >0){
						foreach($customerBookings as $key=> $booking){
							$policyDetail = $wpdb->get_results( "SELECT * FROM consolidate_policy WHERE policy_code=".$booking->code, OBJECT );
							$bookingData[] = array(
								$key => $booking,
								'policy_'.$key => $policyDetail,
							);
						}
					}
					if ( is_file( $template_path ) ) {
						extract( $bookingData );
						ob_start();
						if ( 'always' == $require ) {
							require( $template_path );
						} else {
							require_once( $template_path );
						}
						$template_content = apply_filters( 'hsw_template_content', ob_get_clean(), $default_template_path, $template_path, $bookingData );
					} else {
						$template_content = '<h5 class="mb-4">My DHS Plans</h5> <p>Invalid view path.</p>';					
					}
				}else{
					$template_content = '<h5 class="mb-4">My DHS Plans</h5> <p>Invalid customer detail.</p>';					
				}
			}
		}else{
			$template_content = '<h5 class="mb-4">My DHS Plans</h5> <p>Not found any data.</p>';
		}
		do_action( 'hsw_render_template_post', $default_template_path, $bookingData, $template_path, $template_content );
		echo  $template_content;
	}
		
	add_action( 'woocommerce_account_my-plans_endpoint', 'hsw_my_plans_content' );
	// Note: add_action must follow 'woocommerce_account_{your-endpoint-slug}_endpoint' format

	/* ###################
	*  Author: Kantsverma
	*  Method: Add content to the new endpoint
	*  Date:  22-07-22
	* ###################*/

		
	function hsw_new_plans_content() {
		global $wpdb;
		$plans = array();
		if ( is_user_logged_in() ) {
			$current_user = wp_get_current_user();
			$require = 'once';
			$default_template_path   = '';
			$template_path = WP_PLUGIN_DIR  . '/hs_woo_addon/views/new_plans.php';

			if($current_user->roles[0]  == 'administrator'){
				$template_content = '<h5 class="mb-4">Buy New DHS Plan</h5> <p>No found any plan for admin.</p>';
			}else{
				$customerCode = $wpdb->get_var( "SELECT code FROM customer WHERE mobile =".$current_user->user_login);
				// check custome detail with old database
				if(!empty($customerCode)){
					$plans = $wpdb->get_results( "SELECT * FROM `schemes` WHERE `min_amount` >= 4000 AND `status` = 1 ORDER BY `min_amount` ASC", OBJECT );
					//$plans = $wpdb->get_results( "SELECT code, scheme_name, min_amount, max_months, payback, payback_p,  FROM schemes WHERE status ='1' and min_amount >= '4000' ORDER BY min_amount ASC", OBJECT );
					if($wpdb->num_rows >0){
						
					}					
					if ( is_file( $template_path ) ) {
						extract( $plans );
						ob_start();
						if ( 'always' == $require ) {
							require( $template_path );
						} else {
							require_once( $template_path );
						}
						$template_content = apply_filters( 'hsw_template_content', ob_get_clean(), $default_template_path, $template_path, $plans );
					} else {
						$template_content = '<h5 class="mb-4">My DHS Plans</h5> <p>Invalid view path.</p>';
					}
				}else{
					$template_content = '<h5 class="mb-4">Buy New DHS Plan</h5> <p>Invalid customer detail.</p>';					
				}
			}
		}else{
			$template_content = '<h5 class="mb-4">Buy New DHS Plan</h5> <p>Not found any data.</p>';
		}
		do_action( 'hsw_render_template_post', $default_template_path, $plans, $template_path, $template_content );
		echo  $template_content;
	}
		
	add_action( 'woocommerce_account_new-plans_endpoint', 'hsw_new_plans_content' );	
	/* ###################
	*  Author: Kantsverma
	*  Method: Add content to the new endpoint
	*  Date:  29-12-21
	* ###################*/

		
	function hsw_reward_points_content() {
		global $wpdb;
		$rewardPoints = array();
		if ( is_user_logged_in() ) {
			$current_user = wp_get_current_user();
			$require = 'once';
			$default_template_path   = '';
			$template_path = WP_PLUGIN_DIR  . '/hs_woo_addon/views/my_rewards.php';
			// echo '<pre>';
			// print_r($current_user->roles);
			// echo '</pre>';

			if($current_user->roles[0]  == 'administrator'){
				$template_content = '<h5 class="mb-4">Reward Points</h5> <p>Not found any reward points for admin.</p>';
			}else{
				$customerCode = $wpdb->get_var( "SELECT code FROM customer WHERE mobile =".$current_user->user_login);
				// check custome detail with old database
				if(!empty($customerCode)){
					$rewardPoints = $wpdb->get_results( "SELECT code, vno, date, userid, amt, type, remarks, status, created_at FROM pw_consolidate  WHERE userid=".$customerCode, OBJECT );
					
					if ( is_file( $template_path ) ) {
						extract( $rewardPoints );
						ob_start();
						if ( 'always' == $require ) {
							require( $template_path );
						} else {
							require_once( $template_path );
						}
						$template_content = apply_filters( 'hsw_template_content', ob_get_clean(), $default_template_path, $template_path, $rewardPoints );
					} else {
						$template_content = '<h5 class="mb-4">My DHS Plans</h5> <p>Invalid view path.</p>';
					}
				}else{
					$template_content = '<h5 class="mb-4">Reward Points</h5> <p>Invalid customer detail.</p>';
				}
			}
		}else{
			$template_content = '<h5 class="mb-4">Reward Points</h5> <p>Not found any data.</p>';			
		}
		do_action( 'hsw_render_template_post', $default_template_path, $rewardPoints, $template_path, $template_content );
		echo  $template_content;
	}
		
	add_action( 'woocommerce_account_reward-points_endpoint', 'hsw_reward_points_content' );

	/* ###################
	*  Author: Kantsverma
	*  Method: Used to remove the unwatned tabs from my account
	*  Date:  29-12-21
	* ###################*/

	function remove_account_tab( $items ) {
		unset( $items['downloads'] );
		return $items;
	}
	add_filter ( 'woocommerce_account_menu_items', 'remove_account_tab' );

	/* ###################
	*  Author: Kantsverma
	*  Method: Reorder account items.
	*  Date:  29-12-21
	* ###################*/

	function reorder_account_menu( $items ) {
		return array(
				'dashboard'          => __( 'Dashboard', 'woocommerce' ),
				'my-plans'           => __( 'My Plans', 'woocommerce' ),			
				'new-plans'          => __( 'Buy New Plan', 'woocommerce' ),			
				'reward-points'      => __( 'Reward Points', 'woocommerce' ),			
				'orders'             => __( 'Orders', 'woocommerce' ),
				'edit-account'       => __( 'Edit Account', 'woocommerce' ),
				'edit-address'       => __( 'Addresses', 'woocommerce' ),
				'customer-logout'    => __( 'Logout', 'woocommerce' ),
		);

	}
	add_filter ( 'woocommerce_account_menu_items', 'reorder_account_menu' );

	/* ###################
	*  Author: Kantsverma
	*  Method: Used generate thr Razorpay orderId 
	*  Date:  20-07-21
	* ###################*/

	add_action("wp_ajax_hsw_genrate_order_id" , "hsw_genrate_order_id");
	add_action("wp_ajax_nopriv_hsw_genrate_order_id" , "hsw_genrate_order_id");
	
	function hsw_genrate_order_id(){

		global $wpdb;
		$current_user = wp_get_current_user();		
		if(!empty($_POST['customerId'])){
			// generate orderId  RAZOR_KEY_ID
			$api = new Api(RAZOR_KEY_ID, RAZOR_KEY_SECRET);	
			$customer_data = array('Name'=> trim($_POST['customerName']),'CustomerId'=> $_POST['customerId'],'Mobile'=> trim($_POST['phone']),'Email'=> (!empty($_POST['email']) ? trim($_POST['email']) :''),'DhsNo'=> (!empty($_POST['dhsNo']) ? trim($_POST['dhsNo']) :''));
			$response =  $api->order->create(array('receipt' => rand(), 'amount' => (trim($_REQUEST['amount']) * 100), 'currency' => 'INR', 'notes'=> $customer_data));  
			if($response->id){
				echo $response->id; wp_die();				
			}else{
				return ''; wp_die();		
			}
		}
	}

	/* ###################
	*  Author: Kantsverma
	*  Method: Used ajax request to pay voucher amount
	*  Date:  13-07-21
	* ###################*/

	add_action("wp_ajax_hsw_ajax_pay_plan" , "hsw_ajax_pay_plan");
	add_action("wp_ajax_nopriv_hsw_ajax_pay_plan" , "hsw_ajax_pay_plan");
	
	function hsw_ajax_pay_plan(){
		global $wpdb;
		$current_user = wp_get_current_user();
		if(!empty($_POST['razorpay_payment_id'])){
			$policyData = $wpdb->get_row( "SELECT policy_code, policy_booklet_no, date FROM consolidate_policy WHERE policy_code =".$_POST['policyCode']);
			//$policyCode = $wpdb->get_var( "SELECT * FROM consolidate_policy WHERE policy_code =".$_POST['policyCode']);
			if(!empty($policyData->policy_code)){
				// check custome detail with old database
				$customer = $wpdb->get_row( "SELECT code, name, mobile FROM customer WHERE mobile =".$current_user->user_login);

				$bookingDetail = $wpdb->get_row( "SELECT code, order_no, customer_code, bookfor_mobile, bookfor_name, scheme FROM customer_booking WHERE code =".$policyData->policy_code);
				// get scheme data 
				$planData = $wpdb->get_row( "SELECT code, scheme_name, min_amount, max_months, payback, payback_p  FROM schemes WHERE code =".$bookingDetail->scheme);

				$getIns = $wpdb->get_var( "SELECT ins FROM consolidate_payment WHERE policy_code =".$policyData->policy_code." ORDER BY code DESC LIMIT 1");

				$ins = ($getIns >0 ? ($getIns + 1) :0);

				$pre_fix = 'R/'.date("my").'/'; 
				$receiptData = $wpdb->get_var( "SELECT MAX(receipt_number2) FROM consolidate_payment WHERE receipt_number LIKE '%".$pre_fix."%'");
                //echo json_encode($receiptData);die();
				$next = ($receiptData+1);
				
				$receiptNumber = $pre_fix.$next;
				// remarks_admin
				$paymentAdded = $wpdb->insert("consolidate_payment", array(
					'date'                  => date("Y-m-d"),
					'vno'                   => $policyData->policy_code,
					'policy_code'           => $policyData->policy_code,
					'remarks'               => 'Payment Received by Razorpay from Website',
					'remarks_admin'         => 'Online payment received against RN : '.$receiptNumber,
					'amt'                   => round($_POST['amount'],2),
					'receipt_number'        => $receiptNumber,
					'receipt_number2'       => $next,
					'admin_id'              => '1',
					'received_by'           => '1',
					'received_by_name'      => 'Razorpay',
					'paytm_transaction_no'  => trim($_POST['razorpay_payment_id']),
					'bank_transaction_no'   => trim($_POST['razorpay_payment_id']),
					'bank_name'             => 'Razorpay',
					'bank_t_type'           => 'Razorpay',
					'policy_booklet_no'     => $policyData->policy_booklet_no,
					'paid'                  => '1',
					'ins'                   => $ins,
					's_code'                => '0',
					'type'                  => '',
					'direct_sponser'        => '0',
					'rec_date'              => date("Y-m-d"),
					'reference'             => '0',
				));
				if($paymentAdded){
					//update consolidate policy detail for payment 
					$payementId = $wpdb->insert_id;
					$pupdate = $wpdb->update( 'consolidate_policy', 
						array( 
							'receipt_number' 		=> $receiptNumber,
							'paid' 			 		=> '1', 
							'received_by_name' 		=> 'Razorpay', 
							'policy_booklet_no' 	=> $policyData->policy_booklet_no, 
							'remarks_admin' 		=> 'Online payment received against RN : '.$receiptNumber, 
							'payment_id' 			=> $payementId,
							'rec_date' 				=> date("Y-m-d"), 
							'receipt_number2'       => $next,					
							'bank_name' 			=> 'Razorpay',
							'payment_amount' 		=> round($_POST['amount'],2),
							'bank_transaction_no' 	=> trim($_POST['razorpay_payment_id']),
							'paytm_transaction_no' 	=> trim($_POST['razorpay_payment_id']),
						), 
						array( 'code' => trim($_POST['policyId'])),
					);

					if($pupdate){
						$getPromotionalwalletlog = $wpdb->get_var( "SELECT level_paid FROM pw_paid_log WHERE policy_code =".$policyData->policy_code." ORDER BY code DESC LIMIT 1");
						if(!empty($getPromotionalwalletlog)){
							$next_level = ($getPromotionalwalletlog+1);
							$wpdb->insert("pw_paid_log", array(
								'policy_code'   => $policyData->policy_code,
								'level_paid'    => $next_level,
								'amt_paid'      => round($_POST['amount'],2)
							));
						}
						// add Scheme buyback 10% to customer wallet if its in scheme master
						$wallet_added = '';
						if($planData->payback_p >0){
							$buyback = round(($planData->payback_p * $planData->min_amount)/100,2);
							// add the promotional wallet to user account
							if($buyback>0){
								$payBackMsg = 'You received '.$planData->payback_p.' % of payback for payment of '.$planData->min_amount.' againts your DHS -'.$bookingDetail->order_no.'.';

								$wallet_added = $wpdb->insert("pw_consolidate", array(
									'date'   		=> date('Y-m-d'),
									'vno'   		=> $policyData->policy_code,
									'userid'    	=> $customer->code,
									'type'       	=> 'PW',
									'amt'       	=> $buyback,
									'status'     	=> '1',
									'remarks'    	=> $payBackMsg,
								));
							}    
						}
						//set sms to user after payment done 
						$getsmstemplate = $wpdb->get_row( "SELECT template_for, template, templateid, hints, sender_id FROM sms_template WHERE code ='11'");
											
						if(!empty($getsmstemplate->template)){
							$getsmstemplate->template = str_replace('[NAME]', ucwords($customer->name), $getsmstemplate->template);
							$getsmstemplate->template = str_replace('[PAYMENT_REC]', round($planData->min_amount,2), $getsmstemplate->template);
							$getsmstemplate->template = str_replace('[PAYMENT_RECEIPT_NO]', preg_replace('/\\\\/', '', $receiptNumber), $getsmstemplate->template);
							$getsmstemplate->template = str_replace('[P_POINTS]', getCustomerTotalRewardPoints($customer->code), $getsmstemplate->template);                                    
							$getsmstemplate->template = str_replace('[TOTAL_BOOKING_PAYMENT]', getPolicyTotalPayment($policyData->policy_code), $getsmstemplate->template);
							$getsmstemplate->template = str_replace('[BOOKING_NO]', preg_replace('/\\\\/', '', $policyData->policy_booklet_no), $getsmstemplate->template);
							
							sendSms($customer->code, $customer->mobile, $getsmstemplate->template, $getsmstemplate->templateid, $getsmstemplate->sender_id);
						}						
						$returndata = array(
							'status' 	=> 1,
							'message' 	=> 'Payment Received successfully, Receipt Number : '.$receiptNumber.' and detail send in sms on your registered mobile no.',
						);						
					}else{
						$returndata = array(
							'status' 	=> 0,
							'message' 	=> 'Payment done successfully your transaction no is '.$_REQUEST['razorpay_payment_id'].' but entry not updated please contact at  91-98 5588 7770 / contact@jshine.in.',
						);						
					}
				}else{
					//something gone wrong
					$returndata = array(
						'status' 	=> 0,
						'message' 	=> 'Payment done successfully your transaction no is '.$_REQUEST['razorpay_payment_id'].' but entry not updated please contact at  91-98 5588 7770 / contact@jshine.in.',
					);
				}
			}else{
				$returndata = array(
					'status' 	=> 0,
					'message' 	=> 'Payment done successfully your transaction no is '.$_REQUEST['razorpay_payment_id'].' but entry not updated please contact at  91-98 5588 7770 / contact@jshine.in.',
				);
			}
		}else{
			$returndata = array(
				'status' 	=> 0,
				'message' 	=> 'Your payment failed and transaction not updated in case of any deducation send transaction message or screenshots on  91-98 5588 7770 / contact@jshine.in',
			);
		}
		echo json_encode($returndata);
		wp_die();
	}

	/* ###################
	*  Author: Kantsverma
	*  Method: Used ajax request to pay voucher amount
	*  Date:  21-07-22
	* ###################*/

	add_action("wp_ajax_hsw_ajax_buy_new_plan" , "hsw_ajax_buy_new_plan");
	add_action("wp_ajax_nopriv_hsw_ajax_buy_new_plan" , "hsw_ajax_buy_new_plan");
	
	function hsw_ajax_buy_new_plan(){
		global $wpdb;
		$current_user = wp_get_current_user();		
		if(!empty($_POST['razorpay_payment_id'])){
			// check plan if exist
			$planData = $wpdb->get_row( "SELECT code, scheme_name, min_amount, max_months, payback, payback_p  FROM schemes WHERE code =".$_POST['schemeCode']);
			if(!empty($planData->code)){
				// check custome detail with old database
				$customer = $wpdb->get_row( "SELECT code, name, member_code, mobile, email, city, add_1, add_2, dob, pin_code, nominee, nominee_dob, nominee_relationship, nominee_contact_no, device_token, device_type, sale_employee_code, sale_employee_code_new  FROM customer WHERE mobile =".$current_user->user_login);
				if(!empty($customer->sale_employee_code_new)){
					$sales_emp_code = $customer->sale_employee_code_new;
				}elseif(!empty($customer->sale_employee_code)){
					$sales_emp_code =  $customer->sale_employee_code;
				}else{
					$sales_emp_code ='1';
				}
				// check last receipt no of month  $customer->sale_employee_code_new
				$dhs_prefix = 'DH/'.date("my").'/';
				$dhsData = $wpdb->get_var( "SELECT max(receipt_number2) FROM customer_booking WHERE order_no LIKE '%".$dhs_prefix."%' ORDER BY `code` DESC");
				$next_dhs_receipt_number = ((!empty($dhsData) ? $dhsData : 0) + 1);
				$dhs_no = $dhs_prefix.$next_dhs_receipt_number;
				// create Reciept no 
				$receipt_prefix = 'R/'.date("my").'/';
				// SELECT max(receipt_number2) FROM `consolidate_payment` WHERE `receipt_number` LIKE '%R/0722/%';
				$receiptData = $wpdb->get_var( "SELECT max(receipt_number2) FROM `consolidate_payment` WHERE `receipt_number` LIKE '%".$receipt_prefix."%'");
				$receipt_next = ($receiptData+1);
				$reciept_no = $receipt_prefix.$receipt_next;
				$customerId = $customer->code;
				// Inser the customer booking in database 
				$adminRemakrs = 'Initial/First Payment From Website';
				$customerBooking = $wpdb->insert("customer_booking", array(
					'customer_code'             => $customerId,
					'bookfor_mobile'            => (!empty($current_user->user_login) ? $current_user->user_login : $customer->mobile),
					'bookfor_name'              => (!empty($current_user->display_name) ? $current_user->display_name : $customer->name),
					'billing_name'              => (!empty($current_user->display_name) ? $current_user->display_name : $customer->name),
					'billing_email'             => (!empty($current_user->user_email) ? $current_user->user_email : $customer->email),
					'billing_mobile'            => (!empty($current_user->user_login) ? $current_user->user_login : $customer->mobile),
					'total_amount'              => trim($planData->min_amount),
					'net_amount'                => trim($planData->min_amount),
					'payment_type'              => 'Online',
					'payment_mode'              => 'Razorpay',
					'paytm_transaction_no'      => trim($_POST['razorpay_payment_id']),
					'bank_transaction_no'       => trim($_POST['razorpay_payment_id']),
					'scheme'                    => $planData->code,
					'payment_plan'              => $planData->code,
					'receipt_number2'           => $next_dhs_receipt_number,
					'sale_emp_code'             => $sales_emp_code,
					'sale_designation'          => '5',
					'c_admin_id'                => '1',
					'ip'                		=> getIPAddress(),
					'browser'                	=> getbrowserName($_SERVER['HTTP_USER_AGENT']),
					'ewallet_op'                => '1',
					'booking_created_from'      => 'Online',
					'pyment_pay'                => trim($planData->min_amount),
					'first_insallment'          => trim($planData->min_amount),
					'c_date'                    => date("Y-m-d"),
					'date_time_f'               => date("Y-m-d H:i:s"),
					'discount'                  => '0',
					'shiping'                   => '0',
					'shipping_date'             => date("Y-m-d"),
					'payment_option'            => '',
					'billing_country'           => '',
					'billing_state'             => '',
					'billing_city'              => '',
					'shipping_name'             => (!empty($current_user->display_name) ? $current_user->display_name : $customer->name),
					'shipping_mobile'           => (!empty($current_user->user_login) ? $current_user->user_login : $customer->mobile),
					'status'                    => '1',
					'admin_id'                  => '1',
					'sort_id'                   => '0',
					'client_id'                 => '0',
					'payment_remarks'           => $adminRemakrs,
					'order_no'                  => $dhs_no,
					'wc_no'                     => '',
					'book_status'               => '1',
					'delivery'                  => '0',
					'delivery_date'             => date("Y-m-d"),
					'product_code'              => $planData->scheme_name,
					'product_style_code'        => $planData->code,
					'payment_missed_consuctive' => '0',
					'last_payment_date'         => date("Y-m-d"),
					'approved_by'               => '1',
					'sponsor_code_policy'       => '0',
					'tax'                       => '0',
					'payment_status'            => '2',
				));

				if($customerBooking){
					$policyCode = $wpdb->insert_id;
					$consolidatepayment = $wpdb->insert("consolidate_payment", array(
						'remarks'              => 'Initial/First Payment From App',
						'policy_code'          => $policyCode,
						'receipt_number'       => $reciept_no,
						'receipt_number2'      => $receipt_next, // latest reciept no
						'ins'                  => '1',
						'paid'                 => '1',
						'amt'                  => round($planData->min_amount,2),
						'policy_booklet_no'    => $dhs_no,
						'type'                 => 'INS',
						'p_type'               => 'Auto Genrated',
						'payment_type'         => 'Online',
						'admin_id'             => '1',
						'remarks_admin'        => 'Payment received Online from Website '.trim($_POST['razorpay_payment_id']),
						'vno'                  => $policyCode,
						'received_by_name'     => 'Razorpay',
						'bank_name'     	   => 'Razorpay',
						'bank_transaction_no'  => trim($_POST['razorpay_payment_id']),
						'paytm_transaction_no' => trim($_POST['razorpay_payment_id']),
						'date'                 => date("Y-m-d"),
						'rec_date'             => date("Y-m-d"),
					));
					// add payment detail in consolidate payment table 
					if($consolidatepayment){
						$paymentId = $wpdb->insert_id;
						$consolidatepolicy = $wpdb->insert("consolidate_policy", array(
							'remarks'                   => 'Initial/First Payment From Website'.trim($_POST['razorpay_payment_id']),
							'vno'                       => $policyCode,
							'date'                      => date("Y-m-d",time()),
							'policy_code'               => $policyCode,
							'ins'                       => 1,
							'amt'                       => round($planData->min_amount,2),
							'policy_booklet_no'         => $dhs_no,
							'type'                      => 'INS',
							's_code'                    => '0',
							'paid'                      => '1',
							'direct_sponser'            => '0',
							'received_by'               => '1',
							'received_by_name'          => 'Razorpay',
							'remarks_admin'             => 'Payment received against RN : '.$reciept_no,
							'rec_date'                  => date("Y-m-d"),
							'receipt_number'            => $reciept_no,
							'receipt_number2'           => $receipt_next,
							'alert1'                    => '0',
							'alert2'                    => '0',
							'reference'                 => '0',
							'transfered_pay'            => '0',
							'used_for'                  => '0',
							'p_type'                    => 'Auto Genrated',
							'payment_type'              => 'Online',
							'bank_name'                 => 'Razorpay',
							'bank_transaction_no'       => trim($_POST['razorpay_payment_id']),
							'paytm_transaction_no'      => trim($_POST['razorpay_payment_id']),                               
							'payment_id'      			=> $paymentId,                                     
							'bank_t_type'      			=> 'Razorpay',                                    
						));
						// create all other installment for future date start
						if($planData->max_months >0 ){
							for ($months = 2;  $months <= $planData->max_months; $months++) {
								//echo '-->'.$months;
								$date = date('Y-m-10',strtotime("+ ".($months-1)." Months",strtotime(date("Y-m-d"))));
								$wpdb->insert("consolidate_policy", array(
									'remarks'                   => $months.' Month - Installment',
									'used_for_remarks'          => 'Used for '.($months).' Month Program',                                            
									'vno'                       => $policyCode,
									'date'                      => $date,
									'policy_code'               => $policyCode,
									'ins'                       => $months,
									'amt'                       => round($planData->min_amount,2),
									'policy_booklet_no'         => $dhs_no,
									'type'                      => 'INS',
									's_code'                    => '0',
									'paid'                      => '0',
									'direct_sponser'            => '0',
									'received_by'               => '1',
									'received_by_name'          => 'Online',
									'remarks_admin'             => '0',
									'receipt_number2'           => $receipt_next,
									'alert1'                    => '0',
									'alert2'                    => '0',
									'reference'                 => '0',
									'transfered_pay'            => '0',
									'used_for'                  => '0',
									'p_type'                    => 'Auto Gen',
									'payment_type'              => 'Online',
									'bank_name'                 => 'Razorpay',
								));
							}
						}
						// Add promotional offer buy paying online from App
						$percentage = (date("Y-m-d", strtotime("+ 1 day")) <= $customerBooking->date ? 5 : 2.5);
						$promotionalamount = round(( $percentage * $planData->min_amount)/100,2);
												
						$getPromotionalwalletlog = $wpdb->get_var( "SELECT level_paid FROM pw_paid_log WHERE policy_code =".$policyCode." ORDER BY code DESC LIMIT 1");
						if(!empty($getPromotionalwalletlog)){
							$next_level = ($getPromotionalwalletlog+1);
							$wpdb->insert("pw_paid_log", array(
								'policy_code'   => $policyCode,
								'level_paid'    => $next_level,
								'amt_paid'      => round($planData->min_amount,2)
							));
						}
						$walletMsg = 'Special Promotional Wallet of '.$percentage.' % received for Payment of '.$planData->min_amount.' through paying Jshine Website.';

						$wallet_added = $wpdb->insert("pw_consolidate", array(
							'date'       => date('Y-m-d'),
							'vno'        => $policyCode,
							'userid'     => $customerId,
							'type'       => 'PW',
							'amt'        => $promotionalamount,
							'status'     => '1',
							'remarks'    => $walletMsg,
						));				
						//set sms to user after payment done 
						$getsmstemplate = $wpdb->get_row( "SELECT template_for, template, templateid, hints, sender_id FROM sms_template WHERE code ='9'");
											
						if(!empty($getsmstemplate->template)){
							$getsmstemplate->template = str_replace('[NAME]', ucwords($customer->name), $getsmstemplate->template);
							$getsmstemplate->template = str_replace('[SCHEME_NAME]', $planData->scheme_name, $getsmstemplate->template);
							
							sendSms($customer->code, $customer->mobile, $getsmstemplate->template, $getsmstemplate->templateid, $getsmstemplate->sender_id);
						}						
					}
				}
				// end code here                                    
				$data = array(
					'dhs_no'        => preg_replace('/\\\\/', '', $dhs_no),
					'message'       => $getsmstemplate->template,
					//'wallet_amount'     => $promotionalamount,
					//'wallet_amount'     => $wallet_added,
				);
				$returndata = array(
					'status' 	=> 1,
					'message' 	=> 'Payment Received successfully, Receipt Number : '.$reciept_no.' and detail send in sms on your registered mobile no.',
				);
			}else{
				$returndata = array(
					'status' 	=> 0,
					'message' 	=> 'Payment done successfully your transaction no is '.$_REQUEST['razorpay_payment_id'].' but entry not updated please contact at  91-98 5588 7770 / contact@jshine.in.',
				);
			}
		}else{
			$returndata = array(
				'status' 	=> 0,
				'message' 	=> 'Your payment failed and transaction not updated in case of any deducation send transaction message or screenshots on  91-98 5588 7770 / contact@jshine.in',
			);
		}
		echo json_encode($returndata);
		wp_die();
	}

    /**
     * Function: getIPAddress() used to customer IP
     * Date:     23-07-22
     * Author:   kantsverma
     * @return \Illuminate\Http\Response
     */      
	function getIpAddress()
	{
		$ipAddress = '';
		if (! empty($_SERVER['HTTP_CLIENT_IP'])) {
			// to get shared ISP IP address
			$ipAddress = $_SERVER['HTTP_CLIENT_IP'];
		} else if (! empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
			// check for IPs passing through proxy servers
			// check if multiple IP addresses are set and take the first one
			$ipAddressList = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
			foreach ($ipAddressList as $ip) {
				if (! empty($ip)) {
					// if you prefer, you can check for valid IP address here
					$ipAddress = $ip;
					break;
				}
			}
		} else if (! empty($_SERVER['HTTP_X_FORWARDED'])) {
			$ipAddress = $_SERVER['HTTP_X_FORWARDED'];
		} else if (! empty($_SERVER['HTTP_X_CLUSTER_CLIENT_IP'])) {
			$ipAddress = $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'];
		} else if (! empty($_SERVER['HTTP_FORWARDED_FOR'])) {
			$ipAddress = $_SERVER['HTTP_FORWARDED_FOR'];
		} else if (! empty($_SERVER['HTTP_FORWARDED'])) {
			$ipAddress = $_SERVER['HTTP_FORWARDED'];
		} else if (! empty($_SERVER['REMOTE_ADDR'])) {
			$ipAddress = $_SERVER['REMOTE_ADDR'];
		}
		return $ipAddress;
	}
    /**
     * Function: getbrowserName() used to customer browser
     * Date:     23-07-22
     * Author:   kantsverma
     * @return \Illuminate\Http\Response
     */   	
	function getbrowserName($user_agent)
	{
			// Make case insensitive.
			$t = strtolower($user_agent);
	
			// If the string *starts* with the string, strpos returns 0 (i.e., FALSE). Do a ghetto hack and start with a space.
			// "[strpos()] may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE."
			//     http://php.net/manual/en/function.strpos.php
			$t = " " . $t;
	
			// Humans / Regular Users     
			if     (strpos($t, 'opera'     ) || strpos($t, 'opr/')     ) return 'Opera'            ;
			elseif (strpos($t, 'edge'      )                           ) return 'Edge'             ;
			elseif (strpos($t, 'chrome'    )                           ) return 'Chrome'           ;
			elseif (strpos($t, 'safari'    )                           ) return 'Safari'           ;
			elseif (strpos($t, 'firefox'   )                           ) return 'Firefox'          ;
			elseif (strpos($t, 'msie'      ) || strpos($t, 'trident/7')) return 'Internet Explorer';
	
			// Search Engines 
			elseif (strpos($t, 'google'    )                           ) return '[Bot] Googlebot'   ;
			elseif (strpos($t, 'bing'      )                           ) return '[Bot] Bingbot'     ;
			elseif (strpos($t, 'slurp'     )                           ) return '[Bot] Yahoo! Slurp';
			elseif (strpos($t, 'duckduckgo')                           ) return '[Bot] DuckDuckBot' ;
			elseif (strpos($t, 'baidu'     )                           ) return '[Bot] Baidu'       ;
			elseif (strpos($t, 'yandex'    )                           ) return '[Bot] Yandex'      ;
			elseif (strpos($t, 'sogou'     )                           ) return '[Bot] Sogou'       ;
			elseif (strpos($t, 'exabot'    )                           ) return '[Bot] Exabot'      ;
			elseif (strpos($t, 'msn'       )                           ) return '[Bot] MSN'         ;
	
			// Common Tools and Bots
			elseif (strpos($t, 'mj12bot'   )                           ) return '[Bot] Majestic'     ;
			elseif (strpos($t, 'ahrefs'    )                           ) return '[Bot] Ahrefs'       ;
			elseif (strpos($t, 'semrush'   )                           ) return '[Bot] SEMRush'      ;
			elseif (strpos($t, 'rogerbot'  ) || strpos($t, 'dotbot')   ) return '[Bot] Moz or OpenSiteExplorer';
			elseif (strpos($t, 'frog'      ) || strpos($t, 'screaming')) return '[Bot] Screaming Frog';
		   
			// Miscellaneous
			elseif (strpos($t, 'facebook'  )                           ) return '[Bot] Facebook'     ;
			elseif (strpos($t, 'pinterest' )                           ) return '[Bot] Pinterest'    ;
		   
			// Check for strings commonly used in bot user agents  
			elseif (strpos($t, 'crawler' ) || strpos($t, 'api'    ) ||
					strpos($t, 'spider'  ) || strpos($t, 'http'   ) ||
					strpos($t, 'bot'     ) || strpos($t, 'archive') ||
					strpos($t, 'info'    ) || strpos($t, 'data'   )    ) return '[Bot] Other'   ;
		   
			return 'Other (Unknown)';
	}

	/* ###################
	*  Author: Kantsverma
	*  Method: Used to register the scripts
	*  Date:  13-07-21
	* ###################*/

	function load_resources() {
		wp_register_script(
			PREFIX . 'rajorpay',
			'https://checkout.razorpay.com/v1/checkout.js',
			array( 'jquery' ),
			VERSION,
			true
		);
		wp_register_script(
			PREFIX . 'sweetalert',
			'https://cdn.jsdelivr.net/npm/sweetalert2@11',
			array( 'jquery' ),
			VERSION,
			true
		);		
		

		wp_enqueue_script( PREFIX . 'rajorpay' );
		wp_enqueue_script( PREFIX . 'sweetalert' );
	}

	add_action( 'wp_enqueue_scripts',    'load_resources' );

	/* ###################
	*  Author: Kantsverma
	*  Method: sendSms() is commond funcation to send the auto genrated sms to customer
	*  Date:  20-07-21
	* ###################*/	

    function sendSms($cust_id,$mobile,$msg,$templateId,  $senderId ='jshine', $save=0)
    {
        $sms_Mobile = trim($mobile);
        $sms_Msg = urldecode(str_replace('	','',$msg));
        
        if (!empty($sms_Mobile) && !empty($sms_Msg)) {
                $encoded_message = urlencode($sms_Msg);
                //$url = 'http://sms.smsdukan.in/app/smsapi/index.php?key=258FB210510A42&campaign=189&routeid=100344&type=text&contacts='.$sms_Mobile.'&senderid=JSHINE&msg='.$encoded_message;
                $url = 'http://sms.smsdukan.in/app/smsapi/index.php?key=258FB210510A42&campaign=189&routeid=100344&type=text&contacts='.$sms_Mobile.'&senderid=jshine&msg='.$encoded_message.'&template_id='.$templateId;

                if (function_exists('curl_init')) {
                    // initialize a new curl resource
                    $ch = curl_init(); 
                    // set the url to fetch
                    curl_setopt($ch, CURLOPT_URL, $url);
                    // don't give me the headers just the content
                    curl_setopt($ch, CURLOPT_HEADER, 0); 
                    // return the value instead of printing the response to browser
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
                    // use a user agent to mimic a browser
                    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5) Gecko/20041107 Firefox/1.0'); 
                    $content = curl_exec($ch);         
                    // remember to always close the session and free all resources 
                    curl_close($ch);
                } else {
                    // curl library is not installed so we better use something else
                    echo '<h2>OOPS! Your SMS Server doesnot support the required parameters, for more information contact Your Administration.</h2>';
                }
        }						
    }

    /**
     * Function: getCustomerTotalRewardPoints() used to get total no of reward points of custoemr by customer id
     * Date:     20-07-22
     * Author:   kantsverma
     * return \Illuminate\Http\Response
     */
    function getCustomerTotalRewardPoints($user_id)
    {
		global $wpdb;

		$total_points = $wpdb->get_var( "SELECT sum(amt) FROM pw_consolidate WHERE userid =".$user_id);
        return round($total_points,2);	
    }

    /**
     * Function: getPolicyTotalPayment() used to ge the total amount of payment done againts policy
     * Date:     20-07-22
     * Author:   kantsverma
     * return \Illuminate\Http\Response
     */   
    function getPolicyTotalPayment($policyId)
    {
		global $wpdb;
		$total_payment = $wpdb->get_var( "SELECT sum(amt) FROM consolidate_payment WHERE policy_code=".$policyId);		
          return round($total_payment,2);	
    }

	// if ( class_exists( 'HSW_Woocommerce_Addons' ) ) {
	// 	$GLOBALS['hsw'] = HSW_Woocommerce_Addons::get_instance();
	// 	register_activation_hook(   __FILE__, array( $GLOBALS['hsw'], 'activate' ) );
	// 	register_deactivation_hook( __FILE__, array( $GLOBALS['hsw'], 'deactivate' ) );
	// }
} else {
	add_action( 'admin_notices', 'hsw_requirements_error' );
}
