<?php 
require 'db.php';
$data = json_decode(file_get_contents('php://input'), true);
 
$uid = $data['uid'];
if($uid == '' || $data['shop_id'] == '')
{
	$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went wrong  try again !");
}
else 
{
    // $shop_id = "8316293";
    // $shop_code = "Ey3a8s7U79";
    $shop_id = strip_tags(mysqli_real_escape_string($con,$data['shop_id']));
    $shop_code = strip_tags(mysqli_real_escape_string($con,$data['shop_code']));
    $u_latitude = strip_tags(mysqli_real_escape_string($con,$data['u_latitude']));
    $u_longitude = strip_tags(mysqli_real_escape_string($con,$data['u_longitude']));
    
    
    $shopp = array();
    $i=0;
    $chek_shop = $con->query("select * from shop_details where shop_code = '$shop_code'");
    while($shop = $chek_shop->fetch_assoc())
    {
        $sho = array();
        $s_latitude = $shop['latitude'];
        $s_longitude = $shop['longitude'];
        
        $address = $con->query("SELECT * from address where uid = '$uid' and status = '1'")->fetch_assoc();
        $address_count = $con->query("SELECT * from address where uid = '$uid' and status = '1'")->num_rows;
        if($address_count != 0)
    	{
    	    $shop_distance = GetDrivingDistance($u_latitude, $u_longitude, $s_latitude, $s_longitude);
            if($shop_distance['distance_value'] < 10000)
            {
                $distance = $shop_distance['distance_value'] / 1000;
                $cy = $con->query("select * from distance_db where status = 1 and shop_id = '$shop_id' and shop_code = '$shop_code' and distance > '$distance' ORDER BY distance ASC");
            	$count = $con->query("select * from distance_db where status = 1 and shop_id = '$shop_id' and shop_code = '$shop_code' and distance > '$distance' ORDER BY distance ASC")->num_rows;
            	if($count != 0)
            	{
            	    if($row = $cy->fetch_assoc())
                	{
            	        $distance_val = $row['dcharge'];
                	}
                	else
                	{
                	    $distance_val = 30.0;
                	}
                }
                
                if($distance >= 1 && $distance < 3.6)
                {
                    $new_dis = $distance + $distance * 20 / 100;
                }
                else if($distance >= 3.6 && $distance < 6)
                {
                    $new_dis = $distance + $distance * 15 / 100;
                }
                else if($distance >= 6 && $distance < 7)
                {
                    $new_dis = $distance + $distance * 12 / 100;
                }
                else if($distance >= 7 && $distance < 8.8)
                {
                    $new_dis = $distance + $distance * 9.8 / 100;
                }
                else if($distance >= 8.8 && $distance < 10)
                {
                    $new_dis = $distance + $distance * 8 / 100;
                }
                else
                {
                    $new_dis = $distance;
                }
                
                $new_distance = number_format($new_dis, 2);
                
                $sho['delivery_charge'] = $distance_val;
                $sho['latitude'] = $shop['latitude'];
                $sho['longitude'] =  $shop['longitude'];
                $sho['distance'] = $new_distance;
                $sho['address1'] = $shop['address1'];
                $sho['address2'] = $shop['address2'];
                $sho['area'] = $shop['area'];
                $sho['city'] = $shop['city'];
                $sho['pincode'] = $shop['pincode'];
                $sho['shop_name'] = $shop['shop_name'];
                $sho['owner'] = $shop['owner'];
                $sho['owner_mobile'] = $shop['owner_mobile'];
                $sho['manager'] = $shop['manager'];
                $sho['manager_mobile'] = $shop['manager_mobile'];
                $sho['doc_no'] = $shop['doc_no'];
                $sho['shop_id'] = $shop['shop_id'];
                $sho['shop_code'] = $shop['shop_code'];
                $shopp[] = $sho;
            }
    	}
    }
    
    $chek = $con->query("select * from user where id = '$uid' and status = '1' and shop_code = '$shop_code'");

    if($chek->num_rows != 0)
    {
        $v = array();
    	$cp = array(); 
    	$d = array();
    	$p = array();
    	$sec = array();
    	
        $sel = $con->query("select * from banner where shop_code = '$shop_code'");
        while($row = $sel->fetch_assoc())
        {
            $v[] = $row;
        }
        
        $current_time = date("H:i");
        
        $sels = $con->query("SELECT category.*, shop_settings.start_time, shop_settings.end_time 
        FROM category 
        INNER JOIN shop_settings on 
        category.cattime != '' and category.shop_id = shop_settings.shop_id
        where category.catstatus='1' and category.shop_id = '$shop_id' and category.shop_code = '$shop_code' and
        TIME_TO_SEC(IF (category.cattime = 'Default', shop_settings.start_time, category.catstarttime)) < TIME_TO_SEC('$current_time')
        and TIME_TO_SEC(IF (category.cattime = 'Default', shop_settings.end_time, category.catstoptime)) > TIME_TO_SEC('$current_time') 
        or category.catstatus='1' and category.shop_id = '$shop_id' and category.shop_code = '$shop_code' and
        TIME_TO_SEC(IF (category.cattime = 'Customise',category.catstarttime, shop_settings.start_time)) < TIME_TO_SEC('$current_time') 
        and TIME_TO_SEC(IF (category.cattime = 'Customise',category.catstoptime, shop_settings.end_time)) > TIME_TO_SEC('$current_time') limit 8");
        
        while($rows = $sels->fetch_assoc())
        {
            $p['id'] = $rows['id'];
    		$p['catname'] = $rows['catname'];
    		$p['catimg'] = $rows['catimg'];
    		$sid = $rows['id'];
    		$p['count'] = $con->query("select * from subcategory where cat_id='$sid' and shop_id = '$shop_id' and shop_code = '$shop_code'")->num_rows;
    		$cp[] = $p;
        }
    
        include 'product_with_dis_home.php';
    
    	$curr = $con->query("SELECT
            shop_details.manager_mobile,
            shop_details.latitude,
            shop_details.longitude,
            shop_details.doc_no,
            shop_settings.*
            FROM shop_settings
            
            INNER JOIN shop_details ON
            shop_settings.shop_id = shop_details.shop_id
            
            WHERE shop_settings.shop_id = '$shop_id' and shop_settings.shop_code = '$shop_code'")->fetch_assoc();
            
            
        $cy = $con->query("select * from coupon_code where status='1' and admin_status='1' and shop_id = '$shop_id' and shop_code = '$shop_code' order by priority ASC");
    	$coupon_count = $con->query("select * from coupon_code where status='1' and admin_status='1' and shop_id = '$shop_id' and shop_code = '$shop_code' order by priority ASC")->num_rows;
    	if($coupon_count != 0)
    	{
        	$cc = array();
        	$q = array();
    	    while($row = $cy->fetch_assoc())
        	{
        	    $code = $row['code'];
        	    $count = $con->query("select * from orders where uid='$uid' and coupon_code='$code' and status <> 'cancelled'")->num_rows;
        	    $use_limit = intval($row['max_use_limit']);
        	    if($use_limit != 0)
        	    {
            	    if($count < $use_limit)
            	    {
                		$cc['id'] = $row['id'];
                		$cc['name'] = $row['name'];
                		$cc['image'] = $row['image'];
                		$cc['code'] = $row['code'];
                		$cc['discount'] = $row['discount'];
                		$cc['description'] = $row['description'];
                		$cc['max_order'] = $row['max_order_amount'];
                		$cc['max_discount'] = $row['max_discount_amount'];
                		$cc['status'] = $row['status'];
                		$q[] = $cc;
            	    }
        	        
        	    }
        	    else
        	    {
        	        $cc['id'] = $row['id'];
            		$cc['name'] = $row['name'];
            		$cc['image'] = $row['image'];
            		$cc['code'] = $row['code'];
            		$cc['discount'] = $row['discount'];
            		$cc['description'] = $row['description'];
            		$cc['max_order'] = $row['max_order_amount'];
            		$cc['max_discount'] = $row['max_discount_amount'];
            		$cc['status'] = $row['status'];
            		$q[] = $cc;
        	    }
        	}
    	}
    	else{
    	    $q = [];
    	}
    	
    	$paym = $con->query("SELECT * from payment_type where status='1' and shop_id = '$shop_id' and shop_code = '$shop_code'");
        $pay_count = $con->query("SELECT * from payment_type where status='1' and shop_id = '$shop_id' and shop_code = '$shop_code'")->num_rows;
        if($pay_count != 0)
    	{
    	    while($spaym = $paym->fetch_assoc())
            {
                $pp['id'] = $spaym['id'];
        		$pp['title'] = $spaym['name'];
        		$pp['img'] = $spaym['img'];
        		$pp['sub_title'] = $spaym['sub_name'];
        		$pay[] = $pp;
            }
    	}
    	else
    	{
    	    $pay = [];
    	}
    	
    	$order = $con->query("SELECT * from orders where uid = '$uid' and status <> 'completed' and status <> 'cancelled' limit 1")->fetch_assoc();
        $order_count = $con->query("SELECT * from orders where uid = '$uid' and status <> 'completed' and status <> 'cancelled' limit 1")->num_rows;
        if($order_count != 0)
    	{
    	    $order_id = $order['order_id'];
    	}
    	else
    	{
    	    $order_id = 0;
    	}
    	
    	$is_raining = 0;
    	$is_govt = 0;
        
    	$kp = array("payment"=>$pay,"shops"=>$shopp,"coupon_data"=>$q,"Main_Data"=>$curr,'Banner'=>$v,'Catlist'=>$cp,'Productlist'=>$d,"dynamic_section"=>$sec,"order_id"=>$order_id,"rain"=>$is_raining,"govt"=>$is_govt);
    	
    	$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Data Get Successfully!","ResultData"=>$kp);

    }
    else  
    {
        $returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Your Account Deactivated!");
    }
    
}
echo json_encode($returnArr);

function GetDrivingDistance($lat1, $long1, $lat2, $long2)
{
    $url = "https://maps.googleapis.com/maps/api/directions/json?origin=".$lat1.",".$long1."&destination=".$lat2.",".$long2."&sensor=false&mode=driving&alternatives=true&key=AIzaSyC38nyMdGmo-rtoKrGIQ7AYNGfV7--uUHY";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    $response = curl_exec($ch);
    curl_close($ch);
    $response_a = json_decode($response, true);
    $dist = $response_a['routes'][0]['legs'][0]['distance']['text'];
    $dist_value = $response_a['routes'][0]['legs'][0]['distance']['value'];
    $time = $response_a['routes'][0]['legs'][0]['duration']['text'];
    $time_value = $response_a['routes'][0]['legs'][0]['duration']['value'];
    // return $dist_value;
    return array('distance' => $dist, 'distance_value' => $dist_value);
}