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

include_once (dirname(__FILE__) . "/Dashboard.php");

class ServiceRequest extends Dashboard {

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

		$currency = '';

		$this->$currency =  GeneralSettings();

		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(){

		$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\": \"Service Inquiry\",  
			\"productID\": \"".ApiBaseUrl()['productID']."\",   
			\"clientID\": \"".ApiBaseUrl()['clientID']."\",       
			\"aspectType\": \"Request Form\",     
			\"query\": {   \"aspectType\": \"Request Form\", \"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);


			// print_r($response);


		if (curl_errno($ch)) {
			echo 'Error:' . curl_error($ch);
		}
		curl_close($ch);
		if ($response->statusCode == 1) {


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

			$data['myServiceRequests_data'] = $response->data;


			// echo '<pre>';
			// print_r($data['myServiceRequests_data']);
			// die();

			$data['page'] = 'MY-SERVICE-REQUEST';
			$data['title'] = 'MY SERVICE REQUEST';
			$data['header'] = 'MY SERVICE REQUEST';
			$this->load->view('admin/my-service-request',$data);
		}else{

			$data['err_msg'] = $response->message;
			$data['page'] = 'MY-SERVICE-REQUEST';
			$data['title'] = 'MY SERVICE REQUEST';
			$data['header'] = 'MY SERVICE REQUEST';
			$this->load->view('admin/my-service-request',$data);
		}
	}

	public function getPreferredLanguage(){
		$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\": \"languageTypes\",     
				\"query\": {        
					\"aspectType\": \"languageTypes\"     
					},   
					\"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);
		return $response = json_decode($result);
		print_r($response->data);

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


	public function getPriestData(){
		$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\": \"Contacts\",  
				\"productID\": \"".ApiBaseUrl()['productID']."\",
				\"clientID\": \"".ApiBaseUrl()['clientID']."\",       
				\"aspectType\": \"Member Directory\",     
				\"query\": {        
					\"aspectType\": \"Member Directory\",      
					\"memberTypes\": \"PRIEST\" ,
					\"status\": \"ACTIVE\" 
					},   
					\"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);
		return $response = json_decode($result);

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

	public function GetServicesByCategory(){

		$currency = getCurrencySymbol();


		$serviceCatTypes = $this->input->post('param');

		if ($serviceCatTypes == 'aparakarya') {
			$serviceCatTypes = 'SHRAADHAM';
		}

		 $filter['query'] = ['aspectType' => 'ServiceSetup', 'serviceCategoryTypes' => $serviceCatTypes, 'sourceTypes' => 'WEBSITE', 'bookingType' => 'SERVICE REQUEST', 'status' => 'ACTIVE'];

		$data =  getServiceRequestData($filter);



		$html = '';
		$html .= '<option value=" " selected disabled>Please Select Service</option>';
		foreach ($data as $item) {
			$html .= '<option value="' . $item['refDataName'] . '"  serviceId="' . $item['_id'] . '" startDate="' . $item['startDate'] . '" startTime="' . $item['startTime'] . '" serviceType="' . $item['serviceTypes'] . '" serviceAmount="' . $item['serviceAmount'] . '">' . $item['refDataName'] . '(' . $currency . ' ' . $item['serviceAmount'] . ')' . '</option>';
		}

		$html .= '<option value="Other" serviceId="0" startdate="" starttime="" servicetype="OTHERS" serviceCategoryType="AWAY-TEMPLE" serviceamount="0.0">Other($ 0.00)</option>';
		echo $html;
	}

	public function ServiceRequest()
	{		
		$data['page'] = 'Service-Request';
		$data['header'] = 'REQUEST A SERVICE';
		$data['GetState'] = GetState();
		$userDetails = getUserDetails();
		$preferredLanguage = getPreferredLanguage();
		$PriestData = $this->getPriestData();
		$preferredLocations = getPreferredLocations();

		$data['userDetails'] = $userDetails->data[0];
		$data['preferredLanguage'] = $preferredLanguage->data;
		$data['preferredLocations'] = $preferredLocations->data;


		//print_r($data['preferredLocations']);
		$data['PriestData'] = $PriestData->data;


		$filter1['query'] = ['aspectType'=>'ServiceSetup','serviceCategoryTypes'=>'IN-TEMPLE', 'sourceTypes' => 'WEBSITE', 'status' => 'ACTIVE'];

		$array1 =  getServiceRequestData($filter1);


		$filter2['query'] = ['aspectType'=>'ServiceSetup','serviceCategoryTypes'=>'AWAY-TEMPLE', 'sourceTypes' => 'WEBSITE', 'status' => 'ACTIVE'];

		$array2 =  getServiceRequestData($filter2);


		$data['services'] = array_merge($array1, $array2);

		$this->load->view('admin/request-a-service',$data);
	}

