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

class RecurringSponsorNow extends MY_Controller {

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

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


	public function getRecurringSponsorServices($serviceType)
	{


		if ($serviceType == 'recurring-donations') {
			$serviceType = 'RECURRING DONATIONS';
		}

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


		$data['sponsorType_details'] = getSponsorTypes($serviceType);
		$data['page'] = 'RECURRING-DONATIONS';
		$data['title'] = 'RECURRING DONATIONS';
		$data['serviceType'] = $serviceType;
		$this->load->view('recurring-donations/recurring-donations', $data);
	}

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


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




	public function AddToCart(){


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



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

			if ($paymentSource == 'card') {
				$paymentSource = 'CREDIT CARD';
			}else{
				$paymentSource = 'PAYPAL WALLET';
			}
			$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++) {

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

				}
			}

			$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\": \"".$paymentSource."\", 
					\"etKitchenTIp\": \"".$PaymentStatus."\", 

					\"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 ($response2->statusCode == 1) {
					$response3 = $this->updateTransactionStatus($response2->data[0]->_id, $response2->data[0]->invoiceNo, $PaymentStatus);
				}

			}



			if ($PaymentStatus != 'TEMP') {

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

					if (@$cart_data['cart_type'] == 'SPONSORSHIP') {
						$this->session->unset_userdata('recurring_donations_cart');
					}

					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('recurring_donations_cart');

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

			return $response = json_decode($result);
		}

	}

	public function ViewCart(){
		$currency 				= '';
		$data['currency'] 		= $this->$currency;
		$data['page'] 			= 'RECURRING-DONATIONS';
		$data['title'] 			= 'RECURRING-DONATIONS';
		$data['session_data'] 	= 'recurring_donations_cart';
		$this->load->view('recurring-donations/recurring-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');
		$cart_items = $this->session->userdata('recurring_donations_cart');
		$total_price = $cart_items['totalPrice'];
		$row_price = 0;
		foreach($cart_items['ids'] as $key => $id){
			if($id == $row_id){
            // remove the row from the cart data
				$row_price = $cart_items['serviceAmount'][$key];
				unset($cart_items['ids'][$key]);
				unset($cart_items['serviceName'][$key]);
				unset($cart_items['description'][$key]);
				unset($cart_items['serviceAmount'][$key]);
				unset($cart_items['qty'][$key]);
				unset($cart_items['image'][$key]);
				break;
			}
		}
		$total_price -= $row_price;
		$cart_items['totalPrice'] = $total_price;
		$this->session->set_userdata('recurring_donations_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'] = 'RECURRING-DONATIONS';
			$data['title'] = 'Checkout';

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


			$this->load->view('recurring-donations/recurring-checkout',$data);


		}else{
			redirect(base_url());
		}
	}


	public function validateCard($card_number, $exp_date, $cvv, $card_holder){

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

		curl_setopt($ch, CURLOPT_URL, 'https://aspgen.vaaptech.com:9000/api/payment/validatePaymentCard');
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POST, 1);
		$data = array(
			"paymentAccountNumber" => $card_number,
			"expirationDate" => $exp_date,
			"securityCode" => $cvv,
			"name" => $card_holder,
			"street" => "street",
			"city" => "city",
			"state" => "VA",
			"zip" => "12345",
			"countryCode" => "",
			"phone" => base64_decode($this->session->userdata('phone')),
			"email" => base64_decode($this->session->userdata('email')),
			"clientId" => ApiBaseUrl()['clientID'],
			"amount" => 700
		);

		$json_data = json_encode($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, true);
		if (curl_errno($ch)) {
			echo 'Error:' . curl_error($ch);
		}
		curl_close($ch);
		return $response;
	}

	public function SubmitRecurringSponsors(){

		$debitFequency = $this->input->post('debitFequency') ? $this->input->post('debitFequency') : '';
		$startDailyDate = $this->input->post('startDailyDate') ? $this->input->post('startDailyDate') : '';
		$endDailyDate = $this->input->post('endDailyDate') ? $this->input->post('endDailyDate') : '';
		$startWeeklyDate = $this->input->post('startWeeklyDate') ? $this->input->post('startWeeklyDate') : '';
		$endWeeklyDate = $this->input->post('endWeeklyDate') ? $this->input->post('endWeeklyDate') : '';
		$startMonthlyDate = $this->input->post('startMonthlyDate') ? $this->input->post('startMonthlyDate') : '';
		$endMonthlyDate = $this->input->post('endMonthlyDate') ? $this->input->post('endMonthlyDate') : '';
		$selectAnualyMonthValue = $this->input->post('selectAnualyMonthValue') ? $this->input->post('selectAnualyMonthValue') : '';
		$selectAnualyDateValue = $this->input->post('selectAnualyDateValue') ?$this->input->post('selectAnualyDateValue') : '';
		$startAnualyDate = $this->input->post('startAnualyDate') ? $this->input->post('startAnualyDate') : '';
		$endAnualyDate = $this->input->post('endAnualyDate') ? $this->input->post('endAnualyDate') : '';
		
		$creditcard = $this->input->post('creditcard') ? $this->input->post('creditcard') : '';

		$card_number = $this->input->post('card-number') ? $this->input->post('card-number') : '';
		$exp_date = $this->input->post('exp-date') ? $this->input->post('exp-date') : '';
		$cvv = $this->input->post('cvv') ? $this->input->post('cvv') : '';
		$card_holder = $this->input->post('card-holder') ? $this->input->post('card-holder') : '';

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



		$validate_card_response = $this->validateCard($card_number, $exp_date, $cvv, $card_holder);
		

		// print_r($validate_card_response);

		
		$token = '';
		$OrganizationId = '';
		if ($validate_card_response['statusCode'] == 1) {
			$token = $validate_card_response['data']['token'];
			$OrganizationId = $validate_card_response['data']['authorizationCode'];
		}else{
			echo json_encode($validate_card_response);
			return;
		}



		$cart_data = $this->session->userdata('recurring_donations_cart');


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



			$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/bookingService/addPledgeForm');
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_POST, 1);
			$data = array(
				"clientId" => ApiBaseUrl()['clientID'],
				"dataJson" => array(
					"memberId" => $this->session->userdata('id'),
					"firstName" => "",
					"lastName" => "",
					"memberName" => $this->session->userdata('refDataName'),
					"prsnEmail" => base64_decode($this->session->userdata('email')),
					"prsnPhone" => base64_decode($this->session->userdata('phone')),
					"noOfPaymentName" => "",
					"paymentReminderName" => "",
					"serviceName" => $cart_data['serviceName'][$i],
					"serviceId" => $cart_data['ids'][$i],
					"serviceAmount" => $cart_data['serviceAmount'][$i],
					"pledgeForName" => "",
					"modeOfPaymentName" => "",
					"achBankAddress" => "",
					"achBankCode" => "",
					"achRoutingNo" => "",
					"achBankName" => "",
					"accNo" => "",
					"accName" => "",
					"bankName" => "",
					"checkNo" => "",
					"checkDate" => "",
					"cardZipCode" => "",
					"cvvNo" => $cvv,
					"expiryDate" => $exp_date,
					"cardNo" => $card_number,
					"cardHolderName" => $card_holder,
					"debitFequency" => $debitFequency,
					"startDailyDate" => $startDailyDate,
					"endDailyDate" => $endDailyDate,
					"startWeeklyDate" => $startWeeklyDate,
					"endWeeklyDate" => $endWeeklyDate,
					"selectWeeklyDay" => "",
					"startMonthlyDate" => $startMonthlyDate,
					"endMonthlyDate" => $endMonthlyDate,
					"selectmonthDate" => "",
					"selectAnualyMonthValue" => $selectAnualyMonthValue,
					"selectAnualyDateValue" => $selectAnualyDateValue,
					"startAnualyDate" => $startAnualyDate,
					"endAnualyDate" => $endAnualyDate,
					"OrganizationId" => $OrganizationId,
					"token" => $token
				)
			);

			$jsonData = json_encode($data);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);


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

			$payment_result = curl_exec($ch);
			$payment_response = json_decode($payment_result, true);;
			if (curl_errno($ch)) {
				echo 'Error:' . curl_error($ch);
			}
			curl_close($ch);

		}


		// print_r($payment_response);

		if ($payment_response['statusCode'] == 1) {
			$this->session->unset_userdata('recurring_donations_cart');
		}
		echo json_encode($payment_response);


	}

}