<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Services extends MY_Controller
{

	public function __construct()
	{
		parent::__construct();
		$currency = '';

		$this->$currency =  GeneralSettings();
	}
	public function index(){

		$currency = '';
		$data['currency'] = $this->$currency;
		$data['page'] = 'Services';
		$data['title'] = 'Services';

		if ($this->session->userdata('logged_in') == 1 && $this->session->userdata('userType') == 'Devotee') {
			$data['userDetails'] =  getUserDetails()->data[0];
			
		}

		$this->load->view('services/services',$data);

		// $this->load->view('services/services-cartSide',$data);	
	}

	// public function ServicesList(){


	// 	$data['page'] = 'Services List';
	// 	$data['title'] = 'Services List';


	// 	$ch = curl_init();

	// 	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
	// 	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

	// 	curl_setopt($ch, CURLOPT_URL, ApiBaseUrl()['url'].filterAPI()['url']);

	// 	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	// 	curl_setopt($ch, CURLOPT_POST, 1);
	// 	curl_setopt($ch, CURLOPT_POSTFIELDS, '{
	// 		"componentConfig": {
	// 			"query": {
	// 				"aspectType": "ServiceSetup",
	// 				"serviceCategoryTypes": "IN-TEMPLE",
	// 				"sourceTypes": "WEBSITE",
	// 				"status": "ACTIVE"
	// 				},
	// 				"moduleName": "Temple Services",
	// 				"aspectType": "ServiceSetup",
	// 				"collectionType": "Business",
	// 				"productID": "'.ApiBaseUrl()['productID'].'",
	// 				"clientID": "'.ApiBaseUrl()['clientID'].'",
	// 				"skip": 0,
	// 				"next": 6
	// 			}
	// 		}');

	// 	$headers = array();
	// 	$headers[] = 'Content-Type: application/json';
	// 	curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

	// 	$result = curl_exec($ch);
	// 	$response = json_decode($result);

	// 	if (curl_errno($ch)) {
	// 		echo 'Error:' . curl_error($ch);
	// 	}

	// 	curl_close($ch);
	// 	$services = json_decode(json_encode($response->data), true);
	// 	$data['services'] = sortBySequenceId($services);

	// 	$this->load->view('services/services-list',$data);

	// }

	public function ServiceRequestForm($request_page){

		
		$currency = '';
		$data['currency'] = $this->$currency;
		$data['page'] = 'Services';
		if (($this->session->userdata('logged_in') == 1 && $request_page == 'outside-temple') || ($this->session->userdata('logged_in') == 1 && $request_page == 'aparakarya') || ($this->session->userdata('logged_in') == 1 && $request_page == 'in-temple')) {


			$data['preferredLocations'] = getPreferredLocations()->data;

			$data['userDetails'] =  getUserDetails()->data[0];

			$data['PriestData'] = getPriest()->data;

			$this->load->view('services/services',$data);
		}else{
			redirect(base_url('services'));
		}



		

	}
	

	
	public function addCart(){
		if($this->input->post())
		{
			$this->session->set_userdata('service_cart', $this->input->post());

			$cartList = $this->session->userdata('service_cart');

			if (isset($cartList['includeSankalpam'])) {
				$includeSankalpam = checkForYesValue($cartList['includeSankalpam']);
			}else{

				$includeSankalpam = 'NO';
			}
		}


		$response = array(
			'status' => '1', 
			'message' => "Success",
			'includeSankalpam' => $includeSankalpam
		);
		echo json_encode($response);
	}


	public function updateCart(){


		$array1 = $this->input->post();



		$array2 = $this->session->userdata('service_cart');

		$mergedArray = $array2;

		foreach ($array1['service_id'] as $key => $serviceId) {
			$index = array_search($serviceId, $array2['ids']);
			if ($index !== false) {
				$mergedArray['isServicePaid'][$index] = $array1['isServicePaid'][$key];
			}
		}

		$this->session->set_userdata('service_cart', $mergedArray);
		print_r($mergedArray);


	}


	public function PaylaterAddCart(){
		if($this->input->post())
		{
			$this->session->set_userdata('paylater_service_cart', $this->input->post());

			$cartList = $this->session->userdata('paylater_service_cart');

			if (isset($cartList['includeSankalpam'])) {
				$includeSankalpam = checkForYesValue($cartList['includeSankalpam']);
			}else{

				$includeSankalpam = 'NO';
			}
		}


		$response = array(
			'status' => '1', 
			'message' => "Success",
			'includeSankalpam' => $includeSankalpam
		);
		echo json_encode($response);
	}



	public function AddToCart()
	{

		if ($this->session->userdata('logged_in') == 1) {



			$paymentSource = $this->input->post('paymentSource');

			if ($paymentSource == 'CAW') {
				$paymentSource_data = 'CAW_CARD_NOT_PRESENT';
			} else if ($paymentSource == 'MPI') {
				$paymentSource_data = 'MPI_CARD_NOT_PRESENT';
			} else {
				$paymentSource_data = 'PAYPAL_CARD_NOT_PRESENT';
			}


			$PaymentStatus = $this->input->post('status');

			$cart_data = json_decode($this->input->post('cart_data'), true);

			$dataWithAmount = array();
			$serviceRequest = array();

			for ($i = 0; $i < count($cart_data['ids']); $i++) {

				$payment_type_check = $cart_data['bookingtype'][$i];

				if (isset($cart_data['startDate'][$i]) && !empty($cart_data['startDate'][$i])) {
					$startDateArray = explode(", ", $cart_data['startDate'][$i]);

					foreach ($startDateArray as $startDate) {

						$dataWithAmount[] = array(
							"_id" => $cart_data['ids'][$i],
							"ServiceId" => $cart_data['ids'][$i],
							"serviceName" => $cart_data['serviceName'][$i],
							"serviceCategory" => $cart_data['ctg'][$i],
							"serviceType" => $cart_data['serviceTypes'][$i],
							"serviceAmount" => $cart_data['serviceAmount'][$i],
							"startDate" => $startDate,
							"qty" => $cart_data['qty'][$i],
							"time" => @$cart_data['startTime'][$i],
							"bookingType" => @$payment_type_check,
							"day" => "",
							"serviceAddress" => "",
							"cartCreDate" => date("m/d/Y"),
							"cartCreTime" => date("h:i A"),
							"isServicePaid" => @$cart_data['isServicePaid'][$i],
							"serviceDesc" => @$cart_data['service_desc'][$i]
						);
					}
				} else {

					$dataWithAmount[] = array(
						"_id" => $cart_data['ids'][$i],
						"ServiceId" => $cart_data['ids'][$i],
						"serviceName" => $cart_data['serviceName'][$i],
						"serviceCategory" => $cart_data['ctg'][$i],
						"serviceType" => $cart_data['serviceTypes'][$i],
						"serviceAmount" => $cart_data['serviceAmount'][$i],
						"startDate" => '',
						"qty" => $cart_data['qty'][$i],
						"time" => @$cart_data['startTime'][$i],
						"bookingType" => @$payment_type_check,
						"day" => "",
						"serviceAddress" => "",
						"cartCreDate" => date("m/d/Y"),
						"cartCreTime" => date("h:i A"),
						"isServicePaid" => @$cart_data['isServicePaid'][$i],
						"serviceDesc" => @$cart_data['service_desc'][$i]
					);
				}
			}

			$dataWithAmountJson = json_encode($dataWithAmount);


			if (!empty($dataWithAmount)) {


				$ch = curl_init();

				curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
				curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
				curl_setopt($ch, CURLOPT_URL, ApiBaseUrl()['url'] . addServiceCart()['url']);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
				curl_setopt($ch, CURLOPT_POST, 1);
				curl_setopt($ch, CURLOPT_POSTFIELDS, "{         
					\"productId\": \"" . ApiBaseUrl()['productID'] . "\",
					\"clientId\": \"" . ApiBaseUrl()['clientID'] . "\",      
					\"memberId\":\"" . $this->session->userdata('id') . "\",      
					\"memberName\":\"" . $this->session->userdata('refDataName') . "\",      
					\"prsnEmail\": \"" . $this->session->userdata('email') . "\",      
					\"prsnPhone\": \"" . $this->session->userdata('phone') . "\", 

					\"data\": $dataWithAmountJson, 

					\"paymentType\": \"CREDIT CARD\",
					\"paymentSource\": \"" . $paymentSource_data . "\", 
					\"etKitchenTIp\": \"" . $PaymentStatus . "\", 
					\"attemptType\": \"" . $PaymentStatus . "\",
					\"cartCreDate\": \"" . date("m/d/Y") . "\",
					\"cartCreTime\": \"" . date("h:i A") . "\",

					\"bankName\":\"\" ,
					\"chequeNo\":\"\" , 
					\"chequeAmount\":\"\" , 
					\"chequeDate\": \"\", 
					\"acharyasanbhavana\": " . $this->input->post('acharya_sambhavana') . ", 
					\"generaldonations\": " . $this->input->post('general_donation') . ", 

					\"totalAmount\": " . $this->input->post('totalPrice') . ", 
					\"transactionId\":\"" . $this->input->post('transaction_id') . "\",
					\"source\":\"WEBSITE\"

				}     
				");
				$token = $this->session->userdata('token');
				$headers = array();


				$headers[] = 'Authorization: Bearer ' . $token . '';

				$headers[] = 'Content-Type: application/json';
				curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

				$result = curl_exec($ch);

				if (curl_errno($ch)) {
					echo 'Error:' . curl_error($ch);
				}
				curl_close($ch);

				$response2 = json_decode($result);
				$sess_temp_order_details = json_decode($result, true);

				// print_r($sess_temp_order_details);


				// die();

				$this->session->set_userdata('temp_order_details', $sess_temp_order_details['data'][0]);

				
			}

			if ($PaymentStatus != 'TEMP') {

				if (@$cart_data['cart_type'] == 'SERVICES') {

					$this->session->unset_userdata('service_cart');
				}

				echo json_encode($response2);
			}else{
				echo json_encode($response2);
			}
		}
	}



	public function PayLaterServiceRequest(){

		if ($this->session->userdata('logged_in') == 1) {

			$cart_data =  $this->session->userdata('paylater_service_cart');


			for($i = 0; $i < count($cart_data['ids']); $i++) {
				$data[] = array(
					"_id" => $cart_data['ids'][$i],
					"serviceName" => $cart_data['serviceName'][$i],
					"serviceCategory" => $cart_data['ctg'][$i],
					"serviceType" => $cart_data['serviceTypes'][$i],
					"serviceAmount" => $cart_data['serviceAmount'][$i],
					"startDate" => @$cart_data['startDate'][$i],
					"qty" => $cart_data['qty'][$i],
					"time" => @$cart_data['startTime'][$i],
					"day" => "",
					"serviceAddress" => ""
				);
			}


			foreach($data as $item){

				$name_parts = explode(" ", $this->session->userdata('refDataName'));
				$first_name = @$name_parts[0];
				$last_name = @$name_parts[1];

				$newData = array(); 

				$newData['memberId'] = $this->session->userdata('id');
				$newData['serviceId'] = $item['_id'];
				$newData['serviceRequestName'] = $first_name.' '.$last_name;
				$newData['prsnEmail'] = $this->session->userdata('email');
				$newData['prsnPhone'] = $this->session->userdata('phone');
				$newData['clientId'] = ApiBaseUrl()['clientID'];
				$newData['serviceDate'] = $item['startDate'];
				$newData['serviceTime'] = $item['time'];
				$newData['serviceLocationName'] = $item['serviceCategory'];
				$newData['adults'] = '';
				$newData['children'] = '';
				$newData['serviceAddress'] = @$this->input->post('venue') !='' ?  $this->input->post('venue') : @$this->session->userdata('address');
				$newData['foodType'] = '';
				$newData['package'] = '';
				$newData['extraFood'] = '';
				$newData['serviceName'] = $item['serviceName'];
				$newData['serviceCategoryTypes'] = $item['serviceCategory'];
				$newData['serviceTypes'] = $item['serviceType'];
				$newData['serviceAmount'] = $item['serviceAmount'];;
				$newData['notes'] = @$this->input->post('description');
				$newData['languagePreferenceName'] = '';
				$newData['requestForPriestName'] = @$this->input->post('priestName');

				$newData['priestEmail'] = @$this->input->post('priestEmail');
				$newData['priestPhone'] = @$this->input->post('priestPhone');
				$newData['etShraadhamFor'] = '';
				$newData['ettithiDetail'] = '';
				$newData['source'] = 'WEBSITE';
				$newData['notificationEmailName'] = 'YES';



				$dataPost = json_encode($newData);

				$ch = curl_init();
				curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
				curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

				curl_setopt($ch, CURLOPT_URL, ApiBaseUrl()['url'].addServiceRequest()['url']);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
				curl_setopt($ch, CURLOPT_POST, 1);
				curl_setopt($ch, CURLOPT_POSTFIELDS, $dataPost);

				$token = $this->session->userdata('token');
				$headers = array();
				$headers[] = 'Authorization: Bearer '.$token.'';

				$headers[] = 'Content-Type: application/json';
				curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

				$result = curl_exec($ch);

				$response = json_decode($result);
				if (curl_errno($ch)) {
					echo 'Error:' . curl_error($ch);
				}
				curl_close($ch);



			}


			if($response->statusCode == 1){
				$this->session->unset_userdata('paylater_service_cart');
			}

			echo json_encode($response);

		}

	}
	public function AddServiceRequest($serviceRequest = ''){

		if ($this->session->userdata('logged_in') == 1) {

			$cart_data =  $this->session->userdata('service_cart');

			if ($serviceRequest == '') {

				if (isset($cart_data)) {

					for($i = 0; $i < count($cart_data['ids']); $i++) {
						$data[] = array(
							"_id" => $cart_data['ids'][$i],
							"serviceName" => $cart_data['serviceName'][$i],
							"serviceCategory" => $cart_data['ctg'][$i],
							"serviceType" => $cart_data['serviceTypes'][$i],
							"serviceAmount" => $cart_data['serviceAmount'][$i],
							"startDate" => @$cart_data['startDate'][$i],
							"qty" => $cart_data['qty'][$i],
							"time" => @$cart_data['startTime'][$i],
							"day" => "",
							"serviceAddress" => ""
						);
					}
				}else{

					$id = $this->input->post('serviceId');
					$serviceName = $this->input->post('serviceName');
					$serviceCategory = $this->input->post('serviceCategory');
					$serviceTypes = $this->input->post('serviceTypes');
					$startDate = $this->input->post('startDate');
					$serviceAmt = $this->input->post('serviceAmt');
					$startTime = $this->input->post('startTime');

					$data[] = array(
						"_id" => $id,
						"serviceName" => $serviceName,
						"serviceCategory" => $serviceCategory,
						"serviceType" => $serviceTypes,
						"serviceAmount" => $serviceAmt,
						"startDate" => @$startDate,
						"qty" => 1,
						"time" => @$startTime,
						"day" => "",
						"serviceAddress" => ""
					);
				}

			}else{
				$data = json_decode($serviceRequest, true);
			}


			foreach($data as $item){

				$name_parts = explode(" ", $this->session->userdata('refDataName'));
				$first_name = @$name_parts[0];
				$last_name = @$name_parts[1];

				$newData = array(); 

				$newData['memberId'] = $this->session->userdata('id');
				$newData['serviceId'] = $item['_id'];
				$newData['serviceRequestName'] = $first_name.' '.$last_name;
				$newData['prsnEmail'] = $this->session->userdata('email');
				$newData['prsnPhone'] = $this->session->userdata('phone');
				$newData['clientId'] = ApiBaseUrl()['clientID'];
				$newData['serviceDate'] = $item['startDate'];
				$newData['serviceTime'] = $item['time'];
				$newData['serviceLocationName'] = $item['serviceCategory'];
				$newData['adults'] = '';
				$newData['children'] = '';
				$newData['serviceAddress'] = $this->session->userdata('address');
				$newData['foodType'] = '';
				$newData['package'] = '';
				$newData['extraFood'] = '';
				$newData['serviceName'] = $item['serviceName'];
				$newData['serviceCategoryTypes'] = $item['serviceCategory'];
				$newData['serviceTypes'] = $item['serviceType'];
				$newData['serviceAmount'] = $item['serviceAmount'];;
				$newData['notes'] = '';
				$newData['languagePreferenceName'] = '';
				$newData['requestForPriestName'] = '';

				$newData['priestEmail'] = '';
				$newData['priestPhone'] = '';
				$newData['etShraadhamFor'] = '';
				$newData['ettithiDetail'] = '';
				$newData['source'] = 'WEBSITE';
				$newData['notificationEmailName'] = 'YES';



				$dataPost = json_encode($newData);

				$ch = curl_init();
				curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
				curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

				curl_setopt($ch, CURLOPT_URL, ApiBaseUrl()['url'].addServiceRequest()['url']);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
				curl_setopt($ch, CURLOPT_POST, 1);
				curl_setopt($ch, CURLOPT_POSTFIELDS, $dataPost);

				$token = $this->session->userdata('token');
				$headers = array();
				$headers[] = 'Authorization: Bearer '.$token.'';

				$headers[] = 'Content-Type: application/json';
				curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

				$result = curl_exec($ch);

				$response = json_decode($result);
				if (curl_errno($ch)) {
					echo 'Error:' . curl_error($ch);
				}
				curl_close($ch);



			}

			if ($serviceRequest == '') {

				if($response->statusCode == 1){
					$this->session->unset_userdata('service_cart');
				}

				echo json_encode($response);
			}else{
				return $response;
			}
		}

	}


	public function updateTransactionStatus($id = '', $invoiceNo = '', $PaymentStatus = ''){

		if (!empty($this->input->post('transaction_id'))) {
			$paymentDescription = json_encode($this->input->post('paymentDescription'));
			$transactionId = $this->input->post('transaction_id');
			$PaymentStatus = $this->input->post('status');
		}else{
			$transactionId = '';
		}

		if (!empty($this->session->userdata('temp_order_details'))) {
			$invoiceNo = $this->session->userdata('temp_order_details')['invoiceNo'];
			$id = $this->session->userdata('temp_order_details')['_id'];
		}

		$ch = curl_init();

		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($ch, CURLOPT_URL, ApiBaseUrl()['url'].updateTransactionStatus()['url']);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, "{         
			\"productId\": \"".ApiBaseUrl()['productID']."\",
			\"clientId\": \"".ApiBaseUrl()['clientID']."\",  

			\"_id\":\"".$id."\",      
			\"invoiceNo\":\"".$invoiceNo."\",      
			\"paymentStatus\": \"".$PaymentStatus."\",      
			\"transactionId\": \"".$transactionId."\"

		}     
		");
		$token = $this->session->userdata('token');

		$headers = array();

		$headers[] = 'Authorization: Bearer '.$token.'';

		$headers[] = 'Content-Type: application/json';
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

		$result = curl_exec($ch);
		if (curl_errno($ch)) {
			echo 'Error:' . curl_error($ch);
		}
		curl_close($ch);


		if (!empty($this->input->post('transaction_id')) && $PaymentStatus == 'COMPLETED') {
				// print_r($result);
			$response = json_decode($result);

			$this->session->unset_userdata('temp_order_details');
			$this->session->unset_userdata('service_cart');

			$data['orderId'] = $id;
			$data['envoiceNo'] = $invoiceNo;
			$data['statusCode'] = $response->statusCode;
			$data['message'] = $response->message;
			$updatedResponse = json_encode($data);
			print_r($updatedResponse);
		}else if(!empty($this->input->post('transaction_id')) && $PaymentStatus == 'FAILED'){
			// print_r($result);
			$response = json_decode($result);

			// $this->session->unset_userdata('temp_events_order_details');
			// $this->session->unset_userdata('events_cart');

			$data['orderId'] = $id;
			$data['envoiceNo'] = $invoiceNo;
			$data['statusCode'] = $response->statusCode;
			$data['message'] = $transactionId;
			$updatedResponse = json_encode($data);
			print_r($updatedResponse);
		}else{

			return $response = json_decode($result);
		}

	}

	public function ViewCart(){
		$currency 				= '';
		$data['currency'] 		= $this->$currency;
		$data['page'] 			= 'Services Cart';
		$data['title'] 			= 'Services Cart';
		$data['session_data'] 	= 'service_cart';
		$this->load->view('services/view-cart',$data);
	}


	public function checkServiceAvailibilty(){



		$no_days = 30;


		if($this->input->post())
		{
			$formData = $this->input->post();

			$startDate 	 = $formData['startDate']?$formData['startDate']:(date('m/d/Y'));
			$endDate 	 = $formData['endDate']?$formData['endDate']:(date('m/d/Y', strtotime("+".$no_days." days")));


			$startTime = $formData['startTime'];
			$serviceName = $formData['serviceName'];
			$endTime 	 = $formData['endTime'];

			$BookingLimitPerDay 	 = $formData['BookingLimitPerDay'];
			$serviceID 				 = $formData['serviceID'];

			// $details = array('statusCode' =>'1' ); //getServiceAvailibiltydata($startDate, $startTime, $serviceName, $endDate, $endTime);
			$details = getServiceAvailibiltydata($startDate, $startTime, $serviceName, $endDate, $endTime);



			$html = '';
			for ($i=0; $i < $no_days; $i++) { 
				$newDate = date('m/d/Y', strtotime("+".$i." days"));
				$BookingLimitPerDay 	 = $formData['BookingLimitPerDay'];

				if(!empty($details['data']))
				{
					if(in_array($newDate, array_column($details['data'], '_id')))
					{
						$BookingLimitPerDay = $BookingLimitPerDay - $details['data'][array_search($newDate, array_column($details['data'], '_id'))]['count'];
					}
				}


				$html .= '<tr>';
				$html .= '<td style="vertical-align: middle;padding: 20px;"> <strong> '.$newDate.' </strong></td>';
				$html .= '<td> <a href="javascript:void(0);" onclick="serviceAvailabilitybook(this);" class="btn btn-primary availability-btn" data-date="'.$newDate.'" data-service-id="'.$serviceID.'"  data-availability="'.$BookingLimitPerDay.'"> Availability ('.$BookingLimitPerDay.')</a>   </td>';
				$html .= '</tr>';
			}


			$month1 = date('M', strtotime($startDate));
			$month2 = date('M', strtotime($endDate));

			if ($month1 == $month2) {
				$details['headerMonths'] = ' ( '.$month1.' )';
			} else {
				$details['headerMonths'] = ' ( '.$month1 . '-' . $month2.' )';
			}

			$details['servicesList'] = $html;

			echo json_encode($details);
		}

	}






	public function delete_cart_row(){
		$row_id 	= $this->input->post('row_id');
		$selected_date 	= $this->input->post('selected_date');

		$cart_items = $this->session->userdata('service_cart');
		$total_price = $cart_items['totalPrice'];
		$row_price = 0;



		foreach($cart_items['ids'] as $key => $id){
			if($id == $row_id){

				if(!empty($cart_items['startDate'][$key]))
				{
					$cartDateCount = explode(',', $cart_items['startDate'][$key]);

					$cartDateCount_arr = array();
					foreach ($cartDateCount as $keyk => $cartDateCount_val) {
						if(trim($cartDateCount_val) != trim($selected_date))
						{
							$cartDateCount_arr[] = $cartDateCount_val;
						}
					}

					if (!empty($cartDateCount_arr)) {
						$cart_items['startDate'][$key] = implode(',', $cartDateCount_arr);
					}

					$row_price = $cart_items['serviceAmount'][$key]*$cart_items['qty'][$key];

					if(empty($cartDateCount_arr))
					{
						unset($cart_items['ids'][$key]);
						unset($cart_items['qty'][$key]);
						unset($cart_items['serviceName'][$key]);
						unset($cart_items['description'][$key]);
						unset($cart_items['serviceAmount'][$key]);
						unset($cart_items['image'][$key]);
						unset($cart_items['startDate'][$key]);
						unset($cart_items['startTime'][$key]);
						unset($cart_items['cart_ctg'][$key]);
						unset($cart_items['serviceTypes'][$key]);
						unset($cart_items['bookingtype'][$key]);
						unset($cart_items['ctg'][$key]);
					}
				}
				break;
			}
		}



		$total_price = $total_price-$row_price;
			// echo $total_price; die();

		$cart_items['totalPrice'] = $total_price;
		$this->session->set_userdata('service_cart', $cart_items);
		echo json_encode(array('status' => 'success'));


	}


	public function getThithiNext90Days(){

		$tithi = $this->input->post('tithi');
		$datesArray = getThithiNext90Days($tithi);


		if (!empty($datesArray['data'])) {
			$dates = array();
			foreach ($datesArray['data'] as $key => $value) {

				$newDate = str_replace("T00:00:00.000Z", "", $value['startDate']);

				array_push($dates, $newDate);
					// $dates =  $newDate;
			}
			echo json_encode($dates);
				// echo '<pre>';
				// print_r($datesArray);
				// die();

		}else{
			echo json_encode($datesArray);
		}
	}





	public function AddSankalpamToSession(){

		$this->session->set_userdata('sankalpam_data',$this->input->post('formData'));

		$result = array('statusCode'=> 1, 'status' => 'success', 'message' => 'sankalpam_data has been saved in session');
			// echo json_encode($result);


		$family_member_name = $this->input->post('formData');

		$formData = $family_member_name; 

		$fullNames = [];
		$gotras = [];
		$stars = [];

		foreach ($formData as $key => $value) {
			$trimmedKey = rtrim($key, '0');

			if ($trimmedKey === 'fname') {
				$fname[] = $value;
			} elseif ($trimmedKey === 'lname') {
				$lname[] = $value;
			}
			elseif ($trimmedKey === 'gotra') {
				$gotras[] = $value;
			} elseif ($trimmedKey === 'stars') {
				$stars[] = $value;
			}
		}

    // Display or process the separated data arrays as needed


		$fullNames = array();

		for ($i = 0; $i < count($fname); $i++) {
			$fullName = $fname[$i] . ' ' . $lname[$i];
			$fullNames[] = $fullName;
		}
		$newArray = array();
		for ($i = 0; $i < count($fullNames); $i++) {
			$newArray[] = array(
				'family_member_name' => $fullNames[$i],
				'family_member_rashi' => $gotras[$i],
				'family_member_stars' => $stars[$i]
			);
		}

		$jsonArray = array();
		foreach ($newArray as $key => $val) {
			$jsonArray[] = array(
				'memberName' => $val['family_member_name'],
				'rashi' => $val['family_member_rashi'],
				'nakshatra' => $val['family_member_stars']
			);
		}
		$moduleName = customerLogin()['moduleName'];
		$Id = $this->session->userdata('id');

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

		curl_setopt($ch, CURLOPT_URL, ApiBaseUrl()['url'].postAPI()['url']);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, "{  
			\"_id\":\"".$Id."\",    
			\"dataJson\": { 
				\"memberDetail\":".json_encode($jsonArray)."
				},
				\"componentConfig\": {\"moduleName\":\"Contacts\",        
				\"productID\": \"".ApiBaseUrl()['productID']."\",        
				\"clientID\": \"".ApiBaseUrl()['clientID']."\",        
				\"userName\": \"".$this->session->userdata('refDataName')."\"    }}");

		$token = $this->session->userdata('token');
		$headers = array();
		$headers[] = 'Authorization: Bearer '.$token.'';
		$headers[] = 'Content-Type: application/json';
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

		$result = curl_exec($ch);
		$response = json_decode($result, true);
		if (curl_errno($ch)) {
			echo 'Error:' . curl_error($ch);
		}
		curl_close($ch);

		echo json_encode($response);

	}



		// MPI Integration 09/01/2023


	public function mpiCardPayment(){

		$token = $this->input->post('token');
		$totolAmt = $this->input->post('totolAmt');
		$name = $this->input->post('name');
		$address = $this->input->post('address');
		$zipcode = $this->input->post('zipcode');


		$roundedAmount = round($totolAmt, 2);
		$amountInCents = $roundedAmount * 100;


		$invoiceNum = floor(microtime(true) * 1000);





		$postData = array(
			'token' => $token,
			'amount' => $amountInCents,
			'name' => $name,
			'address' => $address,
			'zipcode' => $zipcode,
			'clientId' => ApiBaseUrl()['clientID'],
			'InvoiceNum' => $invoiceNum
		);



			// ====================================

		$cart_data = json_decode($this->input->post('cart_data'), true);
		$postData_addServiceCartTemp = array(
			'cardData' => $cart_data,
			'Paymenttype' => 'CREDIT CARD',

			'InvNumber' => $invoiceNum,
			'totalAmount' => $amountInCents,

			'TerminalId' => 'WEBSITE',

			'clientId' => ApiBaseUrl()['clientID'],
			'productId' => ApiBaseUrl()['productID'],
			'paymentSource' => 'MPI_CARD_NOT_PRESENT',
			'Source' => 'WEBSITE',
			"cartCreDate" => date("m/d/Y"),
			"cartCreTime" => date("h:i A"),
			'remark' => 'WEBSITE~WEBSITE~'.$this->session->userdata('id')
		);


		$ch = curl_init();
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

		curl_setopt($ch, CURLOPT_URL, ApiBaseUrl()['url'].'/api/bookingService/addServiceCartTemp');
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData_addServiceCartTemp));

		$headers = array();
		$headers[] = 'Content-Type: application/json';
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

		curl_exec($ch);
		if (curl_errno($ch)) {
			echo 'Error:' . curl_error($ch);
		}
		curl_close($ch);


			// =====================================


		$ch = curl_init();
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

		curl_setopt($ch, CURLOPT_URL, ApiBaseUrl()['url'].'api/vaaptech/mpiCardPayment');
			// curl_setopt($ch, CURLOPT_URL, 'http://192.168.1.6:3000/api/vaaptech/mpiCardPayment');
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));

		$headers = array();
		$headers[] = 'Content-Type: application/json';
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

		$result = curl_exec($ch);
		if (curl_errno($ch)) {
			echo 'Error:' . curl_error($ch);
		}
		curl_close($ch);

		$response = json_decode($result, true);

		echo json_encode($response);
	}



	public function PayLaterServices(){
		$currency = '';
		$data['currency'] = $this->$currency;
		$data['page'] = 'Services';

		if ($this->session->userdata('logged_in') == 1 && $this->session->userdata('userType') == 'Devotee') {
			$data['userDetails'] =  getUserDetails()->data[0];

		}

		$this->load->view('services/paylater-services',$data);
	}
}
