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

class Dashboard extends MY_Controller
{

	public function __construct()
	{
		parent::__construct();


		if ($this->session->userdata('logged_in') != 1 &&  getUserDetails()->data[0]->memberTypes != 'DEVOTEE') {
			echo json_encode('User not found!!');
			$this->session->unset_userdata('logged_in');
			redirect(base_url());
		}
	}
	public function index()
	{

		$response = getUserDetails();
		if ($response->statusCode == 1) {
			$data['page'] = 'Dashboard';
			$data['title'] = 'Dashboard';
			$data['header'] = 'Dashboard';
			$data['paymentsCount'] = count(MyPayments()['payments_data']);
			$bookingCount = count(FilterBookingData('IN-TEMPLE')['booking_data']);
			$bookingCount += count(FilterBookingData('AWAY-TEMPLE')['booking_data']);
			$bookingCount += count(FilterBookingData('EVENTS')['booking_data']);
			$sponsorCount = count(FilterBookingData('SPONSORSHIP')['booking_data']);
			$facilityBookingCount = count(FilterBookingData('FACILITY')['booking_data']);
			$data['bookingCount'] = $bookingCount;
			$data['sponsorCount'] = $sponsorCount;
			$data['facilityBookingCount'] = $facilityBookingCount;
			$data['donationCount'] = count(MyDonations()['donations_data']);
			$data['recurringDonationCount'] = 0;
			$data['userDetails'] = $response->data[0];
			$this->load->view('admin/dashboard', $data);
		} else {
			echo json_encode('User not found!!');
			$this->session->unset_userdata('logged_in');
			redirect(base_url());
		}
	}

	public function getTithi()
	{

		$latitude = $this->input->post('latitude');
		$longitude = $this->input->post('longitude');
		$tzone = $this->input->post('tzone');
		$year = $this->input->post('year');
		$month = $this->input->post('month');
		$day = $this->input->post('day');
		$hour = $this->input->post('hour');
		$minute = $this->input->post('minute');

		$response = getPanchangamData($latitude, $longitude, $tzone, $year, $month, $day, $hour, $minute);
		echo json_encode($response);
	}

