<?php

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



class Order extends CI_Controller

{



	public function checkout()

	{



		$address = $this->session->userdata('address');

		$deliveryData = $this->session->userdata('deliveryData');





		$data = $deliveryData;

		$data['lat'] = @$address['lat'];

		$data['lng'] = @$address['lng'];



		$response = apiCall('preCheckout', $data, '');



		if ($_SESSION['transaction_type'] == null) {

			$this->session->set_flashdata('error', "Please select Order type (Delivery/Pickup)");

			redirect('menu');
		}



		if ($response['code'] != 1) {

			$this->session->set_flashdata('error', $response['msg']);

			redirect('menu');
		}



		$this->session->set_userdata('deliveryData', $deliveryData);

		if ($this->session->userdata('user')) {

			redirect('order/payment_option');
		}

		//	}



		$resturantInfo = apicall('getRestaurantInfo');

		$this->session->set_userdata('resturantInfo', $resturantInfo['details']);

		renderView($this, 'order/checkout');
	}





	public function guestcheckout()

	{

		$deliveryData = $this->session->userdata('deliveryData');
        $merchantinfo = $this->session->userdata('merchantInfo');


		$address = $this->session->userdata('address');

		// 	    $deliveryData['lat'] = @$address['lat'];

		// 		$deliveryData['lng'] = @$address['lng'];

		$deliverydata['lat'] = isset($address['lat']) ? @$address['lat'] : $merchantinfo['latitude'];

		$deliverydata['lng'] = isset($address['lng']) ? @$address['lng'] : $merchantinfo['lontitude'];




		$cart = apiCall('loadCart', $deliveryData, '');

		//p($cart);

		$total = 0;
		$subtotal = 0;
		if (isset($cart['details'])) {
		    $details = $cart['details'];
		    
		    if (isset($details['data'])) {
		        $cartData = $details['data'];
		        $total = $cartData['total']['total'];
		        $subtotal = $cartData['total']['subtotal'];
		    }
		}

		$response = apiCall('getMobileCodeList');

		$this->session->set_userdata('is_guest_login', 1);



		$loadPaymentList = apiCall('loadPaymentList', ['transaction_type' => $deliveryData['transaction_type'] ?? '', 'total_amount' => $total, 'subtotal_amount' => $subtotal], '');



		renderView($this, 'order/payment_option', [

			'guestcheckout' => true,

			'address' => $address,

			'deliveryData' => $deliveryData,

			'countrylist' => $response['details']['data'],

			'loadPaymentList' => $loadPaymentList['details']['data'],

			'provider_list' => $loadPaymentList['details']['provider_list'],

		]);
	}



	public function payment_option()

	{



		$addressbook = apiCall('AddressBookList');

		$response = apiCall('getMobileCodeList');

		$deliveryData = $this->session->userdata('deliveryData');



		$address = $this->session->userdata('address');

		$cart = apiCall('loadCart', $deliveryData, '');

		$total = 0;
		$subtotal = 0;
		if (isset($cart['details'])) {
		    $details = $cart['details'];
		    
		    if (isset($details['data'])) {
		        $cartData = $details['data'];
		        $total = $cartData['total']['total'];
		        $subtotal = $cartData['total']['subtotal'];
		    }
		}

		$user = $this->session->userdata('user');



		$loadPaymentList = apiCall('loadPaymentList', ['transaction_type' => $deliveryData['transaction_type'] ?? '', 'total_amount' => $total, 'subtotal_amount' => $subtotal], '');

		//p($loadPaymentList['details']['provider_list']); 

		renderView($this, 'order/payment_option', [

			'user' => $user,

			'address' => $address,

			'deliveryData' => $deliveryData,

			'countrylist' => $response['details']['data'],

			'addressbooklist' => $addressbook['details'],

			'loadPaymentList' => $loadPaymentList['details']['data'],

			'provider_list' => $loadPaymentList['details']['provider_list'],

		]);
	}



	public function addressdata()

	{



		$data = apiCall('AddressBookListById', ['id' => $_POST['id']], '');

		echo json_encode($data);
	}



	public function getreview()

	{



		$order_id = $_POST['order_id'];

		$html = $this->load->view('order/review', ['order_id' => $order_id], TRUE);

		echo $html;
	}







	// 	public function load_cart()

	// 	{

	// 		$data = [];

	// 		$address = $this->session->userdata('address');

	// 		if ($address) {

	// 			$data['lat'] = @$address['lat'];

	// 			$data['lng'] = @$address['lng'];

	// 		}

	// 		$deliveryData = $this->session->userdata('deliveryData');



	// 		$data['transaction_type'] = $deliveryData['transaction_type'];



	// 		$cart = apiCall('loadCart', $data,'');



