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

class AkshayPatra extends MY_Controller
{

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

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

	public function index()
	{


		$data['page'] = 'Akshaya Patra';
		$data['title'] = 'Akshaya Patra';
		$data['header'] = 'Akshaya Patra';
		$json_data = json_encode([
			"componentConfig" => [
				"query" => [
					"aspectType" => "menu",
					"menuCategory" => "FOOD ITEM",
					"status" => "ACTIVE",
					"isDailyMenu" => false
				],
				"moduleName" => "Menu",
				"aspectType" => "menu",
				"userName" => "vaapadmin3230",
				"productID" => ApiBaseUrl()['productID'],
				"clientID" => ApiBaseUrl()['clientID'],
				"skip" => 0,
				"next" => 100000
			]
		]);

		$data['dailyMenu'] = getFilterData($json_data);

		$json_food_data = json_encode([
			"componentConfig" => [
				"query" => [
					"aspectType" => "menuType",
					"refDataCode" => "FOOD ITEM",
				],
				"moduleName" => "Master Data Management",
				"aspectType" => "menuType",
				"userName" => "vaapadmin3230",
				"productID" => ApiBaseUrl()['productID'],
				"clientID" => ApiBaseUrl()['clientID'],
				"skip" => 0,
				"next" => 1000
			]
		]);
		// var_dump($json_food_data);

		$data['fooItemsList'] = getFilterData($json_food_data);

		$data['userDetails'] = [];


		$this->load->view('akshaya-patra/index', $data);
	}
	public function List()
	{


		$data['page'] = 'Akshaya Patra';
		$data['title'] = 'Akshaya Patra';
		$data['header'] = 'Akshaya Patra';



		$json_data = json_encode([
			"componentConfig" => [
				"query" => [
					"aspectType" => "menu",
					"menuCategory" => "FOOD ITEM",
					"status" => "ACTIVE",
					"isDailyMenu" => false
				],
				"moduleName" => "Menu",
				"aspectType" => "menu",
				"userName" => "vaapadmin3230",
				"productID" => ApiBaseUrl()['productID'],
				"clientID" => ApiBaseUrl()['clientID'],
				"skip" => 0,
				"next" => 100000
			]
		]);

		// var_dump($json_data);
		$dailyMenu = getFilterData($json_data);



		$fooItemsList = [];
		$groupedMenu = []; // refDataCode ke hisaab se grouping

		foreach ($dailyMenu as $item) {
			// Step 1: unique refDataCode nikalna
			if (!in_array($item->refDataCode, $fooItemsList)) {
				$fooItemsList[] = $item->refDataCode;
			}

			// Step 2: same refDataCode ke items ko group karna
			$groupedMenu[$item->refDataCode][] = $item;
		}

		$data['dailyMenu'] = $dailyMenu;
		$data['groupedMenu'] = $groupedMenu;
		$data['fooItemsList'] = $fooItemsList;


		$data['userDetails'] = [];


		$this->load->view('akshaya-patra/list', $data);
	}


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

