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

class Menu extends CI_Controller
{

	public function index()
	{
	   
	$settings = $this->session->userdata('settings');
		$reviewList = apiCall('ReviewList');
    // 	p($reviewList);
	//	if(empty($settings)){
			$settings = apiCall('getSettings');
			
			$settings=$settings['details']['settings'];
			
			$this->session->set_userdata('settings',$settings);
		
   //	}
		$menu = apiCall('getMerchantMenu');
		
		$resturantInfo = apicall('getRestaurantInfo');
	    //p($menu);
	
		$merchantInfo = apiCall('GetMerchantAbout');
	
		$this->session->set_userdata('merchantInfo', $merchantInfo['details']['data']);
		$data = [];
		$address = $this->session->userdata('address');
	

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

			$data['lat'] = isset($address['lat'])?@$address['lat']:$merchantlatlngInfo['latitude'];
			$data['lng'] = isset($address['lng'])?@$address['lng']:$merchantlatlngInfo['lontitude'];
		
		
		$deliveryDateList = apiCall('deliveryDateList');
		$deliveryTimeList = apiCall('deliveryTimeList');
		$merchantDateList = apiCall('GetMerchantDateList');
	
		$cart = apiCall('loadCart', $data);
	
		$cart_count = 0;	
		
		
		if (isset($_SESSION['cart'])) {
		    $cart = $_SESSION['cart'];
		    
		    if (isset($cart['data'])) {
		        $cartData = $cart['data'];
		        
		        $items = [];
		        if (isset($cartData['item']) && is_array($cartData['item'])) {
		            $items = $cartData['item'];
		        }
		        
		        foreach ($items as $val) {		   	 
    		   	    $cart_count+= $val['qty'];
    		    }
		        
		    }
		}
		
		//print_r($cart['details']['promo_items_pro']);
		//print_r($cart['details']['promo_items']);
		
		
		
		
	
		$cartDetails = [];
        if (isset($cart) && !empty($cart)) {
            $cartDetails = $cart['details'] ?? [];
        }

		$this->session->set_userdata('cart', $cartDetails);
		
		
		$resturantInfoDetails = [];
        if (isset($resturantInfo) && !empty($resturantInfo)) {
            $resturantInfoDetails = $resturantInfo['details'] ?? [];
        }
		$this->session->set_userdata('resturantInfo',$resturantInfoDetails);
		
// 		$this->session->set_userdata('resturantInfo',$resturantInfo['details']);
		
//		$merchantTimeList = apiCall('GetMerchantTimeList');

        $merchantDateListDetails =[];
        if (isset($bookingtabledateList) && !empty($bookingtabledateList)) {
            $merchantDateListDetails = $bookingtabledateList['details']['data'] ?? [];
        }
        $this->session->set_userdata('bookingtabledateList',$merchantDateListDetails);
        
        // $this->session->set_userdata('bookingtabledateList',$merchantDateList['details']['data']);
        
        
       // $this->session->set_userdata('bookingtabletimeList',$merchantTimeList['details']['data']);
		$this->session->set_userdata('dateList',$deliveryDateList['details']['data']);
		$this->session->set_userdata('timeList',$deliveryTimeList['details']['data']);
	   $OrderList = apiCall('OrderList');
		renderView($this, 'menu/index', [
			'merchantInfo'=>$merchantInfo['details']['data'],
			'reviewInfo' =>$reviewList['details'],
			'data' => $menu['details'],
			'settings'=>$settings,
			'cart' => $cartDetails,
			'promos' =>$cartDetails['promo_items'] ?? '',
			'OrderList' => $OrderList['details']['data'] ?? [],
			'cart_count'=>$cart_count
		]);
	}   

	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,'');
	//print_r($cart);
	
	//echo $cart['details']['car_parking_enable'];
		$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('menu/cart', ['cart' => $cartDetails,'dateList'=>$dateList]);
	}

	public function load_mobilecart()
	{
		$data = [];
		$address = $this->session->userdata('address');
		
		if ($address) {
			$data['lat'] = $address['lat'];
			$data['lng'] = $address['lng'];
		}
		
		$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);
        
		$dateList=$this->session->userdata('dateList');
	
		$this->load->view('menu/mobilecart', ['cart' => $cartDetails,'dateList'=>$dateList]);

	}

	public function setAddress()
	{
		$post = $this->input->post();
		
		$this->session->set_userdata('address', $post);
		$merchantInfo = $this->session->userdata('merchantInfo');
		$user = $this->session->userdata('user');
		$post['merchant_id'] = $merchantInfo['merchant_id'];
		$post['contact_phone'] = @$user['contact_phone'];
		$post['location_name'] = @$post['address'];

		jsonResponse(apiCall('setDeliveryAddress', $post));
	}

	public function addtocart()
	{
       // p($_POST);
        // $getloc = json_decode(file_get_contents("http://ipinfo.io/"));
        // $coordinates = explode(",", $getloc->loc);
		$address = $this->session->userdata('address');
	    $merchantinfo = $this->session->userdata('merchantInfo');
	
		$prr=explode("|",$_POST['price']);
		 $pricess=$prr[0];
		
		if($pricess>0){$_POST['promo_id']=0;}else{}
	
		$data = [
            'row' => @$_POST['row'],  
			'category_id' => @$_POST['category_id'],
			'item_id' => $_POST['item_id'],
			'with_size' => @$_POST['with_size'],
			'size_id'=> @$_POST['size_id'],
            'size_name_trans' => @$_POST['size_name_trans'],
            'size_words' => @$_POST['size_words'],
			'price' => $_POST['price'],
			'qty' => $_POST['qty'],
			'promo_id' => @$_POST['promo_id'],
			'notes' => @$_POST['notes'],
			'cooking_ref' => @$_POST['cooking_ref'],
			'sub_item' => @$_POST['sub_item'],
			'lat' => isset($address['lat'])?@$address['lat']:$merchantinfo['latitude'],
			'lng' => isset($address['lng'])?@$address['lng']:$merchantinfo['lontitude'],
		];
		


		$cart_count = 0;
		$item_total = 0;
		
		if (isset($_SESSION['cart'])) {
		    $cart = $_SESSION['cart'];
		    
		    if (isset($cart['data'])) {
		        $cartData = $cart['data'];
		        
		        $items = [];
		        if (isset($cartData['item']) && is_array($cartData['item'])) {
		            $items = $cartData['item'];
		        }
		        
		        foreach ($items as $val) {		   	 
    		   	    $cart_count+= $val['qty'];
    		    }
    		    // $item_total = $data['total']['total'];
		        $item_total = $cartData['total']['subtotal'];
		        
		    }
		}
		
		   $data['item_count'] = $cart_count + $data['qty'];
		   $price = $pricess * $data['qty'] ;
		  // $item_total_price = $_SESSION['cart']['data']['total']['total'] + $price;
		   $data['item_price_total'] = $item_total + $price ;
		jsonResponse(apiCall('addToCart','', $data));
		
	}
	
	
	
	public function addtocart_promo()
	{
       // p($_POST);
        // $getloc = json_decode(file_get_contents("http://ipinfo.io/"));
        // $coordinates = explode(",", $getloc->loc);
		$address = $this->session->userdata('address');
	    $merchantinfo = $this->session->userdata('merchantInfo');
	
		$data = [
            'row' => @$_POST['row'],
			'category_id' => @$_POST['category_id'],
			'item_id' => $_POST['item_id'],
			'with_size' => @$_POST['with_size'],
			'size_id'=> @$_POST['size_id'],
            'size_name_trans' => @$_POST['size_name_trans'],
            'size_words' => @$_POST['size_words'],
			'price' => $_POST['price'],
			'qty' => $_POST['qty'],
			'promo_id' => $_POST['promo_id'],
			'notes' => @$_POST['notes'],
			'cooking_ref' => @$_POST['cooking_ref'],
			'sub_item' => @$_POST['sub_item'],
			'lat' => isset($address['lat'])?@$address['lat']:$merchantinfo['latitude'],
			'lng' => isset($address['lng'])?@$address['lng']:$merchantinfo['lontitude'],
		];
		


		$cart_count = 0;
		$item_total = 0;
	
	   if(is_array($_SESSION['cart']['data']['item']) && count( (array) $_SESSION['cart']['data']['item'])>=1){
		    foreach ($_SESSION['cart']['data']['item'] as $val) {		   	 
		   	 $cart_count+= $val['qty'];
		   }
		  // $item_total = $_SESSION['cart']['data']['total']['total'];
		   $item_total = $_SESSION['cart']['data']['total']['subtotal'];
		    }
		
		   $data['item_count'] = $cart_count + $data['qty'];
		   $price = $data['price'] * $data['qty'] ;
		  // $item_total_price = $_SESSION['cart']['data']['total']['total'] + $price;
		   $data['item_price_total'] = $item_total + $price ;
		   
		  
		jsonResponse(apiCall('addToCart','', $data));
		
	}
	


	public function delete_item()
	{
		$address = $this->session->userdata('address');
		$data = [
			'row' => $this->input->post('row'),
			'lat' => @$address['lat'],
			'lng' => @$address['lng'],
		];
		jsonResponse(apiCall('removeCartItem', $data));
	}

	public function get_item()
	{
	    //p($_POST);
		$address = $this->session->userdata('address');
		
		$data = [
			'cat_id' => $this->input->post('cat_id'),
			'item_id' => $this->input->post('id'),
			'row' => @$this->input->post('row'),
			'lat' => @$address['lat'],
			'lng' => @$address['lng'],
		];
		$itemmenu = apiCall('itemDetails', $data, []);
// 		p($itemmenu);

		if ($itemmenu['code'] == 1) {
			$html=$this->load->view('menu/item', ['item' => $itemmenu['details']],true);
			jsonResponse(['code'=>1,'html'=>$html,'itemmenu'=>$itemmenu]);
		}else{
			jsonResponse($itemmenu);
		}
	}
	
	public function get_item_promotion()
	{
	    //p($_POST);
		$address = $this->session->userdata('address');
		
		$data = [
			'cat_id' => $this->input->post('cat_id'),
			'item_id' => $this->input->post('id'),
			'row' => @$this->input->post('row'),
			'promo_id' => @$this->input->post('promo_id'),
			'lat' => @$address['lat'],
			'lng' => @$address['lng'],
		];
		$itemmenu = apiCall('itemDetails', $data, []);
// 		p($itemmenu);

		if ($itemmenu['code'] == 1) {
			$html=$this->load->view('menu/item_promotion', ['item' => $itemmenu['details']],true);
			jsonResponse(['code'=>1,'html'=>$html,'itemmenu'=>$itemmenu]);
		}else{
			jsonResponse($itemmenu);
		}
	}

	public function timelist()
	{
	    //p(date("Y-m-d"));

	    //echo "timelist";die();
		$data = [
			'delivery_date' => $_POST['date']
		];
		
	
		$data['transaction_type'] = $this->session->userdata('transaction_type');
		
		if(isset($data['transaction_type']) && !empty($data['transaction_type'])){}else{
			$data['transaction_type']=$_POST['dell'];
		}
		
		$deliverytimelist = apiCall('deliveryTimeList_withtimes', $data, '');
		$html = "";
		if ($deliverytimelist['code'] == 1) {
			foreach ($deliverytimelist['details']['data'] as $key => $time) {
				$html .= "<option value='$key'>$time</option>";
			}
		} else {
			$html = "<option value=''></option>";
		}
		echo $html;
	}

	public function bookingtimelist()
    {
        $data = [
            'date' => $_POST['date']
        ];
        $bookingtimelist = apiCall('GetMerchantTimeList', $data, '');
        $html = "";
        if ($bookingtimelist['code'] == 1) {
            foreach ($bookingtimelist['details']['data'] as $key => $time) {
                $html .= "<option value='$key'>$time</option>";
            }
        } else {
            $html = "<option value=''></option>";
        }
        echo $html;
    }

    public function addReviews()
    {
        $address = $this->session->userdata('address');
        $data = [
            
            'order_id' => @$_POST['order_id'],
            'review' => $_POST['review_content'],
            'rating' => @$_POST['rating'],
            'lat' => $address['lat'],
            'lng' => $address['lng'],
            'user_token' => $this->session->userdata('token'),
        ];
       
      
        jsonResponse(apiCall('addReview', '', $data));
    }



	public function clearCart()
	{
        jsonResponse(apiCall('clearCart'));

	}

	public function bookATable()
    {
        $address = $this->session->userdata('address');
        $this->form_validation->set_rules('number_guest', 'Guest', 'required');
        $this->form_validation->set_rules('date_booking', 'Date', 'required');
        $this->form_validation->set_rules('booking_time', 'Time', 'required');
        $this->form_validation->set_rules('booking_name', 'Name', 'required');
        $this->form_validation->set_rules('email', 'Email', 'required');
        $this->form_validation->set_rules('mobile', 'Mobile No', 'required');
        if ($this->form_validation->run() == TRUE) {
            $data = [
                'book_merchant_id' => merchant_id,
                'number_guest' => $_POST['number_guest'],
                'date_booking' => $_POST['date_booking'],
                'booking_time' => @$_POST['booking_time'],
                'booking_name' => $_POST['booking_name'],
                'email' => $_POST['email'],
                'mobile' => @$_POST['mobile'],
                'booking_notes' => @$_POST['booking_notes'],
                'lat' => $address['lat'],
                'lng' => $address['lng'],
                'user_token' => @$this->session->userdata('token'),
            ];
            $response= apiCall('SaveBooking', '', $data);
           if($response['code'] == 1)
           {
               $this->session->set_flashdata('success',$response['msg']);
           }else{
               $this->session->set_flashdata('error',$response['msg']);
           }
        }else{
            $this->session->set_flashdata('error','All Fields are required');
        }
        redirect('menu');
    }
    
    public function save_transactionType()
    {
         $this->session->set_userdata('transaction_type', $_POST['transaction_type']);
    }

}