	// 		$this->load->view('order/cart', ['cart' => $cart['details']]);

	// 	}



	public function load_cart()

	{

		$data = [];

		$address = $this->session->userdata('address');

		$merchantinfo = $this->session->userdata('merchantInfo');

		/*	if ($address) {*/

		$data['lat'] = isset($address['lat']) ? @$address['lat'] : $merchantinfo['latitude'];

		$data['lng'] = isset($address['lng']) ? @$address['lng'] : $merchantinfo['lontitude'];

		/*	}*/



		$data['transaction_type'] = $this->session->userdata('transaction_type');



		$cart = apiCall('loadCart', $data, '');

        $cartDetails = [];
        if (isset($cart) && is_array($cart)) {
            $cartDetails = $cart['details'];
        }

		$this->session->set_userdata('cart', $cartDetails);

		//p($cart);

		$dateList = $this->session->userdata('dateList');

		//$timeList=$this->session->userdata('timeList');



		$this->load->view('order/cart', ['cart' => $cartDetails, 'dateList' => $dateList]);
	}



	public function confirm_order()

	{



		$address = $this->session->userdata('address');

		if (!isset($address['lat']) || $address['lat'] == '') {

			$this->session->set_flashdata('error', "Please select delivery address!");

			redirect('menu');
		}

		$data = [];

		$this->form_validation->set_rules('payment_opt', 'Payment Option', 'required');

		$this->form_validation->set_rules('street', 'Street', 'required');

		$this->form_validation->set_rules('city', 'City', 'required');

		$this->form_validation->set_rules('state', 'State', 'required');

		$this->form_validation->set_rules('zipcode', 'ZipCode', 'required');

		$this->form_validation->set_rules('contact_phone', 'Contact Phone', 'required');

		$this->form_validation->set_rules('location_name', 'Location Name', 'required');

		if ($this->input->server('REQUEST_METHOD') == 'POST') {

			//if ($this->form_validation->run() == TRUE) {

			$inst = $this->input->post('delivery_instruction');

			$deliveryData = $this->session->userdata('deliveryData');



			$address = [

				'street' => $this->input->post('street'),

				'city' => $this->input->post('city'),

				'state' => $this->input->post('state'),

				'zipcode' => $this->input->post('zipcode'),

				'country' => $this->input->post('country'),

				'country_code' => $this->input->post('country_code'),

				'contact_phone' => $this->input->post('contact_phone'),

				'lat' => $this->input->post('lat'),

				'lng' => $this->input->post('lng'),

			];

			$address['address'] = $address['street'] . ' , ' . $address['city'] . ' , ' . $address['state'] . ' , ' . $address['country'];



			$this->session->set_userdata('address', $address);

			$address = $this->session->userdata('address');



			$data = [

				'street' => $address['street'],

				'city' => $address['city'],

				'state' => $address['state'],

				'zipcode' => $address['zipcode'],

				'country' => $address['country'],

				'country_code' => $address['country_code'],

				'contact_phone' => $address['contact_phone'],

				'transaction_type' => $deliveryData['transaction_type'],

				'delivery_date' => $deliveryData['delivery_date'],

				'delivery_time' => $deliveryData['delivery_time'],

				'delivery_asap' => $deliveryData['delivery_asap'],

				'payment_provider' => $this->input->post('payment_opt'),

				'voucher_name' => $this->input->post('voucher_code'),

				'pickup_contact' => $this->input->post('contact_phone'),

				'delivery_instruction' => $inst,

				'location_name' => $this->input->post('location_name'),

				'mapbox_drag_map' => 'true',

				'mapbox_drag_end' => 'true',

				'order_change' => $this->input->post('order_change'),

				'lat' => @$address['lat'],

				'lng' => @$address['lng'],

			];

			$response = apiCall('setDeliveryAddress', $data);

			//p($response);	

			if ($response['code'] == 1) {

				$this->session->set_userdata('orderconfirmData', $data);
			} else {

				$cart = apiCall('loadCart', $data);



				$this->session->set_flashdata('error', 'Delivery is not available to your address');

				redirect('order/payment_option');
			}



			//}

			// else{

			//     $this->session->set_flashdata('error', 'something went to wrong');

			//     redirect('order/payment_option');

			// }

		}

		$address = $this->session->userdata('address');

		if ($address) {

			$data['lat'] = @$address['lat'];

			$data['lng'] = @$address['lng'];
		}

		$cart = apiCall('loadCart', $data);



		renderView($this, 'order/confirm_order', ['cart' => $cart['details']]);
	}





	public function place_order()