			$cartList = $this->session->userdata('akshaya_patra_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 delete_cart_row()
	{
		$row_id 	= $this->input->post('row_id');
		$selected_date 	= $this->input->post('selected_date');

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



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




				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['serviceCategoryTypes'][$key]);
				unset($cart_items['bookingtype'][$key]);
				unset($cart_items['ctg'][$key]);
				unset($cart_items['isServicePaid'][$key]);
				unset($cart_items['service_desc'][$key]);
				unset($cart_items['serviceOccurrencesNo'][$key]);
				unset($cart_items['oldServiceAmount'][$key]);
				unset($cart_items['discountedAmount'][$key]);
				unset($cart_items['trayType'][$key]);
				if (isset($cart_items['fullPackage'][$key])) {
					unset($cart_items['fullPackage'][$key]);
				}
				if (isset($cart_items['isDietySelected'][$key])) {
					unset($cart_items['isDietySelected'][$key]);
				}
				if (isset($cart_items['dietyName'][$key])) {
					unset($cart_items['dietyName'][$key]);
				}
				if (isset($cart_items['disclaimerText'][$key])) {
					unset($cart_items['disclaimerText'][$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 = (float)$total_price - (float)$row_price;
		// echo $total_price; die();

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






	public function clear_cart()
	{

		$session_data = $this->session->userdata('akshaya_patra_cart');
		if (!empty($session_data['ids'])) {
			$this->session->unset_userdata('akshaya_patra_cart');
		}
		redirect(base_url('admin/prasadam'));
	}
	public function ValidateCheckout()
	{
		$returnStatus = ValidateAkshayaPatraCheckout();

		echo json_encode($returnStatus);
	}

	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 = $this->session->userdata('akshaya_patra_cart');
			// var_dump($cart_data);
			if (!is_array($cart_data)) {
				$cart_data = json_decode($this->input->post('akshaya_patra_cart'), true);
			}
			// var_dump($cart_data);die();

			$dataWithAmount = array();
			$etKitchenTIp = @$this->input->post('etKitchenTIp') ?? 0;
			$delivery = @$this->input->post('delivery');
			if ($delivery == 'Delivery') {
				$address = @$this->input->post('address');
				$City = @$this->input->post('City');
				$state = @$this->input->post('state');
				$zipcode = @$this->input->post('zipcode');
			} else {
				$address = "";
				$City = "";
				$state = "";
				$zipcode = "";
			}

			$deliveryDetails = new stdClass();

			$deliveryDetails->delivery = $delivery;
			$deliveryDetails->delivery = $delivery;
			$deliveryDetails->address = $address;
			$deliveryDetails->City = $City;
			$deliveryDetails->state = $state;
			$deliveryDetails->zipcode = $zipcode;
			$deliveryDetails->memberName = $this->session->userdata('refDataName');

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

				$payment_type_check = @$cart_data['bookingtype'][$i];


				$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],
					"serviceCategory" => $cart_data['serviceCategoryTypes'][$i],
					"serviceAmount" => $cart_data['serviceAmount'][$i],
					"trayType" => @$cart_data['trayType'][$i],
					"startDate" => '',
					"qty" => $cart_data['qty'][$i],
					"time" => @$cart_data['startTime'][$i],
					"bookingType" => @$payment_type_check,
					"day" => "",
					"serviceAddress" => "",
					"cartCreDate" => date("m/d/Y"),
					"cartCreTime" => date("h:i A"),
					"isServicePaid" => @$cart_data['isServicePaid'][$i],
					"serviceDesc" => @$cart_data['service_desc'][$i],
					"serviceOccurrencesNo" => @$cart_data['serviceOccurrencesNo'][$i],
					"fullPackage" => @$cart_data['fullPackage'][$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,
				);
			}

			$dataWithAmountJson = json_encode($dataWithAmount);

			// var_dump($dataWithAmountJson);die();
			if (!empty($dataWithAmount)) {


				$ch = curl_init();

				$eventDetails = new stdClass();

				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, 
					\"eventDetail\": {}, 

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

					\"bankName\":\"\" ,
					\"chequeNo\":\"\" , 
					\"chequeAmount\":\"\" , 
					\"chequeDate\": \"\", 
					\"tenderAmount\": \"\", 
					\"pickupTime\": \"\", 
					\"serviceImage\": \"\", 
					\"serviceName\": \"\", 
					\"serviceCategory\": \"\", 
					\"serviceType\": \"\", 
					\"startTime\": \"\", 
					\"endTime\": \"\", 
					\"uniteType\": \"\", 
					\"costPerUnitType\": \"\", 
					\"serviceAmount\": \"\", 
					\"acharyasanbhavana\": \"" . @$this->input->post('acharya_sambhavana') . "\", 
					\"generaldonations\": \"" . @$this->input->post('general_donation') . "\", 

					\"totalAmount\": " . $this->input->post('totalPrice') . ", 
					\"transactionId\":\"" . $this->input->post('transaction_id') . "\",
					\"source\":\"WEBSITE\",
					
					\"deliveryDetails\": " . json_encode($deliveryDetails) . ",
					\"deliveryTime\": \"" . date("h:i A",strtotime($this->input->post('deliveryTime'))) . "\",
					\"deliveryDate\": \"" . $this->input->post('deliveryDate') . "\",
					\"delivery\": \"" . $this->input->post('delivery') . "\",
					\"etKitchenTIp\": \"" . $etKitchenTIp . "\"
					

				}     
				");


				/*,
					\"formAction\": \"" . @$this->input->post('formAction') . "\"
					*/

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



				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'];
		}
	$pendingAmount = (float)@$this->input->post('pendingAmount');
		$advanceAmount = (float)@$this->input->post('advanceAmount');
		$totalAmount =(float) @$this->input->post('totalAmount');

		$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_URL, ApiBaseUrl()['url'] . "api/bookingService/updateCateringTransactionStatus");
		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 . "\",
			\"advanceAmount\": \"" . $advanceAmount . "\",
			\"pendingAmount\": \"" . $pendingAmount . "\",
			\"totalAmount\": \"" . $totalAmount . "\"

		}     
		");
	
		$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' || $PaymentStatus == 'PARTIALLY_COMPLETED')) {
			// print_r($result);die();
			$response = json_decode($result);

			$this->session->unset_userdata('temp_order_details');
			$this->session->unset_userdata('akshaya_patra_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);
		}
	}

	public function checkout_prasadam_web()
	{
		$session_data = $this->session->userdata('akshaya_patra_cart');
		if (!empty($session_data['ids']) && ValidateAkshayaPatraCheckout()) {
			$response = getUserDetails();
			if ($response->statusCode == 1) {
				$data['page'] = 'Akshaya Patra';
				$data['title'] = 'Akshaya Patra';
				$data['header'] = 'Akshaya Patra';
				$data['GetState'] = GetState();
				$data['dailyMenu'] = getDailyMenuDevotee();
				$data['userDetails'] = $response->data[0];
				// $this->load->view('akshaya-patra/list', $data);
				$this->load->view('akshaya-patra/checkout', $data);
			} else {
				echo json_encode('User not found!!');
				$this->session->unset_userdata('logged_in');
				redirect(base_url('akshaya-patra'));
			}
		} else {
			// echo "okkk";die();
			redirect(base_url('akshaya-patra'));
		}
	}
}