	public function addServiceRequest(){
		// print_r($this->input->post());

		// die();

		$redirect_url = $this->input->post('page_name') == 'outside-temple' ?  'services/request/outside-temple' :  ($this->input->post('page_name') == 'aparakarya' ? 'services/request/aparakarya' : 'services/serviceRequest');

		$gotra = $this->input->post('gotra');
		$stars = $this->input->post('stars');
		$rashi = $this->input->post('rashi');


		if (!empty($gotra) || !empty($stars) || !empty($rashi)) {



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

			$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);
			curl_setopt($ch, CURLOPT_POSTFIELDS, "{  
				\"_id\":\"".$Id."\",    
				\"dataJson\": {        
					\"gotraName\": \"".$gotra."\",        
					\"Nakshtra\": \"".$stars."\",
					\"rashi\": \"".$rashi."\"
					},
					\"componentConfig\": {\"moduleName\":\"Contacts\",        
					\"productID\": \"".ApiBaseUrl()['productID']."\",        
					\"clientID\": \"".ApiBaseUrl()['clientID']."\",        
					\"userName\": \"".$userName."\"    
				}}");

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

		}

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

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

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

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


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


		$serviceDate = $this->input->post('serviceDate');
		$serviceTime = $this->input->post('serviceTime');

		// $preferredLanguage = $this->input->post('preferredLanguage');
		$preferredLocation = $this->input->post('preferredLocation');

		$serviceName = $this->input->post('serviceName');
		
		$addtionalInfo = $this->input->post('addtionalInfo');
		$serviceType = $this->input->post('serviceType');
		$serviceAmount = $this->input->post('serviceAmount');
		$serviceId = $this->input->post('serviceId');
		$preferredLanguage = @getUserDetails()->data[0]->languagePreferenceName;


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

		if ($serviceAddress != '') {
			$serviceAddress = $this->input->post('serviceAddress');
		}else{
			$serviceAddress == '';
		}

		$isConfirmed = ($priestName != 'Any Priest') ? 'true' : 'false';
		

		if ($serviceName == 'Other') {
			$serviceName = $this->input->post('serviceDetails');
		}
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

		curl_setopt($ch, CURLOPT_URL, ApiBaseUrl()['url'].addServiceRequest()['url']);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, "{      
			\"memberId\": \"".$this->session->userdata('id')."\", 
			\"serviceId\": \"".$serviceId."\", 

			\"serviceRequestName\":\"".$fname." ".$lname."\",      
			\"prsnEmail\": \"".$email."\",      
			\"prsnPhone\": \"".$phoneNumber."\",      
			\"clientId\": \"".ApiBaseUrl()['clientID']."\",      
			\"serviceDate\": \"".$serviceDate."\",      
			\"serviceTime\": \"".$serviceTime."\",      
			\"serviceLocationName\": \"".$preferredLocation."\",      

			\"serviceAddress\": \"".$serviceAddress."\",  


			\"serviceName\": \"".$serviceName."\",      
			\"serviceCategoryTypes\": \"".$preferredLocation."\",  

			\"serviceTypes\": \"".$serviceType."\",    
			\"serviceAmount\":".$serviceAmount.",    
			\"languagePreferenceName\": \"".$preferredLanguage."\",

			\"notes\": \"".$addtionalInfo."\",           
			\"requestForPriestName\": \"".$priestName."\",  

			\"priestEmail\": \"".$priestEmail."\",      
			\"priestPhone\": \"".$priestPhone."\", 


			\"requestedPriestId\": \"".$priestId."\", 
			
			\"isConfirmed\": $isConfirmed, 

			\"foodType\": \"\",      
			\"package\": \"\",      
			\"extraFood\": \"\",    
			\"etShraadhamFor\": \"\",      
			\"ettithiDetail\": \"\",     

			\"source\": \"WEBSITE\",      
			\"notificationEmailName\": \"YES\"    
		}");

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

		// print_r($response);

		// die;

		if ($response->statusCode == 1) {
			$this->session->set_flashdata('success', '<div class="alert alert-success alert-dismissible fade show"><strong>Success!</strong> Your Service Request has been successful.<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button></div>');



			if (isset($_POST['source']) && $_POST['source'] == 'SERVICES-PAGE') {

				echo '<script type="text/javascript"> 
				alert("Service Request has been submitted successfully!!");
				if (confirm("Would you like to go to the My Service Requests page?")) {
					window.location.href="'.base_url().'/admin/my-service-request/";
					} else {
						window.location.href="'.base_url().'";
					}
					</script>';

				// redirect(base_url($redirect_url));
				}else{
					redirect(base_url('admin/my-service-request'));

				}
			}
		}
	}
?>
