<?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';

		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": 1024
				}
			}');

		$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)
	{
		$data['GetState'] = GetState();
		$data['nakshtra_data'] = getNakshtra()['data'];
		$data['gotra_data'] = getGotra()['data'];
		$data['rashi_data'] = getRashi()['data'];

		$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')
		) {

			$preferredLocations = getPreferredLocations();

			// Check if 'data' exists and is not empty
			if (isset($preferredLocations->data) && !empty($preferredLocations->data)) {
				$data['preferredLocations'] = $preferredLocations->data;
			} else {
				$data['preferredLocations'] = []; // Fallback to an empty array
			}

			$userDetails = getUserDetails();

			// Check if 'data' exists and is not empty
			if (isset($userDetails->data) && !empty($userDetails->data)) {
				$data['userDetails'] = $userDetails->data[0];
			} else {
				$data['userDetails'] = null; // Fallback to null if no user details
			}

			$priestData = getPriest();

			// Check if 'data' exists and is not empty
			if (isset($priestData->data) && !empty($priestData->data)) {
				$data['PriestData'] = $priestData->data;
			} else {
				$data['PriestData'] = []; // Fallback to an empty array
			}

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




	public function addCart()
	{
		if ($this->input->post()) {
			// echo "<pre>";
			// var_dump($this->input->post());die();
			$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 = $this->input->post('cart_data');
			// var_dump($cart_data);
			if (!is_array($cart_data)) {
				$cart_data = json_decode($this->input->post('cart_data'), true);
			}
			// var_dump($cart_data);die();

			$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],
							"serviceOccurrencesNo" => @$cart_data['serviceOccurrencesNo'][$i],
							"oldServiceAmount" => isset($cart_data['oldServiceAmount'][$i]) && $cart_data['oldServiceAmount'][$i] > 0 ? $cart_data['oldServiceAmount'][$i] : $cart_data['serviceAmount'][$i],
							"discountedAmount" => isset($cart_data['discountedAmount'][$i]) && $cart_data['discountedAmount'][$i] > 0 ? $cart_data['discountedAmount'][$i] : 0,
							"fullPackage" => @$cart_data['fullPackage'][$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],
						"serviceOccurrencesNo" => @$cart_data['serviceOccurrencesNo'][$i],
						"fullPackage" => @$cart_data['fullPackage'][$i],
						"oldServiceAmount" => isset($cart_data['oldServiceAmount'][$i]) && $cart_data['oldServiceAmount'][$i] > 0 ? $cart_data['oldServiceAmount'][$i] : $cart_data['serviceAmount'][$i],
						"discountedAmount" => isset($cart_data['discountedAmount'][$i]) && $cart_data['discountedAmount'][$i] > 0 ? $cart_data['discountedAmount'][$i] : 0,
					);
				}
			}

			$dataWithAmountJson = json_encode($dataWithAmount);

			// var_dump($dataWithAmountJson);die();
			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);


				$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 = 90;

		if ($this->input->post()) {
			// var_dump($this->input->post('holdingDates'));
			$formData = $this->input->post();
			$holdingDates = isset($formData['holdingDates']) && !empty($formData['holdingDates']) ? explode(", ", $formData['holdingDates']) : [];
			$startDate = @$formData['startDate'] ? @$formData['startDate'] : date('m/d/Y');
			//  echo $startDate;
			$endDate = @$formData['endDate'] ? @$formData['endDate'] : date('m/d/Y', strtotime("+$no_days days"));
			// echo "<br>";
			// echo $endDate;die();
			$startTime = @$formData['startTime'];
			$serviceName = @$formData['serviceName'];
			$endTime = @$formData['endTime'];
			$daytype = @$formData['daytype'];
			$cutofftime = @$formData['cutofftime'];

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

			// Fetch service availability data
			$details = getServiceAvailibiltydata($startDate, $serviceName, $endDate);

			// print_r( $details);

			// die();

			$html = '';
			$daytypes = array_map('trim', explode('&', strtoupper($daytype))); // Split daytype string by ' & ' and convert to uppercase

			// Function to add ordinal suffix to a number
			function addOrdinalSuffix($num)
			{
				if (!in_array(($num % 100), array(11, 12, 13))) {
					switch ($num % 10) {
						case 1:
							return $num . 'st';
						case 2:
							return $num . 'nd';
						case 3:
							return $num . 'rd';
					}
				}
				return $num . 'th';
			}

			// Get the current Unix timestamp
			$currentTimeUnix = time();

			// Convert the cutoff time to a Unix timestamp
			$cutofftimeUnix = null;
			if ($cutofftime) {
				$dateTimeString = date('Y-m-d ') . $cutofftime;
				$cutofftimeUnix = strtotime($dateTimeString);
				$currentTimeUnix  = strtotime(date('Y-m-d H:i'));
			}

			// Iterate through days from startDate to endDate
			$currentDate = strtotime($startDate);
			$endDateUnix = strtotime($endDate);
			// echo $startDate.'/'.$endDate;
			while ($currentDate <= $endDateUnix) {

				// $details = getServiceAvailibiltydata(date('m/d/Y',$currentDate), $serviceName, $endDate);
				$newDate = date('m/d/Y', $currentDate);
				$dayOfWeek = strtoupper(date('l', $currentDate)); // Get the day of the week in uppercase
				// $html.=date('m/d/Y',$currentDate).'=====>'.date('m/d/Y',$endDateUnix).'<br>';
				// $html.= "okkk/".in_array($dayOfWeek, $daytypes)?'YES':'NO'.'<br>';
				// Check if the day of the week matches any of the specified daytypes
				if (in_array($dayOfWeek, $daytypes)) {
					$BookingLimitPerDay = @$formData['BookingLimitPerDay'];
					// echo $BookingLimitPerDay.' / ';
					// var_dump($details['data']);
					if (!empty($details['data'])) {
						if (in_array($newDate, array_column($details['data'], '_id'))) {
							// echo $details['data'][array_search($newDate, array_column($details['data'], '_id'))]['count']; die();
							$BookingLimitPerDay = $BookingLimitPerDay - $details['data'][array_search($newDate, array_column($details['data'], '_id'))]['count'];
						}
					}
					// echo $BookingLimitPerDay.'<br>';
					// echo '=====>'.in_array($dayOfWeek, $daytypes) ? 'YES' :'NO';
					// echo '<br>'.date('m/d/Y',$currentDate);
					$dayName = date('l', $currentDate); // Get the day name
					$monthName = date('F', $currentDate); // Get the month name
					$dayNum = date('j', $currentDate); // Get the day number without leading zeros
					$formattedDate = $dayName . ', ' . $monthName . ' ' . addOrdinalSuffix($dayNum);

					// Check if the current time has passed the cutoff time for the next available date
					$display_hidden = '';
					$isDisabled = '';
					$tb_bg = '';
					$btn = '';

					$nextDay = date('m/d/Y', strtotime("+1 day", $currentDate));
					$nextDayStartUnix = strtotime($nextDay . ' 00:00:00');

					if ($BookingLimitPerDay <= 0) {
						$BookingLimitPerDay = 0;
						$display_hidden = 'hidden';
						$isDisabled = ' disabled';
						$tb_bg = 'background: #eeeeee';
						$btn = 'background: #242424;border: 2px solid black !important;';
					} else {

						$newDateUnix = strtotime($newDate);
						if ($newDateUnix < strtotime(date('m/d/Y'))) {
							$display_hidden = 'hidden 22';
							$isDisabled = ' disabled';
							$tb_bg = 'background: #eeeeee';
							$btn = 'background: #242424;border: 2px solid black !important;';
						} else {
							if ($cutofftime && $newDate == $nextDay && $currentTimeUnix > $cutofftimeUnix) {
								$display_hidden = 'hidden';
								$isDisabled = ' disabled';
								$tb_bg = 'background: #eeeeee';
							} else {
								$display_hidden = '';
								$isDisabled = '';
								$filter = '';
								$tb_bg = '';
								$btn = '';
							}
						}
					}

					$description = '';


					if (in_array($newDate, $holdingDates)) {

						$date = DateTime::createFromFormat('m/d/Y', $newDate);
						$formattedDate = strtoupper($date->format('F jS'));


						$display_hidden = '';
						$isDisabled = ' disabled';
						$tb_bg = 'background: #eeeeee';
						$btn = 'background: #242424;border: 2px solid black !important;';
						$description = '<br><span style="color:red!important;font-weight:bold;">BOOKINGS NOT ACCEPTED FOR ' . $formattedDate . '.</span>';
					}
					// Generate HTML for the matching dates
					// echo strtotime($newDate) > strtotime(date('m/d/Y'));
					// echo $newDate.'===>'.date('m/d/Y');
					// echo "<br>";
					// echo strtotime($newDate) > strtotime(date('m/d/Y'))?'YES':'NO';
					// echo "<br>";
					if (strtotime($newDate) == strtotime(date('m/d/Y'))) {

						$display_hidden = '';
						$isDisabled = ' disabled';
						$tb_bg = 'background: #eeeeee';
						$btn = 'background: #242424;border: 2px solid black !important;';
						$description = '<br><span style="color:red!important;font-weight:bold;">BOOKINGS NOT ACCEPTED FOR ' . $formattedDate . '.</span>';

						$html .= '<tr ' . $display_hidden . '>';
						$html .= '<td style="vertical-align: middle;padding: 20px;vertical-align: middle;' . $tb_bg . '"> <strong>' . $formattedDate . $description . '</strong></td>';
						$html .= '<td style="vertical-align: middle;' . $tb_bg . '"> <a href="javaScript:void(0);" onclick="serviceAvailabilitybook(this);" class="btn btn-primary availability-btn' . $isDisabled . '" data-date="' . $newDate . '" data-service-id="' . $serviceID . '"  data-availability="' . $BookingLimitPerDay . '" details-data="' . json_encode($details['data']) . '" style="' . $btn . '"> Availability (' . $BookingLimitPerDay . ')</a> </td>';
						$html .= '</tr>';
					} else if (strtotime($newDate) > strtotime(date('m/d/Y'))) {

						$html .= '<tr ' . $display_hidden . '>';
						$html .= '<td style="vertical-align: middle;padding: 20px;vertical-align: middle;' . $tb_bg . '"> <strong>' . $formattedDate . $description . '</strong></td>';
						$html .= '<td style="vertical-align: middle;' . $tb_bg . '"> <a href="javaScript:void(0);" onclick="serviceAvailabilitybook(this);" class="btn btn-primary availability-btn' . $isDisabled . '" data-date="' . $newDate . '" data-service-id="' . $serviceID . '"  data-availability="' . $BookingLimitPerDay . '" details-data="' . json_encode($details['data']) . '" style="' . $btn . '"> Availability (' . $BookingLimitPerDay . ')</a> </td>';
						$html .= '</tr>';
					}
				}
				$currentDate = strtotime("+1 day", $currentDate);
			}

			$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]);
						unset($cart_items['isServicePaid'][$key]);
						unset($cart_items['service_desc'][$key]);
						unset($cart_items['serviceOccurrencesNo'][$key]);
						unset($cart_items['oldServiceAmount'][$key]);
						unset($cart_items['discountedAmount'][$key]);
						unset($cart_items['fullPackage'][$key]);
						unset($cart_items['isDietySelected'][$key]);
						unset($cart_items['dietyName'][$key]);
						unset($cart_items['disclaimerText'][$key]);
					} else {
						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]);
						unset($cart_items['isServicePaid'][$key]);
						unset($cart_items['service_desc'][$key]);
						unset($cart_items['serviceOccurrencesNo'][$key]);
						unset($cart_items['oldServiceAmount'][$key]);
						unset($cart_items['discountedAmount'][$key]);
						unset($cart_items['fullPackage'][$key]);
						unset($cart_items['isDietySelected'][$key]);
						unset($cart_items['dietyName'][$key]);
						unset($cart_items['disclaimerText'][$key]);
					}
				} else {
					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]);
					unset($cart_items['isServicePaid'][$key]);
					unset($cart_items['service_desc'][$key]);
					unset($cart_items['serviceOccurrencesNo'][$key]);
					unset($cart_items['oldServiceAmount'][$key]);
					unset($cart_items['discountedAmount'][$key]);
					unset($cart_items['fullPackage'][$key]);
					unset($cart_items['isDietySelected'][$key]);
					unset($cart_items['dietyName'][$key]);
					unset($cart_items['disclaimerText'][$key]);
				}
				break;
			}
		}

		foreach ($cart_items as $cart_key => &$cart_value) {
			if ($cart_key != 'totalPrice') {
				if (is_array($cart_value)) {
					$cart_value = array_values($cart_value);
				}
			}
		}

		$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');
		$startDate = $this->input->post('startDate');
		$endDate = $this->input->post('endDate');
		$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'),
			'memberId' => $this->session->userdata('id'),
			'memberName' => $this->session->userdata('refDataName'),
			'prsnEmail' => $this->session->userdata('email'),
			'prsnPhone' => $this->session->userdata('phone')
		);


		$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);
	}
}
