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

class MakePayments extends MY_Controller {

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

	}

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


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




	public function Checkout(){
		$data['GeneralSettings'] = GeneralSettings();
		if (!empty($this->session->userdata('logged_in')) && $this->session->userdata('logged_in') == 1) {
			$data['page'] = 'Make Payments';
			$data['title'] = 'Checkout';
			$data['session_data'] = 'make_payments_cart';
			$this->load->view('make-your-payments',$data);
		}else{
			redirect(base_url());
		}
	}


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

			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],
					"serviceCategory" => $cart_data['ctg'][$i],
					"serviceType" => $cart_data['serviceTypes'][$i],
					"serviceAmount" => $cart_data['serviceAmount'][$i],
					"qty" => $cart_data['qty'][$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."\", 
					\"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_due_payments_details = json_decode($result, true);

				$this->session->set_userdata('temp_payments_details', $sess_temp_due_payments_details['data'][0]);

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

			}

			if ($PaymentStatus != 'TEMP') {
				if (@$response2->statusCode == 1) {
					if(@$cart_data['cart_type'] == 'MAKE-PAYMENTS'){
						$this->session->unset_userdata('make_payments_cart');
						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_payments_details'))) {
			$invoiceNo = $this->session->userdata('temp_payments_details')['invoiceNo'];
			$id = $this->session->userdata('temp_payments_details')['_id'];
		}


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





		if (!empty($cart_data['ids'])) {


			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'].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\":\"".$cart_data['ids'][$i]."\",      
					\"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_payments_details');
			$this->session->unset_userdata('make_payments_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'] 			= 'Payments Cart';
		$data['title'] 			= 'Payments Cart';
		$data['session_data'] 	= 'make_payments_cart';
		$this->load->view('view-payments-cart',$data);
	}

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