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

class Common extends MY_Controller
{

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

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

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

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

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

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




	public function addCart()
	{
		if ($this->input->post()) {
			// echo "<pre>";
			// var_dump($this->input->post());die();
			$this->session->set_userdata('service_cart', $this->input->post());

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

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

				$includeSankalpam = 'NO';
			}
		}


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





	public function AddToCart()
	{

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



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

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


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

			$sponser_cart_items = $this->input->post('sponser_cart_items');
			$service_cart_items = $this->input->post('service_cart_items');
			$donation_cart_items = $this->input->post('donation_cart_items');
			$event_cart_items = $this->input->post('event_cart_items');
			$books_cart_items = $this->input->post('books_cart_items');
			$creditCardRemark = @$this->input->post('creditCardRemark');
			// var_dump($books_cart_items);
			if (!is_array($sponser_cart_items) && !empty($sponser_cart_items)) {
				$sponser_cart_items = json_decode($this->input->post('sponser_cart_items'), true);
			}

			if (!is_array($service_cart_items) && !empty($service_cart_items)) {
				$service_cart_items = json_decode($this->input->post('service_cart_items'), true);
			}

			if (!is_array($donation_cart_items) && !empty($donation_cart_items)) {
				$donation_cart_items = json_decode($this->input->post('donation_cart_items'), true);
			}


			if (!is_array($event_cart_items) && !empty($event_cart_items)) {
				$event_cart_items = json_decode($this->input->post('event_cart_items'), true);
			}
			
			if (!is_array($books_cart_items) && !empty($books_cart_items)) {
				$books_cart_items = json_decode($this->input->post('books_cart_items'), true);
			}
			// var_dump($books_cart_items);die();

			$dataWithAmount = array();
			if (!empty($service_cart_items)) {
				for ($i = 0; $i < count($service_cart_items['ids']); $i++) {

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

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

						foreach ($startDateArray as $startDate) {

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

						$dataWithAmount[] = array(
							"_id" => $service_cart_items['ids'][$i],
							"ServiceId" => $service_cart_items['ids'][$i],
							"serviceName" => $service_cart_items['serviceName'][$i],
							"serviceCategory" => $service_cart_items['ctg'][$i],
							"serviceType" => $service_cart_items['serviceTypes'][$i],
							"serviceAmount" => $service_cart_items['serviceAmount'][$i],
							"startDate" => '',
							"qty" => $service_cart_items['qty'][$i],
							"time" => @$service_cart_items['startTime'][$i],
							"bookingType" => @$payment_type_check,
							"day" => "",
							"serviceAddress" => "",
							"cartCreDate" => date("m/d/Y"),
							"cartCreTime" => date("h:i A"),
							"isServicePaid" => @$service_cart_items['isServicePaid'][$i],
							"serviceDesc" => @$service_cart_items['service_desc'][$i],
							"deity" => @$service_cart_items['dietyName'][$i],
							"serviceOccurrencesNo" => @$service_cart_items['serviceOccurrencesNo'][$i],
							"fullPackage" => @$service_cart_items['fullPackage'][$i],
							"oldServiceAmount" => isset($service_cart_items['oldServiceAmount'][$i]) && $service_cart_items['oldServiceAmount'][$i] > 0 ? $service_cart_items['oldServiceAmount'][$i] : $service_cart_items['serviceAmount'][$i],
							"discountedAmount" => isset($service_cart_items['discountedAmount'][$i]) && $service_cart_items['discountedAmount'][$i] > 0 ? $service_cart_items['discountedAmount'][$i] : 0,
						);
					}
				}
			}

			if (!empty($sponser_cart_items) && isset($sponser_cart_items['ids']) && !empty($sponser_cart_items['ids'])) {
				for ($i = 0; $i < count($sponser_cart_items['ids']); $i++) {

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

							$dataWithAmount[] = array(
								"_id" => $sponser_cart_items['ids'][$i],
								"ServiceId" => $sponser_cart_items['ids'][$i],
								"serviceName" => $sponser_cart_items['serviceName'][$i],
								"serviceCategory" => $sponser_cart_items['ctg'][$i],
								"serviceType" => $sponser_cart_items['serviceTypes'][$i],
								"serviceAmount" => $sponser_cart_items['serviceAmount'][$i],
								"startDate" => $startDate,
								"qty" => $sponser_cart_items['qty'][$i],
								"time" => @$sponser_cart_items['startTime'][$i],
								"day" => "",
								"serviceAddress" => "",
								"serviceDesc" => @$sponser_cart_items['service_desc'][$i],
								"deity" => @$sponser_cart_items['dietyName'][$i],
								"serviceOccurrencesNo" => @$sponser_cart_items['serviceOccurrencesNo'][$i],
								"fullPackage" => @$sponser_cart_items['fullPackage'][$i],
								"oldServiceAmount" => isset($sponser_cart_items['oldServiceAmount'][$i]) && $sponser_cart_items['oldServiceAmount'][$i] > 0 ? $sponser_cart_items['oldServiceAmount'][$i] : $sponser_cart_items['serviceAmount'][$i],
								"discountedAmount" => isset($sponser_cart_items['discountedAmount'][$i]) && $sponser_cart_items['discountedAmount'][$i] > 0 ? $sponser_cart_items['discountedAmount'][$i] : 0,
							);
						}
					} else {

						$dataWithAmount[] = array(
							"_id" => $sponser_cart_items['ids'][$i],
							"ServiceId" => $sponser_cart_items['ids'][$i],
							"serviceName" => $sponser_cart_items['serviceName'][$i],
							"serviceCategory" => $sponser_cart_items['ctg'][$i],
							"serviceType" => $sponser_cart_items['serviceTypes'][$i],
							"serviceAmount" => $sponser_cart_items['serviceAmount'][$i],
							"startDate" => '',
							"qty" => $sponser_cart_items['qty'][$i],
							"time" => @$sponser_cart_items['startTime'][$i],
							"day" => "",
							"serviceAddress" => "",
							"serviceDesc" => @$sponser_cart_items['service_desc'][$i],
							"deity" => @$sponser_cart_items['dietyName'][$i],
							"serviceOccurrencesNo" => @$sponser_cart_items['serviceOccurrencesNo'][$i],
							"fullPackage" => @$sponser_cart_items['fullPackage'][$i],
							"oldServiceAmount" => isset($sponser_cart_items['oldServiceAmount'][$i]) && $sponser_cart_items['oldServiceAmount'][$i] > 0 ? $sponser_cart_items['oldServiceAmount'][$i] : $sponser_cart_items['serviceAmount'][$i],
							"discountedAmount" => isset($sponser_cart_items['discountedAmount'][$i]) && $sponser_cart_items['discountedAmount'][$i] > 0 ? $sponser_cart_items['discountedAmount'][$i] : 0,
						);
					}
				}
			}


			if (!empty($donation_cart_items)) {
				for ($i = 0; $i < count($donation_cart_items['ids']); $i++) {

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

			if (!empty($event_cart_items)) {
				for ($i = 0; $i < count($event_cart_items['ids']); $i++) {

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

							$dataWithAmount[] = array(
								"_id" => $event_cart_items['ids'][$i],
								"ServiceId" => $event_cart_items['ids'][$i],
								"serviceName" => $event_cart_items['serviceName'][$i],
								"serviceCategory" => $event_cart_items['ctg'][$i],
								"serviceType" => $event_cart_items['serviceTypes'][$i],
								"serviceAmount" => $event_cart_items['serviceAmount'][$i],
								"startDate" => $startDate,
								"qty" => $event_cart_items['qty'][$i],
								"time" => @$event_cart_items['startTime'][$i],
								"day" => "",
								"serviceAddress" => "",
								"serviceDesc" => @$event_cart_items['service_desc'][$i],
								"deity" => @$event_cart_items['dietyName'][$i],
								"serviceOccurrencesNo" => @$event_cart_items['serviceOccurrencesNo'][$i],
								"fullPackage" => @$event_cart_items['fullPackage'][$i],
								"oldServiceAmount" => isset($event_cart_items['oldServiceAmount'][$i]) && $event_cart_items['oldServiceAmount'][$i] > 0 ? $event_cart_items['oldServiceAmount'][$i] : $event_cart_items['serviceAmount'][$i],
								"discountedAmount" => isset($event_cart_items['discountedAmount'][$i]) && $event_cart_items['discountedAmount'][$i] > 0 ? $event_cart_items['discountedAmount'][$i] : 0,
							);
						}
					} else {

						$dataWithAmount[] = array(
							"_id" => $event_cart_items['ids'][$i],
							"ServiceId" => $event_cart_items['ids'][$i],
							"serviceName" => $event_cart_items['serviceName'][$i],
							"serviceCategory" => $event_cart_items['ctg'][$i],
							"serviceType" => $event_cart_items['serviceTypes'][$i],
							"serviceAmount" => $event_cart_items['serviceAmount'][$i],
							"startDate" => '',
							"qty" => $event_cart_items['qty'][$i],
							"time" => @$event_cart_items['startTime'][$i],
							"day" => "",
							"serviceAddress" => "",
							"serviceDesc" => @$event_cart_items['service_desc'][$i],
							"deity" => @$event_cart_items['dietyName'][$i],
							"serviceOccurrencesNo" => @$event_cart_items['serviceOccurrencesNo'][$i],
							"fullPackage" => @$event_cart_items['fullPackage'][$i],
							"oldServiceAmount" => isset($event_cart_items['oldServiceAmount'][$i]) && $event_cart_items['oldServiceAmount'][$i] > 0 ? $event_cart_items['oldServiceAmount'][$i] : $event_cart_items['serviceAmount'][$i],
							"discountedAmount" => isset($event_cart_items['discountedAmount'][$i]) && $event_cart_items['discountedAmount'][$i] > 0 ? $event_cart_items['discountedAmount'][$i] : 0,
						);
					}
				}
			}
	

			if (!empty($books_cart_items)) {
				for ($i = 0; $i < count($books_cart_items['ids']); $i++) {

					$dataWithAmount[] = array(
						"_id" => $books_cart_items['ids'][$i],
						"date" => date("m/d/Y"),
						"serviceImage" => $books_cart_items['image'][$i],
						"zeroAllowInd" => $books_cart_items['zeroAllowInd'][$i],
						"carryOutPrice" => $books_cart_items['carryOutPrice'][$i],
						"menuCategory" => $books_cart_items['menuCategory'][$i],
						"carryout" => $books_cart_items['carryout'][$i],
						"startDate" => date("m/d/Y"),
						"serviceCategory" => $books_cart_items['serviceCategory'][$i],
						"serviceType" => $books_cart_items['serviceType'][$i],
						"serviceName" => $books_cart_items['serviceName'][$i],
						"serviceDesc" => $books_cart_items['description'][$i],
						"serviceAmount" => $books_cart_items['serviceAmount'][$i],
						"qty" => $books_cart_items['qty'][$i],
						"ServiceId" => $books_cart_items['ids'][$i],
						"day" => "",
						"totalAmount" => $books_cart_items['totalAmount'][$i],
						"time" => date("h:i A")
					);
				}
			}
			$dataWithAmountJson = json_encode($dataWithAmount);
			
			// var_dump($dataWithAmountJson);die();
			if (!empty($dataWithAmount)) {


				$ch = curl_init();

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

					\"data\": $dataWithAmountJson, 

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

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

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

				}     
				");

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


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

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

				$result = curl_exec($ch);

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

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

				// print_r($sess_temp_order_details);


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

			if ($PaymentStatus != 'TEMP') {

				if (!empty($this->session->userdata('service_cart'))) {
					$this->session->unset_userdata('service_cart');
				}


				if (!empty($this->session->userdata('sponsorship_cart'))) {
					$this->session->unset_userdata('sponsorship_cart');
				}

				if (!empty($this->session->userdata('donations_cart'))) {
					$this->session->unset_userdata('donations_cart');
				}
				if (!empty($this->session->userdata('events_cart'))) {

					$this->session->unset_userdata('events_cart');
				}
				if (!empty($this->session->userdata('books_cart'))) {

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

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



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

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

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


		$ch = curl_init();

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

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

		}     
		");

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

		$headers = array();

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

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

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


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

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

			
				if (!empty($this->session->userdata('service_cart'))) {
					$this->session->unset_userdata('service_cart');
				}


				if (!empty($this->session->userdata('sponsorship_cart'))) {
					$this->session->unset_userdata('sponsorship_cart');
				}

				if (!empty($this->session->userdata('donations_cart'))) {
					$this->session->unset_userdata('donations_cart');
				}
				if (!empty($this->session->userdata('events_cart'))) {

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

			if (!empty($this->session->userdata('books_cart'))) {

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

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

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

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

			return $response = json_decode($result);
		}
	}
}