	{

		$address = $this->input->post('street') . $this->input->post('city') . $this->input->post('state') . $this->input->post('zipcode') . $this->input->post('country');

		$lat_res = apiCall('getgeodecodeAddress', ['address' => $address], '');

        $lat = '';
        $long = '';
		if ($lat_res) {
		    $lat = $lat_res['details']['data']['lat'];
		    $long = $lat_res['details']['data']['long'];
		}



		$deliveryData = $this->session->userdata('deliveryData');





		$inst = $this->input->post('delivery_instruction');

		$address = [

			'street' => $this->input->post('street'),

			'city' => $this->input->post('city'),

			'state' => $this->input->post('state'),

			'zipcode' => $this->input->post('zipcode'),

			'country' => $this->input->post('country'),

			'country_code' => $this->input->post('country_code'),

			'contact_phone' => $this->input->post('contact_phone'),

			'lat' => $lat,

			'lng' => $long,

		];



		$address['address'] = $address['street'] . ' , ' . $address['city'] . ' , ' . $address['state'] . ' , ' . $address['country'];



		$this->session->set_userdata('address', $address);

		$address = $this->session->userdata('address');



		$data = [

			'first_name' => @$this->input->post('first_name'),

			'email_address' => @$this->input->post('email_address'),

			'is_guest' => @$this->input->post('is_guest'),

			'street' => $address['street'],

			'city' => $address['city'],

			'state' => $address['state'],

			'zipcode' => $address['zipcode'],

			'country' => $address['country'],

			'country_code' => $address['country_code'],

			'contact_phone' => $address['contact_phone'],

			'transaction_type' => $deliveryData['transaction_type'],

			'delivery_date' => $deliveryData['delivery_date'],

			'delivery_time' => $deliveryData['delivery_time'],

			'delivery_asap' => $deliveryData['delivery_asap'],

			'payment_provider' => $this->input->post('payment_opt'),

			'payment_provider_name' => $this->input->post('payment_provider_name'),

			'voucher_name' => $this->input->post('voucher_code'),

			'pickup_contact' => $this->input->post('contact_phone'),

			'delivery_instruction' => $inst,

			'location_name' => $this->input->post('location_name'),

			'mapbox_drag_map' => 'true',

			'mapbox_drag_end' => 'true',

			'order_change' => $this->input->post('order_change'),

        	'lat' => $deliveryData['lat'],
        	
			'lng' => $deliveryData['lng'],

			'is_guest_login' => @$_SESSION['is_guest_login'],

			'cancel_url' => base_url('order/payment_option'),

			'redirect_url' => base_url('order/receipt'),
			'delivery_time' => $deliveryData['delivery_time'],
			'delivery_time' => $deliveryData['delivery_time'],
			'car_park_enable' =>$this->session->userdata('isplate'),
			'number_plate' =>$this->session->userdata('car_no'),
			
			
			
		];


		$cart = apiCall('loadCart', $data, '');
		

		if (isset($cart['details']['cart_error'][0])) {

			$this->session->set_flashdata('error', $cart['details']['cart_error'][0]);

			redirect('order/payment_option');
		}



		$response = apiCall('setDeliveryAddress', $data);

		if ($response['code'] == 1 || $data['transaction_type'] == 'pickup') {

			$this->session->set_userdata('orderconfirmData', $data);
			if ($data['is_guest'] == 1) {

				$response = apiCall('guestcheckout', $data, '');

				// p($response);

				if ($response['code'] == 1) {

					$this->session->set_userdata('token', $response['details']['client_info'][0]['token']);
				} else {

					$this->session->set_flashdata('error', $response['msg']);

					if ($data['is_guest'] == 1) {

						redirect('order/guestcheckout');
					}

					redirect('order/payment_option');
				}
			} else {

				$response = apiCall('payNow', $data);

				//p($response);

			}

			// p($response);

			if ($response['code'] == 1) {

				if ($data['is_guest'] == 1) {

					$user = $response['details']['client_info'][0];

				// 	$this->session->set_userdata('user', $user);

					$this->session->set_userdata('user_name', $user['first_name']);
				}

				$this->session->set_userdata('orderData', $response['details']);

				if (isset($response['details']['redirect_url']) && $response['details']['redirect_url']) {

					redirect($response['details']['redirect_url']);
				} else {

					redirect('order/receipt');
				}
			} else {

				$this->session->set_flashdata('error', $response['msg']);

				if ($data['is_guest'] == 1) {

					redirect('order/guestcheckout');
				}

				redirect('order/payment_option');
			}
		} else {



			$this->session->set_flashdata('error', $response['msg']);

			redirect('order/payment_option');
		}
	}



	public function receipt()

