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

class SponsorNow extends MY_Controller
{

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

		$this->$currency =  GeneralSettings();
	}

	public function index()
	{


		$data['page'] = 'Sponsor Now';
		$data['title'] = 'Sponsor Now';

		$data['sponsorships'] = getSponsorTypes();

		$this->load->view('sponsor-now-services/sponsor-now-types', $data);
	}

	public function getSponsorServices($serviceType)
	{

		$serviceType = urldecode($serviceType);

		if (!empty($this->session->userdata('sponsorship_cart')['serviceTypes'])) {
			$session_array = $this->session->userdata('sponsorship_cart')['serviceTypes'];
			if ($this->session->userdata('sponsorship_cart')['serviceTypes']['0'] != $serviceType) {
				$this->session->unset_userdata('sponsorship_cart');
			}
		}


		$data['sponsorType_details'] = getSponsorTypes($serviceType);
		$data['page'] = 'Sponsor Now';
		$data['title'] = 'Sponsor Now';
		$data['serviceType'] = $serviceType;
		$this->load->view('sponsor-now-services/sponsor-now-services', $data);
	}

	public function addCart()
	{
		if ($this->input->post()) {
			$this->session->set_userdata('sponsorship_cart', $this->input->post());
		}


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



	public function AddToCart(){



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



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

			if ($paymentSource == 'CAW') {
				$paymentSource_data = 'CAW_CARD_NOT_PRESENT';

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


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

			$cart_data = json_decode($this->input->post('cart_data'), true);

			$dataWithAmount = array();
			$serviceRequest = array();

			for ($i = 0; $i < count($cart_data['ids']); $i++) {

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

						$dataWithAmount[] = array(
							"_id" => $cart_data['ids'][$i],
							"ServiceId" => $cart_data['ids'][$i],
							"serviceName" => $cart_data['serviceName'][$i],
							"serviceCategory" => $cart_data['ctg'][$i],
							"serviceType" => $cart_data['serviceTypes'][$i],
							"serviceAmount" => $cart_data['serviceAmount'][$i],
							"startDate" => $startDate,
							"qty" => $cart_data['qty'][$i],
							"time" => @$cart_data['startTime'][$i],
							"day" => "",
							"serviceAddress" => "",
							"serviceDesc" => @$cart_data['service_desc'][$i]
						);
					}
				} else {

					$dataWithAmount[] = array(
						"_id" => $cart_data['ids'][$i],
						"ServiceId" => $cart_data['ids'][$i],
						"serviceName" => $cart_data['serviceName'][$i],
						"serviceCategory" => $cart_data['ctg'][$i],
						"serviceType" => $cart_data['serviceTypes'][$i],
						"serviceAmount" => $cart_data['serviceAmount'][$i],
						"startDate" => '',
						"qty" => $cart_data['qty'][$i],
						"time" => @$cart_data['startTime'][$i],
						"day" => "",
						"serviceAddress" => "",
						"serviceDesc" => @$cart_data['service_desc'][$i]
					);
				}
			}

			$dataWithAmountJson = json_encode($dataWithAmount);

			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\": \"\" , 
					\"generaldonations\": \"\" , 

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

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


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

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

				$result = curl_exec($ch);

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

				$response2 = json_decode($result);



				$sess_temp_order_details = json_decode($result, true);

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

			}



			if ($PaymentStatus != 'TEMP') {

				if (@$response2->statusCode == 1) {

					if (@$cart_data['cart_type'] == 'SPONSORSHIP') {
						$this->session->unset_userdata('sponsorship_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') {
			$response = json_decode($result);

			$this->session->unset_userdata('temp_order_details');
			$this->session->unset_userdata('sponsorship_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') {
			$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 {
			// echo 123456;

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

	public function ViewCart()
	{
		$currency 				= '';
		$data['currency'] 		= $this->$currency;
		$data['page'] 			= 'Sponsor Now';
		$data['title'] 			= 'Sponsorship Cart';
		$data['session_data'] 	= 'sponsorship_cart';
		$this->load->view('sponsor-now-services/view-cart', $data);
	}


	public function checkServiceAvailibilty()
	{



		$no_days = 30;


		if ($this->input->post()) {
			$formData = $this->input->post();

			$startDate 	 = $formData['startDate'] ? $formData['startDate'] : (date('m/d/Y'));
			$endDate 	 = $formData['endDate'] ? $formData['endDate'] : (date('m/d/Y', strtotime("+" . $no_days . " days")));


			$startTime = $formData['startTime'];
			$serviceName = $formData['serviceName'];
			$endTime 	 = $formData['endTime'];

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


			$details = getServiceAvailibiltydata($startDate, $startTime, $serviceName, $endDate, $endTime);



			$html = '';
			for ($i = 0; $i < $no_days; $i++) {
				$newDate = date('m/d/Y', strtotime("+" . $i . " days"));
				$BookingLimitPerDay 	 = $formData['BookingLimitPerDay'];

				if (!empty($details['data'])) {
					if (in_array($newDate, array_column($details['data'], '_id'))) {
						$BookingLimitPerDay = $BookingLimitPerDay - $details['data'][array_search($newDate, array_column($details['data'], '_id'))]['count'];
					}
				}


				$html .= '<tr>';
				$html .= '<td style="vertical-align: middle;padding: 20px;"> <strong> ' . $newDate . ' </strong></td>';
				$html .= '<td> <a href="javascript:void(0);" onclick="serviceAvailabilitybook(this);" class="btn btn-primary availability-btn" data-date="' . $newDate . '" data-service-id="' . $serviceID . '"  data-availability="' . $BookingLimitPerDay . '"> Availability (' . $BookingLimitPerDay . ')</a>   </td>';
				$html .= '</tr>';
			}


			$month1 = date('M', strtotime($startDate));
			$month2 = date('M', strtotime($endDate));

			if ($month1 == $month2) {
				$details['headerMonths'] = ' ( ' . $month1 . ' )';
			} else {
				$details['headerMonths'] = ' ( ' . $month1 . '-' . $month2 . ' )';
			}

			$details['servicesList'] = $html;

			echo json_encode($details);
		}
	}






	public function delete_cart_row()
	{
		$row_id 	= $this->input->post('row_id');
		$selected_date 	= $this->input->post('selected_date');

		$cart_items = $this->session->userdata('sponsorship_cart');
		$total_price = $cart_items['totalPrice'];
		$row_price = 0;



		foreach ($cart_items['ids'] as $key => $id) {
			if ($id == $row_id) {

				if (!empty($cart_items['startDate'][$key])) {
					$cartDateCount = explode(',', $cart_items['startDate'][$key]);

					$cartDateCount_arr = array();
					foreach ($cartDateCount as $keyk => $cartDateCount_val) {
						if (trim($cartDateCount_val) != trim($selected_date)) {
							$cartDateCount_arr[] = $cartDateCount_val;
						}
					}

					if (!empty($cartDateCount_arr)) {
						$cart_items['startDate'][$key] = implode(',', $cartDateCount_arr);
					}

					$row_price = $cart_items['serviceAmount'][$key] * $cart_items['qty'][$key];

					if (empty($cartDateCount_arr)) {
						unset($cart_items['ids'][$key]);
						unset($cart_items['qty'][$key]);
						unset($cart_items['serviceName'][$key]);
						unset($cart_items['description'][$key]);
						unset($cart_items['serviceAmount'][$key]);
						unset($cart_items['image'][$key]);
						unset($cart_items['startDate'][$key]);
						unset($cart_items['startTime'][$key]);
						unset($cart_items['cart_ctg'][$key]);
						unset($cart_items['serviceTypes'][$key]);
						unset($cart_items['payment_btn_check'][$key]);
						unset($cart_items['ctg'][$key]);
					}
				}else{
					$row_price = $cart_items['serviceAmount'][$key] * $cart_items['qty'][$key];
					unset($cart_items['ids'][$key]);
					unset($cart_items['qty'][$key]);
					unset($cart_items['serviceName'][$key]);
					unset($cart_items['description'][$key]);
					unset($cart_items['serviceAmount'][$key]);
					unset($cart_items['image'][$key]);
					unset($cart_items['startDate'][$key]);
					unset($cart_items['startTime'][$key]);
					unset($cart_items['cart_ctg'][$key]);
					unset($cart_items['serviceTypes'][$key]);
					unset($cart_items['payment_btn_check'][$key]);
					unset($cart_items['ctg'][$key]);
					
				}
				break;
			}
		}



		$total_price = $total_price - $row_price;
		// echo $total_price; 
		// echo $row_price; 


		// die();

		$cart_items['totalPrice'] = $total_price;
		$this->session->set_userdata('sponsorship_cart', $cart_items);
		echo json_encode(array('status' => 'success'));
	}


	public function getThithiNext90Days()
	{

		$tithi = $this->input->post('tithi');
		$datesArray = getThithiNext90Days($tithi);


		if (!empty($datesArray['data'])) {
			$dates = array();
			foreach ($datesArray['data'] as $key => $value) {

				$newDate = str_replace("T00:00:00.000Z", "", $value['startDate']);

				array_push($dates, $newDate);
				// $dates =  $newDate;
			}
			echo json_encode($dates);
			// echo '<pre>';
			// print_r($datesArray);
			// die();

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



	public function Checkout()
	{

		$data['GeneralSettings'] = GeneralSettings();

		// print_r($data['GeneralSettings']); die();
		if (!empty($this->session->userdata('logged_in')) && $this->session->userdata('logged_in') == 1) {

			$data['page'] = 'Sponsor Now';
			$data['title'] = 'Sponsorship Checkout';

			$data['session_data'] = 'sponsorship_cart';


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