	public function getEventData()
	{

		$userName = $this->session->userdata('refDataName');

		$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\": {   
				\"moduleName\": \"Master Data Management\",  
				\"productID\": \"" . ApiBaseUrl()['productID'] . "\",   
				\"clientID\": \"" . ApiBaseUrl()['clientID'] . "\",       
				\"aspectType\": \"Annual Registration types\",     
				\"query\": {        
					\"aspectType\": \"Annual Registration types\"     
					},   
					\"userName\": \"" . $userName . "\",     
					\"skip\": 0,    
					\"next\": 1020    } }");

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

		// print_r($result);

		return	 $response = json_decode($result);



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

	public function MyAnnualEventsList()
	{

		$data['page'] = 'MY-ANNUAL-EVENTS';
		$data['title'] = 'MY-ANNUAL-EVENTS';
		$data['header'] = 'MY-ANNUAL-EVENTS';
		$data['EventData'] = $this->getEventData();
		$this->load->view('admin/my-annual-events', $data);
	}

	public function getAnnualEvent()
	{

		$filter = $this->input->post('selectedValue');
		$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);

		// Create an associative array to represent the data structure
		$data = array(
			"componentConfig" => array(
				"query" => array(
					"aspectType" => "annualRegistrations",
					"memberId" => $this->session->userdata('id')
				),
				"moduleName" => "Annual Registration",
				"aspectType" => "annualRegistrations",
				"refDataName" => $filter,
				"collectionType" => "Business",
				"productID" => ApiBaseUrl()['productID'],
				"clientID" => ApiBaseUrl()['clientID'],
				"userName" => $this->session->userdata('refDataName'),
				"skip" => 0,
				"next" => 220
			)
		);

		// echo '<pre>';
		// print_r($data);

		// print_r(getUserDetails());

		// die();

		$jsonData = json_encode($data);

		curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);

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

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

		usort($response->data, 'sortByTimestampDesc');

		$html = '';
		if ($response != '') {

			$annualEventData  = json_decode(json_encode($response->data), true);

			$html .= '<table id="myBookings" class="table table-hovered">';
			$html .= '<thead style="background-color: var(--devotee-table-header-bg); color: white;">';
			$html .= 			'<tr>';

			$html .= 				'<th class="text-center">#</th>';
			$html .= 				'<th class="text-center">Event&nbspDate/Time</th>';
			$html .= 				'<th class="text-center">Name&nbsp;Of&nbsp;Person</th>';
			$html .= 				'<th class="text-center">Event&nbsp;Location</th>';
			$html .= 				'<th class="text-center">Event&nbspType</th>';
			$html .=				'<th class="text-center">Tithi</th>';
			$html .=				'<th class="text-center">Status</th>';

			$html .= 			'</tr>';
			$html .=		'</thead>';
			$html .=		'<tbody>';
			foreach ($annualEventData as $key => $val) {


				$html .= '<tr><td class="text-center">' . ($key + 1) . '</td>';
				$html .= '<td class="text-center">' . $val['eventDate'] . ' ' . $val['eventTime'] . '</td>';
				$html .= '<td class="text-center">' . $val['nameOfPerson'] . '</td>';
				$html .= '<td class="text-center">' . $val['eventLocation'] . '</td>';
				$html .= '<td class="text-center">' . $val['refDataName'] . '</td>';
				$html .= '<td class="text-center">' . $val['tithi'] . '</td>';
				$html .= '<td class="text-center">' . $val['status'] . '</td></tr>';
			}
			$html .= 		'</tbody>';
			$html .= 	'</table>';

			echo $html;
		} else {
			echo $html;
		}
	}


	public function AddAnnualEventsPage()
	{

		$response = getUserDetails();
		if ($response->statusCode == 1) {
			$data['page'] = 'ADD-ANNUAL-EVENTS';
			$data['title'] = 'ADD-ANNUAL-EVENTS';
			$data['header'] = 'ADD-ANNUAL-EVENTS';
			$data['Events'] = $this->getEventData()->data;
			$data['userDetails'] = $response->data[0];
			$data['nakshtra_data'] = getNakshtra()['data'];
			$data['gotra_data'] = getGotra()['data'];
			$data['rashi_data'] = getRashi()['data'];
			$this->load->view('admin/add-annual-events', $data);
		} else {
			echo json_encode('User not found!!');
			$this->session->unset_userdata('logged_in');
			redirect(base_url());
		}
	}

	public function AddAnnualEvent()
	{
		$userName = $this->session->userdata('refDataName');

		$data['memberId'] = $this->session->userdata('id');
		$data['memberEmail'] = base64_decode($this->session->userdata('email'));
		$data['refDataName'] = $this->input->post('eventType');
		$data['eventDate'] = $this->input->post('eventDate');
		$data['eventTime'] = $this->input->post('eventTime');
		$data['eventLocation'] = $this->input->post('eventLocation');

		$data['latitude'] = $this->input->post('latitude');
		$data['longitude'] = $this->input->post('longitude');
		$data['dob'] = $this->input->post('dob');
		$data['nameOfPerson'] = $this->input->post('nameOfPerson');

		$data['eventNakshtra'] = $this->input->post('eventNakshtra');
		$data['eventGotra'] = $this->input->post('eventGotra');
		$data['tithi'] = $this->input->post('eventTithi');

		$data['startDate'] = $this->input->post('startDate');
		$data['endDate'] = $this->input->post('endDate');
		$data['status'] = 'ACTIVE';
		$data['reminderType'] = $this->input->post('reminderType');

		$data['beforeDayReminder'] = $this->input->post('beforeDayReminder');

		$data['isTithiReminder'] = $this->input->post('isTithiReminder') == 'on' ? true : false;
		$data['isEmailReminder'] = $this->input->post('isEmailReminder') == 'on' ? true : false;
		$data['isSmsReminder'] = $this->input->post('isSmsReminder') == 'on' ? true : false;

		$emailArray = array();
		$emailArray[] = base64_decode($this->session->userdata('email'));

		if (!empty($this->input->post('emailOnMember'))) {
			$emailArray[] = $this->input->post('emailOnMember');
		}

		$data['emailto'] = $emailArray;

		$dataJson = json_encode($data);

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

		curl_setopt($ch, CURLOPT_URL, ApiBaseUrl()['url'] . addAnnualRegistrations()['url']);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, "{    
			\"componentConfig\": {        
				\"moduleName\": \"" . addAnnualRegistrations()['moduleName'] . "\",        
				\"aspectType\": \"" . addAnnualRegistrations()['aspectType'] . "\",        
				\"productID\": \"" . ApiBaseUrl()['productID'] . "\",        
				\"clientID\": \"" . ApiBaseUrl()['clientID'] . "\",        
				\"userName\": \"" . $userName . "\"    
				},    
				\"dataJson\": " . $dataJson . "
			}");

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

		// print_r($response);
		// die();
		if ($response['statusCode'] == 1) {
			$this->session->set_flashdata('success', '<div class="alert alert-success alert-dismissible fade show text-center"><strong>Event Registeration Created Successful..</strong><button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button></div>');
			redirect(base_url('admin/my-annual-events'));
		} else {
			$this->session->set_flashdata('failure', '<div class="alert alert-danger alert-dismissible fade show text-center"><strong>Something went wrong please contact Adminstrator.</strong><button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button></div>');
			redirect(base_url('admin/my-annual-events'));
		}
	}






	public function FacilitiesBooking()
	{
		$data['page'] = 'MY-FACILITIES-BOOKINGS';
		$data['title'] = 'MY FACILITIES BOOKINGS';
		$data['header'] = 'MY FACILITIES BOOKINGS';

		$this->load->view('admin/my-facilities-bookings', $data);
	}

	public function filterFacilitiesBookingData()
	{

		$dateType = $this->input->post('dateType');
		$selecteddate = $this->input->post('selecteddate');
		$selectedenddate = @$this->input->post('selectedenddate');

		$data['page'] =  'MY-BOOKINGS';
		$data['header'] =  'MY BOOKINGS';

		$userName = $this->session->userdata('refDataName');
		$email = $this->session->userdata('email');

		if ($dateType == 'month') {
			$endDate = monthLastDate($selecteddate);
			$startDate = monthFirstDate($selecteddate);
		} else if ($dateType == 'year') {
			$endDate = "12/31/" . $selecteddate;
			$startDate = "01/01/" . $selecteddate;
		} else {
		$selecteddate = str_replace('-', '/', $this->input->post('selecteddate'));
			$selectedenddate = str_replace('-', '/', $this->input->post('selectedenddate'));

			$startDate = date('m/d/Y', strtotime($selecteddate));
			$endDate = date('m/d/Y', strtotime($selectedenddate));
		}

		$json_post_data = json_encode([
			"componentConfig" => [
				"moduleName" => "Calendar",
				"productID" => ApiBaseUrl()['productID'],
				"clientID" => ApiBaseUrl()['clientID'],
				"aspectType" => "Service Schedules",
				"query" => [
					"aspectType" => "Rental Request Form",
					"paymentStatus" => ['$in' => ["COMPLETED", "PENDING", "PARTIALLY_COMPLETED"]],
					"memberId" => $this->session->userdata('id'),
					"serviceCategoryTypes" => "FACILITIES",
					"cartCreDate" => [
						'$lte' => $endDate,
						'$gte' => $startDate
					]
				],
				"userName" => $userName,
				"skip" => 0,
				"next" => 1020
			]
		]);
		// var_dump($json_post_data);
		$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, $json_post_data);

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


		// print_r($response->data);

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

		curl_close($ch);
		$html = '';
		$html = '';
		if ($response && isset($response->data)) {

			usort($response->data, 'sortByTimestampDesc');
			$booking_data = json_decode(json_encode($response->data), true);


			$html .= '<table id="myBookings" class="table table-hovered">';
			$html .= '<thead class="my-table">';
			$html .= '<tr>';

			$html .= '<th>Receipt&nbsp;#</th>';
			$html .= '<th>Booking&nbsp;Date</th>';
			$html .= '<th class="service-name text-center">Facility Name</th>';
			$html .= '<th style="text-align:center">Amount</th>';
			$html .= '<th style="text-align:center;">Facility&nbsp;Date</th>';
			$html .= '<th style="text-align:center;">Start Time&nbsp;-&nbsp;End Time</th>';
			// $html .= '<th style="text-align:center;">Status</th>';
			// $html .= '<th style="text-align:center;">Cancel&nbsp;Booking</th>';
			$html .= '<th style="text-align:center;">Payment&nbsp;Status</th>';
			// $html .= '<th>View&nbsp;Receipt</th>';
			$html .= '</tr>';
			$html .= '</thead>';
			$html .= '<tbody>';

			foreach ($booking_data as $val) {
				// Check if 'statusName' exists; use 'status' otherwise
				$status = isset($val['status']) ? $val['status'] : (isset($val['statusName']) ? $val['statusName'] : 'N/A');

				if ($status == 'SCHEDULED') {
					$status = '<a href="javascript:void(0)" onclick="show_booking_status(`' . camelCase($val['ServiceSetup']) . '` ,`' . $val['status'] . '`)"><img src="' . base_url('admin_assets/img/icons/booking-confirmed-icon.png') . '" height="35" width="35" style="vertical-align: middle!important;"></a>';
				} else {
					$status = '<span class="badge">' . camelCase($status) . '</span>';
				}
				$paymentStatus = $val['paymentStatus'] == 'COMPLETED' ? 'PAID' : 'UNPAID';
				$html .= '<tr>';
				$html .= '<td>';
				$html .= isset($val['tokenNumber']) ? $val['tokenNumber'] : '';
				$html .= '</td><td>' . $val['recCreDate'] . '</td>';
				$html .= '<td class="text-center">' . camelCase($val['ServiceSetup']) . '</td>';
				$html .= '<td style="text-align:center;padding-right:25px">$ ' . sprintf("%.2f", $val['serviceAmount']) . '</td>';
				$html .= '<td style="text-align:center;">' . $val['serviceDate'] . '</td>';
				$html .= '<td>' . $val['startTime'];
				if (isset($val['endTime']) && !empty($val['endTime'])) {
					$html .= ' - ' . @$val['endTime'];
				}
				$html .= '</td>';
				// $html .= '<td style="text-align:center;">' . $status . '</td>';
				// $html .= '<td style="text-align:center;"><a href="javascript:void(0)" onclick="CancelBooking(' . "'" . trim($val['_id']) . "'" . ')"><img src="' . base_url('admin_assets/img/icons/booking-cancel-icon.png') . '" height="35" width="35" style="vertical-align: middle!important;"></a></td>';
				$html .= '<td style="text-align:center;">' . $paymentStatus . '</td>';
				// $html .= '<td><a href="' . base_url("admin/download-reciept/" . base64_encode($val["tokenNumber"]) . "/" . $serviceCategoryTypes) . '" id="btnExport" target="_blank"><i class="fa fa-eye text-blue" style="font-size:22px"></i></a></td>';

				$html .= '</tr>';
			}

			$html .= '</tbody>';
			$html .= '</table>';
			$html .= '</div>';

			echo $html;
		} else {
			echo $html;
		}
	}

	public function In_Temple_Bookings()
	{
		$data['page'] = 'MY-BOOKINGS';
		$data['title'] = 'MY BOOKINGS';
		$data['header'] = 'MY BOOKINGS';
		$data['myServiceRequestCount'] = count(myServiceRequest()['myServiceRequests_data']);

		$this->load->view('admin/my-bookings', $data);
	}

	public function FilterBookingData()
	{
		$serviceCategoryTypes = $this->input->post('aspectType');
		$dateType = $this->input->post('dateType');
		$selecteddate = $this->input->post('selecteddate');
		$selectedenddate = @$this->input->post('selectedenddate');
		$data['page'] = 'MY-BOOKINGS';
		$data['header'] = 'MY BOOKINGS';

		$userName = $this->session->userdata('refDataName');
		$email = $this->session->userdata('email');
		if ($dateType == 'month') {
			$endDate = monthLastDate($selecteddate);
			$startDate = monthFirstDate($selecteddate);
		} else if ($dateType == 'year') {
			$endDate = "12/31/" . $selecteddate;
			$startDate = "01/01/" . $selecteddate;
		} else {
			// echo $endDate = date('m/d/Y', strtotime($selectedenddate));
			// echo $startDate = date('m/d/Y', strtotime($selecteddate));

			$selecteddate = str_replace('-', '/', $this->input->post('selecteddate'));
			$selectedenddate = str_replace('-', '/', $this->input->post('selectedenddate'));

			$startDate = date('m/d/Y', strtotime($selecteddate));
			$endDate = date('m/d/Y', strtotime($selectedenddate));
		}
		if ($serviceCategoryTypes == 'ALL') {

			$json_post_data = json_encode([
				"componentConfig" => [
					"moduleName" => "Calendar",
					"productID" => ApiBaseUrl()['productID'],
					"clientID" => ApiBaseUrl()['clientID'],
					"aspectType" => "Service Schedules",
					"query" => [
						"aspectType" => "serviceBooking",
						"serviceCategoryTypes" => ['$nin' => ["TEMPLE SHOP", "DAILY ORDERS","CATERING ORDERS"]],
						'$or' => [
							["paymentStatus" => ['$in' => ["COMPLETED", "PENDING"]]],
							["paymentStatus" => "INITIATED", "serviceStatus" => "SCHEDULED"]
						],
						"memberId" => $this->session->userdata('id'),
						"cartCreDate" => [
							'$lte' => $endDate,
							'$gte' => $startDate
						]
					],
					"userName" => $userName,
					"skip" => 0,
					"next" => 1020
				]
			]);
		} else if ($serviceCategoryTypes == 'FACILITY') {
			$json_post_data = json_encode([
				"componentConfig" => [
					"moduleName" => "Calendar",
					"productID" => ApiBaseUrl()['productID'],
					"clientID" => ApiBaseUrl()['clientID'],
					"aspectType" => "Service Schedules",
					"query" => [
						"aspectType" => "Rental Request Form",
						"paymentStatus" => ['$in' => ["COMPLETED", "PENDING", "PARTIALLY_COMPLETED"]],
						"memberId" => $this->session->userdata('id'),
						"serviceCategoryTypes" => "FACILITIES",
						"cartCreDate" => [
							'$lte' => $endDate,
							'$gte' => $startDate
						]
					],
					"userName" => $userName,
					"skip" => 0,
					"next" => 1020
				]
			]);
		} else {
			$json_post_data = json_encode([
				"componentConfig" => [
					"moduleName" => "Calendar",
					"productID" => ApiBaseUrl()['productID'],
					"clientID" => ApiBaseUrl()['clientID'],
					"aspectType" => "Service Schedules",
					"query" => [
						"aspectType" => "serviceBooking",
						'$or' => [
							["paymentStatus" => ['$in' => ["COMPLETED", "PENDING"]]],
							["paymentStatus" => "INITIATED", "serviceStatus" => "SCHEDULED"]
						],
						"memberId" => $this->session->userdata('id'),
						"serviceCategoryTypes" => $serviceCategoryTypes,
						"cartCreDate" => [
							'$lte' => $endDate,
							'$gte' => $startDate
						]
					],
					"userName" => $userName,
					"skip" => 0,
					"next" => 1020
				]
			]);
		}
		// echo $json_post_data;
		$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, $json_post_data);

		$token = $this->session->userdata('token');
		$headers = [
			'Authorization: Bearer ' . $token,
			'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);

		$html = '';
		if ($response && isset($response->data)) {

			usort($response->data, 'sortByTimestampDesc');
			$booking_data = json_decode(json_encode($response->data), true);
			// echo "<pre>";
			// var_dump($booking_data);
			// die();
			if ($serviceCategoryTypes == 'FACILITY') {
				/*$html .= '<table id="myBookings" class="table table-hovered">';
				$html .= '<thead class="my-table">';
				$html .= '<tr>';

				$html .= '<th>Details</th>';
				$html .= '<th>Receipt&nbsp;#</th>';
				$html .= '<th>Booking&nbsp;Date</th>';
				$html .= '<th class="service-name text-center">Service Name</th>';
				$html .= '<th style="text-align:center">Amount</th>';
				$html .= '<th style="text-align:center;">Service&nbsp;Date</th>';
				// $html .= '<th style="text-align:center;">Status</th>';
				// $html .= '<th style="text-align:center;">Cancel&nbsp;Booking</th>';
				$html .= '<th style="text-align:center;">Payment&nbsp;Status</th>';
				// $html .= '<th>View&nbsp;Receipt</th>';
				$html .= '</tr>';
				$html .= '</thead>';
				$html .= '<tbody>';

				foreach ($booking_data as $val) {
					// Check if 'statusName' exists; use 'status' otherwise
					$status = isset($val['status']) ? $val['status'] : (isset($val['statusName']) ? $val['statusName'] : 'N/A');

					if ($status == 'SCHEDULED') {
						$status = '<a href="javaScript:void(0)" onclick="show_booking_status(`' . camelCase($val['ServiceSetup']) . '` ,`' . $val['status'] . '`)"><img src="' . base_url('admin_assets/img/icons/booking-confirmed-icon.png') . '" height="35" width="35" style="vertical-align: middle!important;"></a>';
					} else {
						$status = '<span class="badge">' . camelCase($status) . '</span>';
					}
					$paymentStatus = $val['paymentStatus'] == 'COMPLETED' ? 'PAID' : 'UNPAID';
					$html .= '<tr>';
					$html .= '<td><a class="toggle-details" style="cursor:pointer;" onclick="toggleChildRows(this)">Veiw Details</a></td>';
					$html .= '<td>';
					$html .= isset($val['tokenNumber']) ? $val['tokenNumber'] : '';
					$html .= '</td><td>' . $val['recCreDate'] . '</td>';
					$html .= '<td class="text-center">' . camelCase($val['ServiceSetup']) . '</td>';
					$html .= '<td style="text-align:center;padding-right:25px">$ ' . sprintf("%.2f", $val['serviceAmount']) . '</td>';
					$html .= '<td style="text-align:center;">' . $val['serviceDate'] . '</td>';
					// $html .= '<td style="text-align:center;">' . $status . '</td>';
					// $html .= '<td style="text-align:center;"><a href="javaScript:void(0)" onclick="CancelBooking(' . "'" . trim($val['_id']) . "'" . ')"><img src="' . base_url('admin_assets/img/icons/booking-cancel-icon.png') . '" height="35" width="35" style="vertical-align: middle!important;"></a></td>';
					$html .= '<td style="text-align:center;">' . $paymentStatus . '</td>';
					// $html .= '<td><a href="' . base_url("admin/download-reciept/" . base64_encode($val["tokenNumber"]) . "/" . $serviceCategoryTypes) . '" id="btnExport" target="_blank"><i class="fa fa-eye text-blue" style="font-size:22px"></i></a></td>';

					$html .= '</tr>';

					$html .= '<tr class="child-row" style="display: none;">
        			<td colspan="2">Details for Row 1</td>
        			<td colspan="2">Details for Row 1</td>
        			<td colspan="2">Details for Row 1</td>
        			<td colspan="2">Details for Row 1</td>
        			<td colspan="2">Details for Row 1</td>
        			<td colspan="2">Details for Row 1</td>
        			<td colspan="2">Details for Row 1</td>
    				</tr>';*/

				$html .= '<table id="myBookings" class="table table-hovered">';
				$html .= '<thead class="my-table">';
				$html .= '<tr>';

				$html .= '<th>Receipt&nbsp;#</th>';
				$html .= '<th>Booking&nbsp;Date</th>';
				$html .= '<th class="service-name text-center">Facility Name</th>';
				$html .= '<th style="text-align:center">Amount</th>';
				$html .= '<th style="text-align:center;">Facility&nbsp;Date</th>';
				$html .= '<th style="text-align:center;">Start Time&nbsp;-&nbsp;End Time</th>';
				// $html .= '<th style="text-align:center;">Status</th>';
				// $html .= '<th style="text-align:center;">Cancel&nbsp;Booking</th>';
				$html .= '<th style="text-align:center;">Payment&nbsp;Status</th>';
				// $html .= '<th>View&nbsp;Receipt</th>';
				$html .= '</tr>';
				$html .= '</thead>';
				$html .= '<tbody>';

				foreach ($booking_data as $val) {
					// Check if 'statusName' exists; use 'status' otherwise
					$status = isset($val['status']) ? $val['status'] : (isset($val['statusName']) ? $val['statusName'] : 'N/A');

					if ($status == 'SCHEDULED') {
						$status = '<a href="javaScript:void(0)" onclick="show_booking_status(`' . camelCase($val['ServiceSetup']) . '` ,`' . $val['status'] . '`)"><img src="' . base_url('admin_assets/img/icons/booking-confirmed-icon.png') . '" height="35" width="35" style="vertical-align: middle!important;"></a>';
					} else {
						$status = '<span class="badge">' . camelCase($status) . '</span>';
					}
					$paymentStatus = $val['paymentStatus'] == 'COMPLETED' ? 'PAID' : 'UNPAID';
					$html .= '<tr>';
					$html .= '<td>';
					$html .= isset($val['tokenNumber']) ? $val['tokenNumber'] : '';
					$html .= '</td><td>' . $val['recCreDate'] . '</td>';
					$html .= '<td class="text-center">' . camelCase($val['ServiceSetup']) . '</td>';
					$html .= '<td style="text-align:center;padding-right:25px">$ ' . sprintf("%.2f", $val['serviceAmount']) . '</td>';
					$html .= '<td style="text-align:center;">' . $val['serviceDate'] . '</td>';
					$html .= '<td>' . $val['startTime'] . ' - ' . $val['endTime'] . '</td>';
					// $html .= '<td style="text-align:center;">' . $status . '</td>';
					// $html .= '<td style="text-align:center;"><a href="javaScript:void(0)" onclick="CancelBooking(' . "'" . trim($val['_id']) . "'" . ')"><img src="' . base_url('admin_assets/img/icons/booking-cancel-icon.png') . '" height="35" width="35" style="vertical-align: middle!important;"></a></td>';
					$html .= '<td style="text-align:center;">' . $paymentStatus . '</td>';
					// $html .= '<td><a href="' . base_url("admin/download-reciept/" . base64_encode($val["tokenNumber"]) . "/" . $serviceCategoryTypes) . '" id="btnExport" target="_blank"><i class="fa fa-eye text-blue" style="font-size:22px"></i></a></td>';

					$html .= '</tr>';
				}
			} else {
				$html .= '<table id="myBookings" class="table table-hovered">';
				$html .= '<thead class="my-table">';
				$html .= '<tr>';

				$html .= '<th>Receipt&nbsp;#</th>';
				$html .= '<th>Booking&nbsp;Date</th>';
				$html .= '<th class="service-name text-center">Service Name</th>';
				$html .= '<th style="text-align:center">Amount</th>';
				$html .= '<th style="text-align:center;">Service&nbsp;Date</th>';
				// $html .= '<th style="text-align:center;">Status</th>';
				// $html .= '<th style="text-align:center;">Cancel&nbsp;Booking</th>';
				$html .= '<th style="text-align:center;">Payment&nbsp;Status</th>';
				// $html .= '<th>View&nbsp;Receipt</th>';
				$html .= '</tr>';
				$html .= '</thead>';
				$html .= '<tbody>';

				foreach ($booking_data as $val) {
					// Check if 'statusName' exists; use 'status' otherwise
					$status = isset($val['status']) ? $val['status'] : (isset($val['statusName']) ? $val['statusName'] : 'N/A');
					if (isset($val['fullPackage']) && $val['fullPackage'] == "true") {
						$serviceAmount = sprintf("%.2f", $val['serviceAmount'] * $val['serviceOccurrencesNo']);
					} else {
						$serviceAmount = sprintf("%.2f", $val['serviceAmount']);
					}
					if ($status == 'SCHEDULED') {
						$status = '<a href="javaScript:void(0)" onclick="show_booking_status(`' . camelCase($val['ServiceSetup']) . '` ,`' . $val['status'] . '`)"><img src="' . base_url('admin_assets/img/icons/booking-confirmed-icon.png') . '" height="35" width="35" style="vertical-align: middle!important;"></a>';
					} else {
						$status = '<span class="badge">' . camelCase($status) . '</span>';
					}
					$paymentStatus = $val['paymentStatus'] == 'COMPLETED' ? 'PAID' : 'UNPAID';
					$html .= '<tr>';
					$html .= '<td>';
					$html .= isset($val['tokenNumber']) ? $val['tokenNumber'] : '';
					$html .= '</td><td>' . $val['recCreDate'] . '</td>';
					$html .= '<td class="text-center">' . camelCase($val['ServiceSetup']) . '</td>';
					$html .= '<td style="text-align:center;padding-right:25px">$ ' . $serviceAmount . '</td>';
					$html .= '<td style="text-align:center;">' . $val['serviceDate'] . '</td>';
					// $html .= '<td style="text-align:center;">' . $status . '</td>';
					// $html .= '<td style="text-align:center;"><a href="javaScript:void(0)" onclick="CancelBooking(' . "'" . trim($val['_id']) . "'" . ')"><img src="' . base_url('admin_assets/img/icons/booking-cancel-icon.png') . '" height="35" width="35" style="vertical-align: middle!important;"></a></td>';
					$html .= '<td style="text-align:center;">' . $paymentStatus . '</td>';
					// $html .= '<td><a href="' . base_url("admin/download-reciept/" . base64_encode($val["tokenNumber"]) . "/" . $serviceCategoryTypes) . '" id="btnExport" target="_blank"><i class="fa fa-eye text-blue" style="font-size:22px"></i></a></td>';

					$html .= '</tr>';
				}
			}
			$html .= '</tbody>';
			$html .= '</table>';

			echo $html;
		} else {
			echo $html;
		}
	}


	public function MyOrders()
	{
		$data['page'] = 'MY-ORDERS';
		$data['title'] = 'MY ORDERS';
		$data['header'] = 'MY ORDERS';

		$this->load->view('admin/my-orders', $data);
	}

	public function filterOrderData()
	{
		$serviceCategoryTypes = $this->input->post('aspectType');
		$dateType = $this->input->post('dateType');
		$selecteddate = $this->input->post('selecteddate');
		$data['page'] = 'MY-ORDERS';
		$data['header'] = 'MY ORDERS';

		$userName = $this->session->userdata('refDataName');
		$email = $this->session->userdata('email');
		if ($dateType == 'month') {
			$endDate = monthLastDate($selecteddate);
			$startDate = monthFirstDate($selecteddate);
		} else if ($dateType == 'year') {
			$endDate = "12/31/" . $selecteddate;
			$startDate = "01/01/" . $selecteddate;
		} else {
			// $endDate = date('m/d/Y', strtotime($selecteddate));
			// $startDate = date('m/d/Y', strtotime($selecteddate));
			$selecteddate = str_replace('-', '/', $this->input->post('selecteddate'));
			$selectedenddate = str_replace('-', '/', $this->input->post('selectedenddate'));

			 $startDate = date('m/d/Y', strtotime($selecteddate));
			 $endDate = date('m/d/Y', strtotime($selectedenddate));
		}


		$json_post_data = json_encode([
			"componentConfig" => [
				"moduleName" => "Calendar",
				"productID" => ApiBaseUrl()['productID'],
				"clientID" => ApiBaseUrl()['clientID'],
				"aspectType" => "Service Schedules",
				"query" => [
					"aspectType" => "serviceBooking",
					// "serviceTypes" => "BOOKS",
					"serviceCategoryTypes" => ['$in' => ["TEMPLE SHOP", "DAILY ORDERS","CATERING ORDERS"]],
					'$or' => [
						["paymentStatus" => ['$in' => ["COMPLETED", "PENDING"]]]
					],
					"memberId" => $this->session->userdata('id'),
					"cartCreDate" => [
						'$lte' => $endDate,
						'$gte' => $startDate
					]
				],
				"userName" => $userName,
				"skip" => 0,
				"next" => 1020
			]
		]);

		// echo $json_post_data;
		$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, $json_post_data);

		$token = $this->session->userdata('token');
		$headers = [
			'Authorization: Bearer ' . $token,
			'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);

		$html = '';
		if ($response && isset($response->data)) {

			usort($response->data, 'sortByTimestampDesc');
			$booking_data = json_decode(json_encode($response->data), true);
		
				$html .= '<table id="myBookings" class="table table-hovered">';
				$html .= '<thead class="my-table">';
				$html .= '<tr>';

				$html .= '<th>Receipt&nbsp;#</th>';
				$html .= '<th>Booking&nbsp;Date</th>';
				$html .= '<th class="service-name text-center">Service Name</th>';
				$html .= '<th style="text-align:center">Amount</th>';
				$html .= '<th style="text-align:center;">Payment&nbsp;Status</th>';
				$html .= '</tr>';
				$html .= '</thead>';
				$html .= '<tbody>';

				foreach ($booking_data as $val) {
					// Check if 'statusName' exists; use 'status' otherwise
					$status = isset($val['status']) ? $val['status'] : (isset($val['statusName']) ? $val['statusName'] : 'N/A');
					if (isset($val['fullPackage']) && $val['fullPackage'] == "true") {
						$serviceAmount = sprintf("%.2f", $val['serviceAmount'] * $val['serviceOccurrencesNo']);
					} else {
						$serviceAmount = sprintf("%.2f", $val['serviceAmount']);
					}
					if ($status == 'SCHEDULED') {
						$status = '<a href="javaScript:void(0)" onclick="show_booking_status(`' . camelCase($val['ServiceSetup']) . '` ,`' . $val['status'] . '`)"><img src="' . base_url('admin_assets/img/icons/booking-confirmed-icon.png') . '" height="35" width="35" style="vertical-align: middle!important;"></a>';
					} else {
						$status = '<span class="badge">' . camelCase($status) . '</span>';
					}
					$paymentStatus = $val['paymentStatus'] == 'COMPLETED' ? 'PAID' : 'UNPAID';
					$html .= '<tr>';
					$html .= '<td>';
					$html .= isset($val['tokenNumber']) ? $val['tokenNumber'] : '';
					$html .= '</td><td>' . $val['recCreDate'] . '</td>';
					$html .= '<td class="text-center">' . camelCase($val['ServiceSetup']) . '</td>';
					$html .= '<td style="text-align:center;padding-right:25px">$ ' . $serviceAmount . '</td>';
					$html .= '<td style="text-align:center;">' . $paymentStatus . '</td>';
					// $html .= '<td><a href="' . base_url("admin/download-reciept/" . base64_encode($val["tokenNumber"]) . "/" . $serviceCategoryTypes) . '" id="btnExport" target="_blank"><i class="fa fa-eye text-blue" style="font-size:22px"></i></a></td>';

					$html .= '</tr>';
				}
			
			$html .= '</tbody>';
			$html .= '</table>';

			echo $html;
		} else {
			echo $html;
		}
	}


	public function MyDonations()
	{
		$data['page'] = 'MY-DONATIONS';
		$data['title'] = 'MY DONATIONS';
		$data['header'] = 'MY DONATIONS';

		$this->load->view('admin/my-donations', $data);
	}

	public function FilterDonationData()
	{
		$dateType = $this->input->post('dateType');
		$selecteddate = $this->input->post('selecteddate');



		$userName = $this->session->userdata('refDataName');
		$email = $this->session->userdata('email');

		if ($dateType == 'month') {
			$endDate = monthLastDate($selecteddate);
			$startDate = monthFirstDate($selecteddate);
		} else if ($dateType == 'year') {
			$endDate = "12/31/" . $selecteddate;
			$startDate = "01/01/" . $selecteddate;
		} else {
			// $endDate = date('m/d/Y', strtotime($selecteddate));
			// $startDate = date('m/d/Y', strtotime($selecteddate));
			$selecteddate = str_replace('-', '/', $this->input->post('selecteddate'));
			$selectedenddate = str_replace('-', '/', $this->input->post('selectedenddate'));

			$startDate = date('m/d/Y', strtotime($selecteddate));
			$endDate = date('m/d/Y', strtotime($selectedenddate));
		}
		// echo $json_post_data;die();
		$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);

		// Create an associative array to represent the data structure
		$postdata = array(
			"componentConfig" => array(
				"moduleName" => "Calendar",
				"productID" => ApiBaseUrl()['productID'],
				"clientID" => ApiBaseUrl()['clientID'],
				"aspectType" => "Service Schedules",
				"query" => array(
					"aspectType" => "serviceBooking",
					"paymentStatus" => "COMPLETED",
					"memberId" => $this->session->userdata('id'),
					"serviceCategoryTypes" => "DONATIONS",
					"cartCreDate" => [
						'$lte' => $endDate,
						'$gte' => $startDate
					]
				),
				"userName" => $userName,
				"skip" => 0,
				"next" => 1020
			)
		);

		$jsonData = json_encode($postdata);

		curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);


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

		usort($response->data, 'sortByTimestampDesc');


		$html = '';
		$html .= '<table id="myDonations" class="table table-hovered bg-white">
			<thead style="background-color: var(--devotee-table-header-bg); color: white;">
				<tr>
					<th>Receipt&nbsp;#</th>
					<th class="text-center">Booking&nbsp;Date</th>

					<th class="text-center service-name">Donation&nbsp;Name</th>
					<th class="text-end">Amount</th>
					<th class="text-center">Service&nbsp;Date</th>
					<th class="text-center">Payment&nbsp;Status</th>

				</tr>
			</thead>
			<tbody>';
		if ($response && isset($response->data)) {


			$booking_data = json_decode(json_encode($response->data), true);


			foreach ($booking_data as $val) {



				$html .= '	<tr>
						<td class="text-start">' . $val['tokenNumber'] . '</td>
						<td class="text-center">' . $val['recCreDate'] . '</td>

						<td class="text-center">' . camelCase($val['ServiceSetup']) . '</td>
						<td class="text-end">' . '$' . sprintf("%.2f", $val['serviceAmount']) . '</td>
						<td class="text-center">
							';
				$html .= $val['recCreDate'] ?	$val['recCreDate'] : '';
				$html .= '

						</td>
						<td class="text-center">' . camelCase($val['paymentType']) . '</td>
						

					</tr>';
			}
		}
		$html .= '	</tbody>
		</table>';

		echo $html;
	}

	public function MyProfile()
	{

		$response = getUserDetails();
		if ($response->statusCode == 1) {
			$data['page'] = 'MY-PROFILE';
			$data['title'] = 'MY PROFILE';
			$data['header'] = 'MY PROFILE';
			$data['userDetails'] = $response->data[0];


			if ($this->session->userdata('userType') == 'Managements') {
				$this->load->view('admin/managements/my-profile', $data);
			} else {
				$this->load->view('admin/my-profile', $data);
			}
		} else {
			echo json_encode('User not found!!');
			$this->session->unset_userdata('logged_in');
			redirect(base_url());
		}
	}
	public function GetCity()
	{
		$stateName = $this->input->post('stateCode');
		GetCity($stateName);
	}

	public function EditProfile()
	{
		$data['page'] = 'MY-PROFILE';
		$data['title'] = 'MY PROFILE';
		$data['header'] = 'EDIT PROFILE';
		$data['GetState'] = GetState();
		$data['userDetails'] = getUserDetails()->data[0];


		// print_r(getUserDetails());



		$data['preferredLanguage'] = getPreferredLanguage();
		$data['priest_data'] = getPriest();

		// print_r($data['priest_data']); die();


		$data['nakshtra_data'] = getNakshtra()['data'];
		$data['gotra_data'] = getGotra()['data'];
		$data['rashi_data'] = getRashi()['data'];

		$this->load->view('admin/edit-profile', $data);
	}


	public function UpdateProfile()
	{



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


		$inputArray = array();

		$member_phone_plain = '';
		$member_email_plain = '';
		foreach ($post_data['family_member_name'] as $key => $family_member_name) {
			$newEntry = new stdClass();
			$newEntry->memberName = $family_member_name;
			$newEntry->dob = $post_data['dateofbirth'][$key];
			$newEntry->nakshatra = @strtoupper($post_data['family_member_stars'][$key]);
			$newEntry->status = isset($post_data['family_member_status'][$key]) ? $post_data['family_member_status'][$key] : '';
			$newEntry->relationship = $post_data['relationship'][$key];
			$newEntry->anniversaryDate = isset($post_data['anniversary'][$key]) ? $post_data['anniversary'][$key] : '';
			$newEntry->gotraName = $post_data['family_member_gotraName'][$key];
			$newEntry->householdInd = isset($post_data['member_household_indicator'][$key]) ? $post_data['member_household_indicator'][$key] : '';
			$newEntry->member_email = isset($post_data['member_email'][$key]) && $post_data['member_email'][$key] != '' ? base64_encode($post_data['member_email'][$key]) : '';
			$newEntry->member_phone = isset($post_data['member_phone'][$key]) && $post_data['member_phone'][$key] != '' ? base64_encode(str_replace([' ', '(', ')', '-'], '', $post_data['member_phone'][$key])) : '';

			$inputArray[] = $newEntry;
		}
		// var_dump($post_data);die();




		foreach ($inputArray as $item) {
			// Check if any of the fields in the object are empty
			if (!empty($item->memberName)) {
				$jsonArray[] = $item;
			}
		}




		$userName = $this->session->userdata('refDataName');

		$fname = $this->input->post('fname');
		$lname = $this->input->post('lname');
		$gothram = strtoupper($this->input->post('gothram'));

		$main_email = $this->input->post('main_email');
		$main_email = $main_email != '' ? base64_encode($main_email) : '';

		$main_phone = $this->input->post('main_phone');
		$main_phone = $main_phone != '' ? base64_encode(str_replace([' ', '(', ')', '-'], '', $main_phone)) : '';

		$stars = strtoupper($this->input->post('stars'));
		$rashi = strtoupper($this->input->post('rashi'));
		$county = $this->input->post('county');
		$address_line1 = $this->input->post('address_line1');
		$address_line2 = $this->input->post('address_line2');

		$spouseName = $this->input->post('spouseName');
		$spouseDob = $this->input->post('spousedateofbirth');
		$spousePhone = $this->input->post('spousePhone');
		$preferredLanguage = $this->input->post('preferredLanguage');
		$spouseEmail = $this->input->post('spouseEmail');
		$spouseGothram = strtoupper($this->input->post('spouseGothram'));
		$spouseStars = strtoupper($this->input->post('spouseStars'));
		$spouseRashi = strtoupper($this->input->post('spouseRashi'));
		$spouse_household_indicator = $this->input->post('household_indicator');


		$spouse_household_indicator_final = (is_array($spouse_household_indicator) && $spouse_household_indicator[0] == "YES") || $spouse_household_indicator == 'YES' ? 'YES' : 'NO';


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


		$priestName = $this->input->post('priestName');
		$priestEmail = $this->input->post('priestEmail');
		$priestEmail  = $priestEmail != '' ? base64_encode($priestEmail) : '';
		$priestPhone = $this->input->post('priestPhone');
		$priestPhone  = $priestPhone != '' ? base64_encode($priestPhone) : '';
		$priestId = $this->input->post('priestId');

		$email = base64_encode($this->input->post('main_email'));

		$phone = $this->input->post('main_phone');

		$phone = base64_encode(str_replace([' ', '(', ')', '-'], '', $phone));

		$full_address = $this->input->post('full_address');
		$state = $this->input->post('state');
		$city = strtoupper($this->input->post('city'));

		if ($city) {
			$city = strtoupper($city);
		}
		$zipcode = $this->input->post('zipcode');
		$company_name = $this->input->post('company_name');
		$company_email = $this->input->post('company_email');
		$company_phone = $this->input->post('company_phone');

		$company_phone = str_replace([' ', '(', ')', '-'], '', $company_phone);


		$company_website = $this->input->post('company_website');
		$Id = $this->session->userdata('id');

		$emailNoti = $this->input->post('emailNotification');
		$phoneSms = $this->input->post('phoneNotification');
		$phoneCallPref = $this->input->post('phoneCallPref');

		$emailSubscription = $emailNoti == 'on' ? 'true' : 'false';
		$phoneSubscription = $phoneSms == 'on' ? 'true' : 'false';
		$phoneCallSubscription = $phoneCallPref == 'on' ? 'true' : 'false';



		$moduleName = customerLogin()['moduleName'];

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


		$post_json_data = [
			"_id" => $Id,
			"dataJson" => [
				"refDataName" => $fname . " " . $lname,
				"firstName" => $fname,
				"lastName" => $lname,
				"email" => $main_email,
				"zip" => $zipcode,
				"phone" => $main_phone,
				"cityTypes" => $city,
				"stateTypes" => $state,
				"addressLine1" => $address_line1,
				"addressLine2" => $address_line2,
				"county" => $county,
				"rashi" => $rashi,
				"gotraName" => strtoupper($gothram),
				"Nakshtra" => $stars,

				"spouseName" => $spouseName,
				"spouseDob" => $spouseDob,
				"spousePhone" => base64_encode($spousePhone),
				"spouseEmail" => base64_encode($spouseEmail),
				"spouseGotra" => $spouseGothram,
				"spouseNakshtra" => $spouseStars,
				"householdInd" => $spouse_household_indicator_final,
				"spouseRashi" => $spouseRashi,
				"dob" => $dob,
				"languagePreferenceName" => $preferredLanguage,

				"requestForPriestName" => $priestName,
				"priestEmail" => $priestEmail,
				"priestPhone" => $priestPhone,
				"requestedPriestId" => $priestId,

				"companyName" => $company_name,
				"companyEmail" => base64_encode($company_email),
				"companyPhone" => base64_encode($company_phone),
				"website" => $company_website,
				"emailPref" => $emailSubscription,
				"smsPref" => $phoneSubscription,
				"phoneCallPref" => $phoneCallSubscription,
				"memberDetail" => $jsonArray,
			],
			"componentConfig" => [
				"moduleName" => "Contacts",
				"productID" => ApiBaseUrl()['productID'],
				"clientID" => ApiBaseUrl()['clientID'],
				"userName" => $userName
			]
		];

		$payload = json_encode($post_json_data);

		// var_dump($post_json_data);die();

		curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);



		$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->set_flashdata('success', '<div class="alert alert-success alert-dismissible fade show text-center"><strong>Updated!</strong> Your profile has been updated.<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button></div>');
			redirect(base_url('admin/my-profile'));
		} else {
			$data['page'] = 'MY-PROFILE';
			$data['title'] = 'MY PROFILE';
			$data['header'] = 'EDIT PROFILE';
			$data['GetState'] = GetState();
			$data['userDetails'] = getUserDetails()->data[0];
			$data['preferredLanguage'] = getPreferredLanguage();
			$this->session->set_flashdata('success', '<div class="alert alert-danger alert-dismissible fade show text-center"><strong>Error!</strong> Something Went Wrong.<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button></div>');
			$this->load->view('admin/edit-profile', $data);
		}
	}


	public function participants()
	{
		$data['page'] = 'PARTICIPANTS';
		$data['title'] = 'Participants';
		$data['header'] = 'Participants';

		// Get logged in user's ID
		$userId = $this->session->userdata('id'); // Changed to match your session key

		// === First API: Get Event List ===
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

		$url = ApiBaseUrl()['url'] . 'api/puja/getParticipateEventList';
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POST, 1);

		// Get current date in required format
		$currentDate = date('Y-m-d');

		$postData = json_encode([
			"dataJson" => [
				"startDate" => $currentDate,
				"endDate" => $currentDate,
				"memberId" => $this->session->userdata('id')
			],
			"clientId" => ApiBaseUrl()['clientID']
		]);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

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

		$result = curl_exec($ch);

		if (curl_errno($ch)) {
			show_error('API Error: ' . curl_error($ch));
		}

		$response = json_decode($result, false);
		curl_close($ch);

		$fullDetails = [];

		if ($response && isset($response->statusCode) && $response->statusCode == 1) {
			$participants = $response->data;

			foreach ($participants as $participant) {
				$memberId = $participant->memberId ?? null;
				$eventId = $participant->eventId ?? null;
				$pujaId = $participant->pujaId ?? $eventId; // Add pujaId mapping

				if ($memberId && $eventId) {
					// Get participation details for this event
					$detailData = [
						"dataJson" => [
							"memberId" => $memberId,
							"eventId" => $eventId
						],
						"clientId" => ApiBaseUrl()['clientID']
					];

					$chDetail = curl_init();
					curl_setopt($chDetail, CURLOPT_SSL_VERIFYHOST, 0);
					curl_setopt($chDetail, CURLOPT_SSL_VERIFYPEER, 0);
					curl_setopt($chDetail, CURLOPT_URL, ApiBaseUrl()['url'] . 'api/puja/getParticipateEvent');
					curl_setopt($chDetail, CURLOPT_RETURNTRANSFER, 1);
					curl_setopt($chDetail, CURLOPT_POST, 1);
					curl_setopt($chDetail, CURLOPT_POSTFIELDS, json_encode($detailData));
					curl_setopt($chDetail, CURLOPT_HTTPHEADER, $headers);

					$detailResult = curl_exec($chDetail);

					if (curl_errno($chDetail)) {
						curl_close($chDetail);
						show_error('Detail API Error: ' . curl_error($chDetail));
					}

					$detailResponse = json_decode($detailResult);
					curl_close($chDetail);

					// Process participation details
					if (
						$detailResponse &&
						isset($detailResponse->statusCode) &&
						$detailResponse->statusCode == 1 &&
						isset($detailResponse->data[0])
					) {
						$firstRecord = $detailResponse->data[0];

						// Calculate user's contributions for this event
						$userContributions = [];
						$totalUserContribution = 0;

						if (!empty($firstRecord->Datas)) {
							foreach ($firstRecord->Datas as $d) {
								if ($d->memberId == $userId) {
									$userContributions[] = $d;
									$totalUserContribution += $d->count;
								}
							}
						}

						// Add data to participant object
						$participant->Datas = $firstRecord->Datas ?? [];
						$participant->resultd = [[
							'count' => $firstRecord->count ?? 0,
							'sum' => $firstRecord->sum ?? 0
						]];
						$participant->userContributions = $userContributions;
						$participant->totalUserContribution = $totalUserContribution;
						$participant->eventId = $eventId;
						$participant->pujaId = $pujaId; // Add pujaId to participant object

					} else {
						// Set default values if no details found
						$participant->Datas = [];
						$participant->resultd = [[
							'count' => 0,
							'sum' => 0
						]];
						$participant->userContributions = [];
						$participant->totalUserContribution = 0;
						$participant->eventId = $eventId;
						$participant->pujaId = $pujaId; // Add pujaId to participant object
					}
				}

				$fullDetails[] = $participant;
			}

			$data['participants'] = $fullDetails;
		} else {
			$data['participants'] = [];
		}

		$this->load->view('admin/participants-new', $data);
	}


	public function loadPartishipentModal($id = null)
	{
		$data['page'] = 'Home';
		$data['action'] = 'addParticipateEvent';
		$data['data'] = getPartisipentEvnt($id); // optional
		$this->load->view('admin/includes/dynamic-modal', $data); // return partial view
	}


	public function getEventDetails()
	{
		$eventId = $this->input->post('eventId');
		$memberId = $this->input->post('memberId');

		// API request data
		$postData = [
			"dataJson" => [
				"eventId" => $eventId,
				"memberId" => $memberId
			],
			"clientId" => ApiBaseUrl()['clientID']
		];

		$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/puja/getParticipateEvent');
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
		curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);

		$result = curl_exec($ch);

		if (curl_errno($ch)) {
			$response = ['success' => false, 'message' => curl_error($ch)];
		} else {
			$apiResponse = json_decode($result);
			if ($apiResponse && isset($apiResponse->statusCode) && $apiResponse->statusCode == 1) {
				$event = $apiResponse->data[0] ?? null;
				if ($event) {
					$response = [
						'success' => true,
						'data' => [
							'eventId' => $eventId,
							'refDataName' => $event->refDataName ?? '',
							'refDataName1' => $event->refDataName1 ?? '',
							'startDate' => $event->startDate ?? date('Y-m-d'),
							'endDate' => $event->endDate ?? date('Y-m-d'),
							'maxCount' => $event->maxCount ?? 0,
							'currentCount' => $event->currentCount ?? 0
						]
					];
				} else {
					$response = ['success' => false, 'message' => 'Event details not found'];
				}
			} else {
				$response = [
					'success' => false,
					'message' => $apiResponse->message ?? 'Failed to get event details'
				];
			}
		}

		curl_close($ch);

		header('Content-Type: application/json');
		echo json_encode($response);
	}

	// New method for adding contributions
	public function addParticipateEvent()
	{
		try {
			// ✅ Read raw JSON input
			$rawInput = file_get_contents('php://input');
			$postData = json_decode($rawInput, true);

			log_message('debug', 'Raw JSON Input: ' . $rawInput);

			if (!$postData || !isset($postData['dataJson'])) {
				throw new Exception('Invalid input format');
			}

			$data = $postData['dataJson'];
			$clientId = $postData['clientId'] ?? null;

			// ✅ Extract from dataJson
			$eventId = $data['eventId'] ?? null;
			$eventName = $data['eventName'] ?? null;
			$count = $data['count'] ?? null;
			$date = $data['cartCreDate'] ?? null;
			$time = $data['cartCreTime'] ?? null;
			$memberId = $data['memberId'] ?? null;
			$memberName = $data['memberName'] ?? null;
			$itemName = $data['itemName'] ?? '';
			$submitAsGroup = isset($data['submitAsGroup']) ? 'YES' : 'NO';
			$groupName = @$data['groupName'] ?? '';

			// ✅ Validate required data
			if (!$eventId || !$count || !$date || !$memberId || !$memberName || !$eventName) {
				throw new Exception('Missing required parameters');
			}

			// ✅ Prepare API request payload
			$addData = [
				"dataJson" => [
					"memberId" => $memberId,
					"memberName" => $memberName,
					"eventName" => $eventName,
					"eventId" => $eventId,
					"itemName" => $itemName,
					"submitAsGroup" => $submitAsGroup,
					"groupName" => $groupName,
					"count" => intval($count),
					"cartCreDate" => $date,
					"cartCreTime" => $time
				],
				"clientId" => $clientId ?? ApiBaseUrl()['clientID']
			];

			log_message('debug', 'API Request: ' . json_encode($addData));

			// ✅ Make cURL request
			$ch = curl_init();
			curl_setopt_array($ch, [
				CURLOPT_URL => ApiBaseUrl()['url'] . 'api/puja/addParticipateEvent',
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_POST => true,
				CURLOPT_POSTFIELDS => json_encode($addData),
				CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
				CURLOPT_SSL_VERIFYHOST => 0,
				CURLOPT_SSL_VERIFYPEER => 0
			]);

			$result = curl_exec($ch);

			if ($result === false) {
				throw new Exception('Curl error: ' . curl_error($ch));
			}

			$apiResponse = json_decode($result);

			if (!$apiResponse) {
				throw new Exception('Invalid API response: ' . $result);
			}

			// ✅ Prepare response
			$response = [
				'success' => isset($apiResponse->statusCode) && $apiResponse->statusCode == 1,
				'message' => $apiResponse->message ?? 'Contribution added successfully',
				'data' => [
					'date' => $date,
					'time' => $time,
					'count' => $count
				]
			];
		} catch (Exception $e) {
			log_message('error', 'Add Participation Error: ' . $e->getMessage());
			$response = [
				'success' => false,
				'message' => $e->getMessage()
			];
		} finally {
			if (isset($ch)) {
				curl_close($ch);
			}
		}

		header('Content-Type: application/json');
		echo json_encode($response);
	}


	public function MyPayments()
	{

		$email = $this->session->userdata('email');
		$userName = $this->session->userdata('refDataName');


		$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\": {   
			\"moduleName\": \"Payments\",  
			\"productID\": \"" . ApiBaseUrl()['productID'] . "\",   
			\"clientID\": \"" . ApiBaseUrl()['clientID'] . "\",       
			\"aspectType\": \"Payments\",     
			\"query\": {   \"aspectType\": \"Payments\", \"memberId\":\"" . $this->session->userdata('id') . "\"   },   
			\"userName\": \"" . $userName . "\",     
			\"skip\": 0,    
			\"next\": 1020} 
		}");

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

		// 	echo '<pre>';


		// 	print_r($this->session->userdata('id'));


		// print_r($response);
		// die;


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

		// echo '<pre>';	
		// print_r($response->data);
		// die;

		if ($response->statusCode == 1) {


			usort($response->data, 'sortByTimestampDesc');
			$data['payments_data'] = $response->data;

			// 	echo '<pre>';
			// print_r($data); die();	
			$data['page'] = 'MY-PAYMENTS';
			$data['title'] = 'MY PAYMENTS';
			$data['header'] = 'MY PAYMENTS';

			$this->load->view('admin/my-payments', $data);
		}
	}

	public function FilterPaymentsDataOld()
	{
		$dateType = $this->input->post('dateType');
		$selecteddate = $this->input->post('selecteddate');

		$data['page'] = 'MY-BOOKINGS';
		$data['header'] = 'MY BOOKINGS';

		$userName = $this->session->userdata('refDataName');
		$email = $this->session->userdata('email');

		if ($dateType == 'month') {
			$json_post_data = json_encode([
				"componentConfig" => [
					"moduleName" => "Payments",
					"aspectType" => "Payments",
					"productID" => ApiBaseUrl()['productID'],
					"clientID" => ApiBaseUrl()['clientID'],
					"userName" => $userName,
					"query" => [
						"aspectType" => "Payments",
						"paymentStatus" => "COMPLETED",
						"memberId" => $this->session->userdata('id'),
						"cartCreDate" => [
							'$lte' => monthLastDate($selecteddate),
							'$gte' => monthFirstDate($selecteddate)
						]
					],
					"skip" => 0,
					"next" => 10000
				]
			], JSON_UNESCAPED_SLASHES);
		} else if ($dateType == 'year') {


			$json_post_data = json_encode([
				"componentConfig" => [
					"moduleName" => "Payments",
					"aspectType" => "Payments",
					"productID" => ApiBaseUrl()['productID'],
					"clientID" => ApiBaseUrl()['clientID'],
					"userName" => $userName,
					"query" => [
						"aspectType" => "Payments",
						"paymentStatus" => "COMPLETED",
						"memberId" => $this->session->userdata('id'),
						"cartCreDate" => [
							'$lte' => "12/31/" . $selecteddate,
							'$gte' => "01/01/" . $selecteddate
						]
					],
					"skip" => 0,
					"next" => 10000
				]
			], JSON_UNESCAPED_SLASHES);
		} else {



			$json_post_data = json_encode([
				"componentConfig" => [
					"moduleName" => "Payments",
					"aspectType" => "Payments",
					"productID" => ApiBaseUrl()['productID'],
					"clientID" => ApiBaseUrl()['clientID'],
					"userName" => $userName,
					"query" => [
						"aspectType" => "Payments",
						"paymentStatus" => "COMPLETED",
						"memberId" => $this->session->userdata('id'),
						"cartCreDate" => [
							'$lte' => date('m/d/Y', strtotime($selecteddate)),
							'$gte' => date('m/d/Y', strtotime($selecteddate))
						]
					],
					"skip" => 0,
					"next" => 10000
				]
			], JSON_UNESCAPED_SLASHES);
		}
		// echo $json_post_data;die();
		$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, $json_post_data);

		$token = $this->session->userdata('token');
		$headers = [
			'Authorization: Bearer ' . $token,
			'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);


		$html = '';
		$html .= '<table id="myDonations" class="table table-hovered">
			<thead style="background-color: var(--devotee-table-header-bg); color: white;width: 100%;">
				<tr>
					<th class="text-center" style="vertical-align: top;">Receipt&nbsp;#</th>
					<th class="text-center service-name" style="vertical-align: top;">Service Name</th>
					<th class="text-center" style="vertical-align: top;">Service Date</th>
					<th class="text-center" style="vertical-align: top;">Total Amount</th>
					<th class="text-center" style="vertical-align: top;">Payment Type</th>
					<th class="text-center" style="vertical-align: top;">Payment Source</th>
					<th class="text-center" style="vertical-align: top;">Booking Date</th>
					<th class="text-center" style="vertical-align: top;">Status</th>
					<!-- <th class="text-center" style="vertical-align: top;">Refund Payment</th> -->
					<th class="text-center" style="vertical-align: top;">View Receipt</th>
				</tr>
			</thead>
			<tbody style="width:100%">';
		if ($response && isset($response->data)) {


			$booking_data = json_decode(json_encode($response->data), true);

			// if(count($booking_data)>0){
			foreach ($booking_data as $val) {



				if ($val['paymentStatus'] != 'TEMP') {
					$html .= '<tr>
								<td class="text-center">' . $val['batchNo'] . '</td>
								<td class="text-center service-name">' . camelCase(@$val['paymentsData'][0]['ServiceSetup']) . '</td>
								<td class="text-center">' . @$val['paymentsData'][0]['serviceDate'] . '</td>
								<td class="text-center" style="text-align: right;padding-right: 21px">$' . sprintf("%.2f", $val['totalAmount']) . '</td>
								<td class="text-center">' . camelCase($val['paymentType']) . '</td>
								<td class="text-center">';
					$html .= camelCase($val['source']) == "Administrator" ? "Front Desk" : camelCase($val['source']);
					$html .= '</td>
								<td class="text-center">' . $val['recCreDate'] . '</td>
	
								<td class="text-center">';
					$html .= $val['paymentStatus'] == 'COMPLETED' ? '<span class="badge">' . $val['paymentStatus'] . '</span>' : '<span style="background:#FAA21B!important;color:#FFFFFF!important;text-shadow:1px 0px 0px black" class="badge" >' . $val['paymentStatus'] . '</span>';

					$html .= '</td>
								<td class="text-center" class="text-center"><a href="' . base_url('admin/download-reciept/' . base64_encode($val['tokenNumber']) . '/PAYMENTS') . '" target="_blank"><i class="fa fa-eye" style="font-size:22px"></i></a></td>
							</tr>';
				}
			}
			// }else{
			// 	$html.='<tr class="odd"><td valign="top" colspan="8" class="dataTables_empty">No Payments Available to show..</td></tr>';
			// }

		}
		$html .= '	</tbody>
		</table>';

		echo $html;
	}

	public function FilterPaymentsData()
	{
		$dateType = $this->input->post('dateType');
		$selecteddate = $this->input->post('selecteddate');

		$userName = $this->session->userdata('refDataName');

		// Prepare the query based on the selected date type
		if ($dateType == 'month') {
			$cartCreDate = [
				'$lte' => monthLastDate($selecteddate),
				'$gte' => monthFirstDate($selecteddate)
			];
		} elseif ($dateType == 'year') {
			$cartCreDate = [
				'$lte' => "12/31/" . $selecteddate,
				'$gte' => "01/01/" . $selecteddate
			];
		} else {
			$cartCreDate = [
				'$lte' => date('m/d/Y', strtotime($selecteddate)),
				'$gte' => date('m/d/Y', strtotime($selecteddate))
			];
		}

		// API request payload
		$json_post_data = json_encode([
			"componentConfig" => [
				"moduleName" => "Payments",
				"aspectType" => "Payments",
				"productID" => ApiBaseUrl()['productID'],
				"clientID" => ApiBaseUrl()['clientID'],
				"userName" => $userName,
				"query" => [
					"aspectType" => "Payments",
					"paymentStatus" => "COMPLETED",
					"memberId" => $this->session->userdata('id'),
					"cartCreDate" => $cartCreDate
				],
				"skip" => 0,
				"next" => 10000
			]
		], JSON_UNESCAPED_SLASHES);

		// Initialize cURL request
		$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, $json_post_data);

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

		$result = curl_exec($ch);
		$response = json_decode($result, true);

		if (curl_errno($ch)) {
			echo json_encode(['error' => curl_error($ch)]);
			exit;
		}

		curl_close($ch);

		// Return JSON response
		if (!empty($response['data'])) {
			echo json_encode($response['data']);
		} else {
			echo json_encode([]);
		}
	}


	public function RefundPayment($payment_id)
	{

		$payment_id = base64_decode($payment_id);

		$email = $this->session->userdata('email');
		$userName = $this->session->userdata('refDataName');


		$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\": {   
			\"moduleName\": \"Payments\",  
			\"productID\": \"" . ApiBaseUrl()['productID'] . "\",   
			\"clientID\": \"" . ApiBaseUrl()['clientID'] . "\",       
			\"aspectType\": \"Payments\",     
			\"query\": {   
				\"aspectType\": \"Payments\", 
				\"prsnEmail\":\"" . $email . "\" ,
				\"insertedId\":\"" . $payment_id . "\" 

				},   
				\"userName\": \"" . $userName . "\",     
				\"skip\": 0,    
				\"next\": 1020} 
			}");

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


		$data['payment_data'] = $response['data'];
		$data['page'] = 'REFUND PAYMENT FORM';
		$data['title'] = 'REFUND PAYMENT';
		$data['header'] = 'REFUND PAYMENT';
		$this->load->view('admin/refund-form', $data);
	}

	public  function SubmitRefundForm($payment_id, $member_id)
	{
		$payment_id = base64_decode($payment_id);
		$member_id = base64_decode($member_id);


		$reason_of_refund = $this->input->post('reason');
		$orderno = $this->input->post('orderno');

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

		curl_setopt($ch, CURLOPT_URL, ApiBaseUrl()['url'] . refundRequest()['url']);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, "{    
			\"memberId\": \"" . $member_id . "\",    
			\"clientId\": \"" . ApiBaseUrl()['clientID'] . "\",    
			\"productId\": \"" . ApiBaseUrl()['productID'] . "\",    
			\"paymentId\": \"" . $payment_id . "\",    
			\"refundReason\": \"" . $reason_of_refund . "\"}");

		$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);
		// print_r($response);

		if ($response['statusCode'] == 1) {
			$this->session->set_flashdata("success", '<div class="alert alert-success alert-dismissible fade show"  role="alert">Your Refund Request For <strong>Order No#: ' . $orderno . '</strong> has been sent Successfully. <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button></div>');
		} else {
			$this->session->set_flashdata("failure", '<div class="alert alert-success alert-dismissible fade show" role="alert"><strong>Something went wrong.</strong> <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button></div>');
		}

		redirect('admin/my-payments');
	}

	public function download_reciept($token_number, $param)
	{


		$invoice_token_decoded = base64_decode($token_number);
		$param = urldecode($param);

		$userName = $this->session->userdata('refDataName');
		$email = $this->session->userdata('email');


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



		if ($param == 'PAYMENTS') {
			curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"componentConfig\": {   
				\"moduleName\": \"Payments\",  
				\"productID\": \"" . ApiBaseUrl()['productID'] . "\",   
				\"clientID\": \"" . ApiBaseUrl()['clientID'] . "\",       
				\"aspectType\": \"Payments\",     
				\"query\": {   \"aspectType\": \"Payments\", \"prsnEmail\":\"" . $email . "\", \"tokenNumber\": " . $invoice_token_decoded . "       },   
				\"userName\": \"" . $userName . "\",     
				\"skip\": 0,    
				\"next\": 1020} 
			}");
		} else {

			curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"componentConfig\": {   
				\"moduleName\": \"Calendar\",  
				\"productID\": \"" . ApiBaseUrl()['productID'] . "\",   
				\"clientID\": \"" . ApiBaseUrl()['clientID'] . "\",       
				\"aspectType\": \"Service Schedules\",     

				\"query\": {        \"aspectType\": \"serviceBooking\", \"customerEmail\":\"" . $email . "\", \"serviceCategoryTypes\":\"" . $param . "\" , 
				\"tokenNumber\": " . $invoice_token_decoded . "     }, 

				\"userName\": \"" . $userName . "\",     
				\"skip\": 0,    
				\"next\": 1020    } }");
		}

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

		// print_r($response->data);

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

		$data['envoice_data']  = json_decode(json_encode($response->data), true);


		if ($param == 'PAYMENTS') {
			$data['page'] = 'MY-PAYMENTS';
			$data['title'] = 'MY PAYMENTS';
			$data['header'] = 'MY PAYMENTS';
			$this->load->view('admin/PaymentReceipt', $data);
		} else {

			$data['page'] = 'MY-BOOKINGS';
			$data['title'] = 'MY BOOKINGS';
			$data['header'] = 'MY BOOKINGS';

			$this->load->view('admin/BookingReceipt', $data);
		}
	}

	public function YearlyTaxLetter()
	{
		$data['page'] = 'YEARLY-TAX-LETTER';
		$data['title'] = 'YEARLY TAX LETTER';
		$data['header'] = 'YEARLY TAX LETTER';
		$this->load->view('admin/YearlyTaxLetter', $data);
	}

	public function DownlaodTaxLetter()
	{
		$year = $this->input->post('Year');

		if ($year != "") {

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

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


			$post_data = array(
				"userID" => "asdf",
				"memberId" => $this->session->userdata('id'),
				"emailId" => base64_decode($this->session->userdata('email')),
				"clientId" => ApiBaseUrl()['clientID'],
				"year" => $year
			);

			$json_data = json_encode($post_data);

			curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);


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


			if ($response->statusCode == 1) {
				$this->session->set_flashdata('success', ' Your yearly tax letter(PDF) has been sent to your registered email id.');
				redirect(base_url('admin/yearly/Tax-Letter'), 'refresh');
			} else if ($response->statusCode == -1) {
				$this->session->set_flashdata('failure', camelCase($response->message));
				redirect(base_url('admin/yearly/Tax-Letter'), 'refresh');
			} else {
				$this->session->set_flashdata('failure', camelCase($response->message));
				redirect(base_url('admin/yearly/Tax-Letter'), 'refresh');
			}
		} else {
			$this->session->set_flashdata('failure', camelCase(' Please Choose Year!'));
			redirect(base_url('admin/yearly/Tax-Letter'), 'refresh');
		}
	}




	public function CancelBooking($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\": {\"status\":\"CANCELED\"},  
			\"componentConfig\": {        
				\"moduleName\":\"Calendar\",        
				\"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);

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


		echo json_encode($response);
	}

	public function getGotraNakshatraRashi()
	{
		try {
			$data = [];
			$lang = isset($_POST['lang']) && !empty($_POST['lang']) ? $_POST['lang'] : 'ENGLISH';
			// $userrashi = isset($_POST['userrashi']) ? $_POST['userrashi'] : '';
			// $userNakshtra = isset($_POST['userNakshtra']) ? $_POST['userNakshtra'] : '';
			// $usergotraName = isset($_POST['usergotraName']) ? $_POST['usergotraName'] : '';
			// $spouseNakshtra = isset($_POST['spouseNakshtra']) ? $_POST['spouseNakshtra'] : '';
			// $spouseRashi = isset($_POST['spouseRashi']) ? $_POST['spouseRashi'] : '';

			// Fetch Gothram
			$gothram = getGotra($lang);

			$gothramhtml = '<option value="" selected disabled>Select Gothram</option>';
			if (!empty($gothram['data'])) {
				foreach ($gothram['data'] as $item) {
					// var_dump($item['refDataName']);die();
					$gothramhtml .= '<option value="' . @replaceSingleQuotesWithBackticks($item['refDataName']) . '">' . @replaceSingleQuotesWithBackticks($item['refDataName']) . '</option>';
				}
			}

			// Fetch Nakshatra
			$stars = getNakshtra($lang);
			$starshtml = '<option value="" selected disabled>Select Nakshtra</option>';
			if (!empty($stars['data'])) {
				foreach ($stars['data'] as $item) {
					$starshtml .= '<option value="' . @replaceSingleQuotesWithBackticks($item['refDataName']) . '">' . @replaceSingleQuotesWithBackticks($item['refDataName']) . '</option>';
				}
			}

			// Fetch Rashi
			$rashi = getRashi($lang);
			$rashihtml = '<option value="" selected disabled>Select Rashi</option>';
			if (!empty($rashi['data'])) {
				foreach ($rashi['data'] as $item) {
					$rashihtml .= '<option value="' . @replaceSingleQuotesWithBackticks($item['refDataName']) . '">' . @replaceSingleQuotesWithBackticks($item['refDataName']) . '</option>';
				}
			}

			// Return as JSON
			$data['gothram'] = $gothramhtml;
			$data['stars'] = $starshtml;
			$data['rashi'] = $rashihtml;
			echo json_encode($data);
		} catch (Exception $e) {
			// Log or display the error for debugging
			echo json_encode(['error' => $e->getMessage()]);
		}
	}

	public function UpdateMobileNumber()
	{
		$response = [
			'stateCode' => -1,
			'message' => 'Something went wrong.'
		];

		if ($this->input->post()) {
			$new_phone = $this->input->post('new_phone');
			$new_phone = $new_phone != '' ? str_replace([' ', '(', ')', '-'], '', $new_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'] . updateMobileNumber()['url']);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_POST, 1);

			$post_json_data = [
				"clientId" => ApiBaseUrl()['clientID'],
				"userName" => $this->session->userdata('refDataName'),
				"memberId" => $this->session->userdata('id'),
				"mobile" => $new_phone,
			];

			$payload = json_encode($post_json_data);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);

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

			$result = curl_exec($ch);
			if ($result === false) {
				$response['message'] = 'Curl error: ' . curl_error($ch);
			} else {
				$response = json_decode($result, true);
				if (isset($response['user']['data'])) {
					$response['user']['data']['email'] = maskEmail(base64_decode($response['user']['data']['email']));
				}
				// var_dump($response);
			}
			curl_close($ch);
		}

		header('Content-Type: application/json');
		echo json_encode($response);
	}


	public function Membership()
	{
		$data['page'] = 'Membership';
		$data['title'] = 'Membership Details';
		$data['header'] = 'Membership Details';
		$data['userDetails'] = getUserDetails()->data[0];
		$this->load->view('admin/membership', $data);
	}


	public function saveParticipateEvent()
	{
		try {
			if (!empty($this->input->post())) {
				$postData = $this->input->post();
				$clientId = $postData['clientId'] ?? null;

				// ✅ Extract from dataJson
				$eventId = $postData['eventId'] ?? null;
				$eventName = $postData['eventName'] ?? null;
				$count = $postData['count'] ?? null;
				$eventDate = $postData['date'] ?? null;
				$date = date('m/d/Y');
				$time = date('h:i A');
				$memberId = $postData['memberId'] ?? null;
				$memberName = $postData['memberName'] ?? null;
				$itemName = $postData['itemName'] ?? '';
				$submitAsGroup = isset($postData['submitAsGroup']) ? 'YES' : 'NO';
				$groupName = @$postData['groupName'] ?? '';
				$devoteeCount = @$postData['devoteeCount'] ?? 1;
				$grpNameHidden = @$postData['grpNameHidden'] ?? '';

				// ✅ Validate required data
				// if (!$eventId || !$count || !$date || !$memberId || !$memberName || !$eventName ||!$eventDate) {
				// 	throw new Exception('Missing required parameters');
				// }
				if (empty($eventDate)) {
					$response = [
						'success' => false,
						'message' => "Please select date!"
					];
				} else if (empty($count)) {
					$response = [
						'success' => false,
						'message' => "Please enter count!"
					];
				} else if ($submitAsGroup == 'YES' && empty($groupName)) {
					$response = [
						'success' => false,
						'message' => "Please fill group name!"
					];
				} else if ($submitAsGroup == 'YES' && empty($devoteeCount)) {
					$response = [
						'success' => false,
						'message' => "Please fill devotee count!"
					];
				} else {
					if (empty(trim($grpNameHidden)) && $submitAsGroup == 'YES') {
						$userData = getUserDetails()->data[0];
						$groupDetails = @$userData->groupDetails ?? [];

						$newGroup = [
							"groupName" => $groupName,
							"eventName" => $eventName,
							"eventId" => $eventId,
							"devoteeCount" => $devoteeCount,
						];

						array_push($groupDetails, $newGroup);

						$profileUpData = [];
						$profileUpData['groupDetails'] = $groupDetails;
						$ch = curl_init();
						curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
						curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

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


						$post_json_data = [
							"_id" => $memberId,
							"dataJson" => $profileUpData,
							"componentConfig" => [
								"moduleName" => "Contacts",
								"productID" => ApiBaseUrl()['productID'],
								"clientID" => ApiBaseUrl()['clientID'],
								"userName" => $memberName
							]
						];

						$payload = json_encode($post_json_data);

						// var_dump($payload);die();

						curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);



						$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);
					}
					// ✅ Prepare API request payload
					$addData = [
						"dataJson" => [
							"memberId" => $memberId,
							"memberName" => $memberName,
							"eventName" => $eventName,
							"eventDate" => $eventDate,
							"eventId" => $eventId,
							"itemName" => $itemName,
							"submitAsGroup" => $submitAsGroup,
							"groupName" => $submitAsGroup == 'NO' ? '' : $groupName,
							"count" => intval($count),
							"devoteeCount" => $devoteeCount,
							"cartCreDate" => $date,
							"cartCreTime" => $time
						],
						"clientId" => $clientId ?? ApiBaseUrl()['clientID']
					];

					log_message('debug', 'API Request: ' . json_encode($addData));
					// var_dump(json_encode($addData));
					// ✅ Make cURL request
					$ch = curl_init();
					curl_setopt_array($ch, [
						CURLOPT_URL => ApiBaseUrl()['url'] . 'api/puja/addParticipateEvent',
						CURLOPT_RETURNTRANSFER => true,
						CURLOPT_POST => true,
						CURLOPT_POSTFIELDS => json_encode($addData),
						CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
						CURLOPT_SSL_VERIFYHOST => 0,
						CURLOPT_SSL_VERIFYPEER => 0
					]);

					$result = curl_exec($ch);

					if ($result === false) {
						throw new Exception('Curl error: ' . curl_error($ch));
					}

					$apiResponse = json_decode($result);

					if (!$apiResponse) {
						throw new Exception('Invalid API response: ' . $result);
					}
					// var_dump($apiResponse);

					// ✅ Prepare response
					$response = [
						'success' => isset($apiResponse->statusCode) && $apiResponse->statusCode == 1,
						'message' => $apiResponse->message ?? 'Contribution added successfully',
						'data' => [
							'date' => $date,
							'time' => $time,
							'count' => $count
						]
					];
				}
			} else {
				$response = [
					'success' => false,
					'message' => "Please fill all required fields!"
				];
			}
		} catch (Exception $e) {
			log_message('error', 'Add Participation Error: ' . $e->getMessage());
			$response = [
				'success' => false,
				'message' => $e->getMessage()
			];
		} finally {
			if (isset($ch)) {
				curl_close($ch);
			}
		}

		header('Content-Type: application/json');
		echo json_encode($response);
	}


	public function prasadam()
	{

		$response = getUserDetails();
		if ($response->statusCode == 1) {
			$data['page'] = 'Prasadam';
			$data['title'] = 'Prasadam';
			$data['header'] = 'Prasadam';

			$data['dailyMenu'] = getDailyMenuDevotee();
			$data['userDetails'] = $response->data[0];
			$addressLine1 = @$data['userDetails']->addressLine1;
			$cityTypes = @$data['userDetails']->cityTypes;
			$county = @$data['userDetails']->county;
			$stateTypes = @$data['userDetails']->stateTypes;
			$zip = @$data['userDetails']->zip;
			if (empty(trim($addressLine1)) || empty(trim($cityTypes)) || empty(trim($stateTypes)) || empty(trim($zip))) {
				$this->session->set_flashdata('show_profile_alert', true);
				redirect(base_url('admin/dashboard'));
			} else {

				$this->load->view('admin/prasadam', $data);
			}
		} else {
			echo json_encode('User not found!!');
			$this->session->unset_userdata('logged_in');
			redirect(base_url());
		}
	}

	public function MySponsers()
	{
		$data['page'] = 'MY-SPONSORS';
		$data['title'] = 'MY SPONSORS';
		$data['header'] = 'MY SPONSORS';


		$this->load->view('admin/my-sponsers', $data);
	}
	public function FilterSponserData()
	{
		$dateType = $this->input->post('dateType');
		$selecteddate = $this->input->post('selecteddate');
		$selectedenddate = @$this->input->post('selectedenddate');



		$userName = $this->session->userdata('refDataName');
		$email = $this->session->userdata('email');

		if ($dateType == 'month') {
			$endDate = monthLastDate($selecteddate);
			$startDate = monthFirstDate($selecteddate);
		} else if ($dateType == 'year') {
			$endDate = "12/31/" . $selecteddate;
			$startDate = "01/01/" . $selecteddate;
		} else {
			// $endDate = date('m/d/Y', strtotime($selectedenddate));
			// $startDate = date('m/d/Y', strtotime($selecteddate));
			$selecteddate = str_replace('-', '/', $this->input->post('selecteddate'));
			$selectedenddate = str_replace('-', '/', $this->input->post('selectedenddate'));

			$startDate = date('m/d/Y', strtotime($selecteddate));
			$endDate = date('m/d/Y', strtotime($selectedenddate));
		}
		// echo $json_post_data;die();
		$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);

		// Create an associative array to represent the data structure
		$postdata = array(
			"componentConfig" => array(
				"moduleName" => "Calendar",
				"productID" => ApiBaseUrl()['productID'],
				"clientID" => ApiBaseUrl()['clientID'],
				"aspectType" => "Service Schedules",
				"query" => array(
					"aspectType" => "serviceBooking",
					"paymentStatus" => "COMPLETED",
					"memberId" => $this->session->userdata('id'),
					"serviceCategoryTypes" => "SPONSORSHIP",
					"cartCreDate" => [
						'$lte' => $endDate,
						'$gte' => $startDate
					]
				),
				"userName" => $userName,
				"skip" => 0,
				"next" => 1020
			)
		);

		$jsonData = json_encode($postdata);

		curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);


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

		usort($response->data, 'sortByTimestampDesc');


		$html = '';
		$html .= '<table id="myDonations" class="table table-hovered bg-white">
			<thead style="background-color: var(--devotee-table-header-bg); color: white;">
				<tr>
					<th>Receipt&nbsp;#</th>
					<th class="text-center">Booking&nbsp;Date</th>

					<th class="text-center service-name">Sponser&nbsp;Name</th>
					<th class="text-end">Amount</th>
					<th class="text-center">Service&nbsp;Date</th>
					<th class="text-center">Payment&nbsp;Status</th>

				</tr>
			</thead>
			<tbody>';
		if ($response && isset($response->data)) {


			$booking_data = json_decode(json_encode($response->data), true);


			foreach ($booking_data as $val) {
				if (isset($val['fullPackage']) && $val['fullPackage'] == "true") {
					$serviceAmount = sprintf("%.2f", $val['serviceAmount'] * $val['serviceOccurrencesNo']);
				} else {
					$serviceAmount = sprintf("%.2f", $val['serviceAmount']);
				}


				$html .= '	<tr>
						<td class="text-start">' . $val['tokenNumber'] . '</td>
						<td class="text-center">' . $val['recCreDate'] . '</td>

						<td class="text-center">' . camelCase($val['ServiceSetup']) . '</td>
						<td class="text-end">' . '$' . $serviceAmount . '</td>
						<td class="text-center">
							';
				$html .= $val['recCreDate'] ?	$val['recCreDate'] : '';
				$html .= '

						</td>
						<td class="text-center">' . camelCase($val['paymentType']) . '</td>
						

					</tr>';
			}
		}
		$html .= '	</tbody>
		</table>';

		echo $html;
	}
}
