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

class Events extends MY_Controller {

	public function __construct() {
		parent::__construct();
		$currency = '';
		$this->$currency =  GeneralSettings();

	}

	public function index($eventName, $eventId){

		$data['page'] = 'Events';
		$serviceId = $eventId;
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

		curl_setopt($ch, CURLOPT_URL, ApiBaseUrl()['url'].getServiceDetailbyId()['url']);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, "{          
			\"_id\": \"".$serviceId."\",          
			\"productId\":\" ".ApiBaseUrl()['productID']."\",           
			\"clientId\": \"".ApiBaseUrl()['clientID']."\"      
		}");

		$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);
		}
		$data['serviceDetails'] = json_decode(json_encode($response->data[0]), true);

		// $this->load->view('event-details',$data);
		$this->load->view('events/event-details',$data);

	}

	public function addCart(){

		
		$data = $this->input->post();


		if($data)
		{
			$this->session->set_userdata('events_cart', $data);

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

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

				$includeSankalpam = 'NO';
			}
		}


		$response = array(
			'status' => '1', 
			'message' => "Success",
			'totalPrice' => $this->input->post('totalPrice'),
			'includeSankalpam' => $includeSankalpam
		);
		echo json_encode($response);

	}


	public function Checkout(){
		$data['GeneralSettings'] = GeneralSettings();
		$data['CheckoutDonationSettings'] = CheckoutDonationSettings();
		if (!empty($this->session->userdata('logged_in')) && $this->session->userdata('logged_in') == 1) {
			$data['page'] = 'Events';
			$data['title'] = 'Checkout';
			$data['userDetails'] =  getUserDetails()->data[0];
			$data['nakshtra_data'] = getNakshtra()['data'];
			$data['gotra_data'] = getGotra()['data'];
			$data['rashi_data'] = getRashi()['data'];
			$data['session_data'] = 'events_cart';
			// $this->load->view('events/events-checkout',$data);
			$this->load->view('common/checkout',$data);
		}else{
			redirect(base_url());
		}
	}


	public function AddToCart(){



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

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

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

			if ($paymentSource == 'card') {
				$paymentMode = 'CREDIT CARD';
			}else if($paymentSource == 'MPI'){
				$paymentMode = 'CREDIT CARD';
			}else{
				$paymentMode = 'CREDIT CARD';
			}
			
			$PaymentStatus = $this->input->post('status');

			$dataWithAmount = array();

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

				$dataWithAmount[] = array(
					"_id" => $cart_data['ids'][$i],
					"ServiceId" => $cart_data['ids'][$i],
					"serviceName" => $cart_data['serviceName'][$i],
					"startDate" => @$cart_data['startDate'][$i],
					"serviceCategory" => $cart_data['ctg'][$i],
					"serviceType" => $cart_data['serviceTypes'][$i],
					"serviceAmount" => $cart_data['serviceAmount'][$i],
					"oldServiceAmount" => isset($cart_data['oldServiceAmount'][$i]) && $cart_data['oldServiceAmount'][$i] > 0 ? $cart_data['oldServiceAmount'][$i] :$cart_data['serviceAmount'][$i],
					"discountedAmount" => isset($cart_data['discountedAmount'][$i]) && $cart_data['discountedAmount'][$i] > 0 ? $cart_data['discountedAmount'][$i] :0,
					"qty" => $cart_data['qty'][$i],
					"day" => "",
					"serviceAddress" => "",
					"cartCreDate" => date("m/d/Y"),
					"cartCreTime" => date("h:i A")
				);
			}

			$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\", 
					\"etKitchenTIp\": \"".$PaymentStatus."\",  
					\"attemptType\": \"".$PaymentStatus."\", 
					\"cartCreDate\": \"".date("m/d/Y")."\",
					\"cartCreTime\": \"".date("h:i A")."\", 
					\"bankName\":\"\" ,
					\"chequeNo\":\"\" , 
					\"chequeAmount\":\"\" , 
					\"chequeDate\": \"\", 

					\"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);

				$response = json_decode($result);

				$sess_temp_events_order_details = json_decode($result, true);

				$this->session->set_userdata('temp_events_order_details', $sess_temp_events_order_details['data'][0]);

			

				if ($PaymentStatus != 'TEMP') {

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

						if(@$cart_data['cart_type'] == 'EVENTS'){

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

						echo json_encode($response);
					}

				}else{
					
						echo json_encode($response);
				}

			}
		}


	}


	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_events_order_details'))) {
			$invoiceNo = $this->session->userdata('temp_events_order_details')['invoiceNo'];
			$id = $this->session->userdata('temp_events_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_events_order_details');
			$this->session->unset_userdata('events_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);

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

	}

	public function ViewCart(){
		$currency 				= '';
		$data['currency'] 		= $this->$currency;
		$data['page'] 			= 'Events';
		$data['title'] 			= 'Events Cart';
		$data['session_data'] 	= 'events_cart';
		$this->load->view('events/view-events-cart',$data);
	}

	public function delete_cart_row(){
		$row_id = $this->input->post('row_id');
		$cart_items = $this->session->userdata('events_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;
			}
		}
		foreach ($cart_items as $cart_key => &$cart_value) {
			if($cart_key !='totalPrice'){
			if (is_array($cart_value)) {
				$cart_value = array_values($cart_value);
			}
		}
		}
		$total_price -= $row_price;
		$cart_items['totalPrice'] = $total_price;
		$this->session->set_userdata('events_cart', $cart_items);
		echo json_encode(array('status' => 'success'));
	}


	public function allUpcomingEvents(){
		$data['page'] = 'Events';
		$data['title'] = 'Events';
		$filter['query'] = ['aspectType'=>'ServiceSetup','serviceCategoryTypes'=>'EVENTS', 'sourceTypes' => 'WEBSITE', 'status' => 'ACTIVE', '$expr' => ['$eq' => ['$parentService', '']]];

		$data['upcoming_events'] =  getServiceRequestData($filter);
		$this->load->view('events/all-upcoming-events', $data);
	}

	public function todayEvents(){
		$data['page'] = 'Events';
		$data['title'] = 'Events';
		$filter['query'] = ['aspectType'=>'ServiceSetup','serviceCategoryTypes'=>'EVENTS', 'sourceTypes' => 'WEBSITE', 'status' => 'ACTIVE', '$expr' => ['$eq' => ['$parentService', '']]];

		$data['upcoming_events'] =  getServiceRequestData($filter);
		$this->load->view('events/today-events', $data);
	}

}