	{



		$orderData = $this->session->userdata('orderData');



		$address = $this->session->userdata('address');

		$deliveryData = $this->session->userdata('deliveryData');

		$this->session->set_userdata('isplate',0);
			$this->session->set_userdata('car_no','');

		$orderconfirmData = $this->session->userdata('orderconfirmData');

		$data = [

			'is_guest' => @$orderData['client_info'][0]['is_guest'],

			'client_id' => @$orderData['client_info'][0]['client_id'],

			'order_id' => $orderData['order_id'],

			'lat' => @$address['lat'],

			'lng' => @$address['lng'],

			'delivery_date' => $deliveryData['delivery_date'],

			'delivery_time' => $deliveryData['delivery_time'],

			'delivery_asap' => $deliveryData['delivery_asap'],

			'is_guest_login' => @$_SESSION['is_guest_login'],

		];



		$this->session->unset_userdata('deliveryData');



		$response = apiCall('ViewOrder', $data);


		


		renderView($this, 'order/receipt', ['receiptData' => $response['details']]);
	}



	public function view_receipt()

	{

		$address = $this->session->userdata('address');

		$data = [

			'order_id' => $this->input->post('order_id'),

			'lat' => $address['lat'],

			'lng' => $address['lng'],

		];

		$response = apiCall('ViewOrder', $data);



		$response = $this->load->view('order/view_receipt', ['receiptData' => $response['details']], TRUE);

		echo $response;
	}



	public function reorder()

	{

		$getloc = json_decode(file_get_contents("http://ipinfo.io/"));

		$coordinates = explode(",", $getloc->loc);

		$data = [

			'order_id' => $_POST['id'],

			'lat' => $_SESSION['lat'],

			'lng' => $_SESSION['lng'],

			'user_token' => $this->session->userdata('token'),

		];

		$response = apiCall('reorder', $data, '');



		echo $response;
	}



	public function checkvoucher()

	{

		$data = [

			'voucher_name' => $_POST['voucher_code']

		];

		$response = apiCall('applyVoucher', $data, '');

		//p($response);

		// echo $response;

		echo json_encode($response);
	}



	public function removevoucher()

	{

		$response = apiCall('removeVoucher', '', '');

		//p($response);

		// echo $response;

		echo json_encode($response);
	}



	public function getBookingDetails()

	{

		$address = $this->session->userdata('address');

		$data = [

			'booking_id' => $this->input->post('booking_id'),

			'lat' => @$address['lat'],

			'lng' => @$address['lng'],

		];

		$response = apiCall('GetBookingDetails', $data);



		$response = $this->load->view('order/booking_table', ['bookingData' => $response['details']], TRUE);

		echo $response;
	}





	public function checkcart_error()

	{

		$address = $this->session->userdata('address');

		$merchantinfo = $this->session->userdata('merchantInfo');



		if ((!isset($address['lat']) || $address['street'] == '') && isset($_POST['transaction_type']) && $_POST['transaction_type'] != "pickup") {

			// 			$this->session->set_flashdata('error', "Please select delivery address!");

			// 			redirect('menu');

			echo json_encode(['code' => 2, 'msg' => 'Please enter your delivery address!']);
		} else if (isset($_POST['us_distance']) && $_POST['us_distance'] > $_POST['del_distance'] && isset($_POST['transaction_type']) && $_POST['transaction_type'] != "pickup") {



			echo json_encode(['code' => 4, 'msg' => 'Your distance is ' . $_POST['us_distance'] . ' KM which is out of our range that is ' . $_POST['del_distance'] . ' KM. You can choose pickup instead.']);
		} else {



			$data['lat'] = isset($address['lat']) ? @$address['lat'] : $merchantinfo['latitude'];

			$data['lng'] = isset($address['lng']) ? @$address['lng'] : $merchantinfo['lontitude'];

			$data['transaction_type'] = @$_POST['transaction_type'];

			$data['delivery_date'] = @$_POST['delivery_date'];

			$data['delivery_time'] = @$_POST['delivery_time'];

			$data['delivery_asap'] = @$_POST['delivery_asap'];

			$data['isplate'] = @$_POST['isplate'];
			$data['car_no'] = @$_POST['car_no'];





			$this->session->set_userdata('deliveryData', $data);

			$cart = apiCall('loadCart', $data, '');

			$this->session->set_userdata('transaction_type', $data['transaction_type']);
			
			$this->session->set_userdata('isplate', $data['isplate']);
			$this->session->set_userdata('car_no', $data['car_no']);
			

			// $cart=@json_decode($cart,true);





			if (isset($cart['code']) && $cart['code'] == 1 && !empty($cart['details']['cart_error'][0])) {

				echo json_encode(['code' => 3, 'msg' => $cart['details']['cart_error'][0]]);
			} else if ($_SESSION['transaction_type'] == null) {

				echo json_encode(['code' => 5, 'msg' => 'Please select Order type (Delivery/Pickup)']);
			} else {

				echo json_encode(['code' => 1, 'msg' => '']);
			}
		}
	}
}
