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

class Donations extends MY_Controller
{

	public function __construct()
	{
		parent::__construct();
		$currency = '';
		$this->$currency =  GeneralSettings();
	}
	public function index()
	{
		$data['donationCategoryTypes'] = getDonationsCatTypes();
		$currency = '';
		$data['currency'] = $this->$currency;
		$data['page'] = 'DONATIONS';
		$data['title'] = 'Donations';
		$this->load->view('donations/donations', $data);
	}


	public function TempleImprovemetsProjectDonations()
	{
		$data['donationCategoryTypes'] = getDonationsCatTypes();
		$currency = '';
		$data['currency'] = $this->$currency;
		$data['page'] = 'Donations';
		$data['title'] = 'Donations';
		$this->load->view('donations/donations-by-donation-type', $data);
	}

	public function addCart()
	{



		$data = $this->input->post();
		// var_dump($data);
		if (isset($data['serviceAmount'])) {
			// Find the indexes where serviceAmount is 0.00
			$indexesToRemove = array_keys($data['serviceAmount'], '0.00');

			// Remove the elements with 0.00 serviceAmount from arrays
			foreach ($data as &$array) {
				if (is_array($array)) {
					foreach ($indexesToRemove as $index) {
						unset($array[$index]);
					}
					// Re-index the array to reset keys
					$array = array_values($array);
				}
			}


			// print_r($data);


			if ($data) {
				$this->session->set_userdata('donations_cart', $data);
			}
		} else {
			$this->session->unset_userdata('donations_cart');
		}

		$response = array(
			'status' => '1',
			'message' => "Success"
		);
		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'] = 'Donations';
			$data['title'] = 'Checkout';
			$data['session_data'] = 'donations_cart';
			// $this->load->view('donations/donations-checkout', $data);
			$this->load->view('common/checkout', $data);
		} else {
			redirect(base_url());
		}
	}



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

			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],
					"ServiceId" => $cart_data['ids'][$i],
					"serviceCategory" => $cart_data['ctg'][$i],
					"serviceType" => $cart_data['serviceTypes'][$i],
					"serviceAmount" => $cart_data['serviceAmount'][$i],
					"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\", 
					\"paymentSource\": \"" . $paymentSource_data . "\", 
					\"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_donations_order_details = json_decode($result, true);

				$this->session->set_userdata('temp_donations_order_details', $sess_temp_donations_order_details['data'][0]);

				if ($response->statusCode == 1) {
					$response2 = $this->updateTransactionStatus($response->data[0]->_id, $response->data[0]->invoiceNo, $PaymentStatus);

					if ($paymentSource == 'MPI') {
						$obj = new stdClass();
						$obj->statusCode = $response2->statusCode;
						$obj->message = $response2->message;
						$array = (array)$obj;
						if ($PaymentStatus != 'TEMP') {
							if (@$response2->statusCode == 1) {
								if (@$cart_data['cart_type'] == 'DONATIONS') {
									$this->session->unset_userdata('donations_cart');
									echo json_encode($array);
								} else {
									echo json_encode($response2);
								}
							} else {
								echo json_encode($response2);
							}
						} else {
							echo json_encode($response2);
						}
						// echo json_encode($array);
					} else {
						echo json_encode($response2);
					}
				} else {

					echo json_encode($response);
				}
			} else {
				$obj = new stdClass();
				$obj->statusCode = -1;
				$obj->message = "Something went wrong";
				$array = (array)$obj;
				echo json_encode($array);
			}
		} else {
			$obj = new stdClass();
			$obj->statusCode = -1;
			$obj->message = "Something went wrong";
			$array = (array)$obj;
			echo json_encode($array);
		}
	}

	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_donations_order_details'))) {
			$invoiceNo = $this->session->userdata('temp_donations_order_details')['invoiceNo'];
			$id = $this->session->userdata('temp_donations_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 . "\"

		}     
		");
		// \"paymentDescription\": \"".$paymentDescription."\"

		$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_donations_order_details');
			$this->session->unset_userdata('donations_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);

			$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'] 			= 'Donations Cart';
		$data['title'] 			= 'Donations Cart';
		$data['session_data'] 	= 'donations_cart';
		$this->load->view('donations/view-donations-cart', $data);
	}

	public function delete_cart_row()
	{
		$row_id = $this->input->post('row_id');
		$cart_items = $this->session->userdata('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;
			}
		}
		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('donations_cart', $cart_items);
		echo json_encode(array('status' => 'success'));
	}

	public function QRDonation()
	{
		$data['donationCategoryTypes'] = getDonationsCatTypes();
		$currency = '';
		$data['currency'] = $this->$currency;
		$data['page'] = 'Donations';
		$data['title'] = 'Donations';
		$this->load->view('donations/qr-donations', $data);
	}
}
