<?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['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(){

		$serviceTypes = $this->input->post('aspectType');

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

		$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);
		curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"componentConfig\": {   
			\"moduleName\": \"Calendar\",  
			\"productID\": \"".ApiBaseUrl()['productID']."\",   
			\"clientID\": \"".ApiBaseUrl()['clientID']."\",       
			\"aspectType\": \"Service Schedules\",     
			\"query\": {        
				\"aspectType\": \"Rental Request Form\",
				\"customerEmail\":\"".$email."\",
				\"serviceTypes\":\"".$serviceTypes."\"      
				},   
				\"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);
		$html = '';
		if($response != ''){

			$booking_data  = 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">Order&nbsp;#</th>';
			$html .= 				'<th>Items Name</th>';
			$html .= 				'<th>Quantity</th>';
			$html .= 				'<th style="text-align:right">Price</th>';

			$html .= 				'<th class="text-center">Order&nbsp;Date</th>';
			$html .=				'<th class="text-center">Status</th>';
			$html .=				'<th class="text-center">Cancel&nbspOrder</th>';
				// $html .=				'<th class="text-center">View&nbsp;Receipt</th>';
			$html .= 			'</tr>';
			$html .=		'</thead>';
			$html .=		'<tbody>';
			foreach($booking_data as $val){

				if (isset($val['status']) && $val['status'] != '') {
					$status = $val['status'];
				}else{
					$status = $val['statusName'];
				}

				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>';
				}
				$html .= '<tr><td class="text-center">'.$val['tokenNumber'].'</td>';
				$html .= '<td>'.camelCase($val['ServiceSetup']).'</td>';
				$html .= '<td>'.$val['qty'].'</td>';
				$html .= '<td style="text-align:right;padding-right:25px">$ '.sprintf("%.2f",$val['serviceAmount']).'</td>';

				$html .= '<td class="text-center">'.$val['recCreDate'].'</td>';
				$html .= '<td class="text-center">'.$status.'</td>';
				$html .= '<td class="text-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 .= 		'</tbody>';
			$html .= 	'</table>';

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

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

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

	public function FilterBookingData(){

		$serviceCategoryTypes = $this->input->post('aspectType');
		$data['page'] =  'MY-BOOKINGS';
		$data['header'] =  'MY BOOKINGS';

		$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);
		curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"componentConfig\": {   
			\"moduleName\": \"Calendar\",  
			\"productID\": \"".ApiBaseUrl()['productID']."\",   
			\"clientID\": \"".ApiBaseUrl()['clientID']."\",       
			\"aspectType\": \"Service Schedules\",     
			\"query\": {        \"aspectType\": \"serviceBooking\", \"paymentStatus\": \"COMPLETED\", \"memberId\":\"".$this->session->userdata('id')."\" ,\"serviceCategoryTypes\":\"".$serviceCategoryTypes."\"      },   
			\"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);


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

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

			usort($response->data, 'sortByTimestampDesc');
			$booking_data  = 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">Order&nbsp;#</th>';
			$html .= 				'<th>Service Name</th>';
			$html .= 				'<th style="text-align:right">Amount</th>';
			$html .= 				'<th class="text-center">Booking&nbsp;Date</th>';
			$html .= 				'<th class="text-center">Service&nbsp;Date</th>';
			$html .=				'<th class="text-center">Status</th>';
			$html .=				'<th class="text-center">Cancel&nbspBooking</th>';
			// $html .=				'<th class="text-center">View&nbsp;Receipt</th>';
			$html .= 			'</tr>';
			$html .=		'</thead>';
			$html .=		'<tbody>';
			foreach($booking_data as $val){

				if (isset($val['status']) && $val['status'] != '') {
					$status = $val['status'];
				}else{
					$status = $val['statusName'];
				}

				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>';
				}
				$html .= '<tr><td class="text-center">'.$val['tokenNumber'].'</td>';
				$html .= '<td>'.camelCase($val['ServiceSetup']).'</td>';
				$html .= '<td style="text-align:right;padding-right:25px">$ '.sprintf("%.2f",$val['serviceAmount']).'</td>';
				$html .= '<td class="text-center">'.$val['recCreDate'].'</td>';
				$html .= '<td class="text-center">'.$val['serviceDate'].'</td>';
				$html .= '<td class="text-center">'.$status.'</td>';
				$html .= '<td class="text-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 class="text-center"><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></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 MyDonations(){
		$data['page'] = 'MY-DONATIONS';
		$data['title'] = 'MY DONATIONS';
		$data['header'] = 'MY DONATIONS';

		$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);
		
		// 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"
				),
				"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');

		$data['donations_data']  = json_decode(json_encode($response->data), true);
		$this->load->view('admin/my-donations',$data);
	}

	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 = $post_data['family_member_status'][$key];
			$newEntry->relationship = $post_data['relationship'][$key];
			$newEntry->anniversaryDate = $post_data['anniversary'][$key];
			$newEntry->gotraName = $post_data['family_member_gotraName'][$key];
			$newEntry->householdInd = $post_data['member_household_indicator'][$key];
			$newEntry->member_email =$post_data['member_email'][$key] != '' ? base64_encode($post_data['member_email'][$key]) : '';
			$newEntry->member_phone = $post_data['member_phone'][$key] != '' ? base64_encode(str_replace([' ', '(', ')', '-'], '',$post_data['member_phone'][$key])) : '';

			$inputArray[] = $newEntry;

		}




		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 = $spouse_household_indicator == 'on' ? '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,
				"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);



		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 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 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{
				$this->session->set_flashdata('failure',camelCase(' Something went wrong!'));
				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);

	}
}
