<?php

include("config.php");



$table_name_style="Style";
$table_name_type_style="TypeStyle";
$table_name_tag_style="TagStyle";
$table_name_orientation_style="OrientationStyle";
$table_name_action_style="ActionStyle";
$table_name_setting_style="SettingStyle";
$table_name_banner_style="BannerStyle";
$table_name_city="City";
$table_name_configuration="Configuration";


$table_name_categories="Categories";
$table_name_sub_categories="SubCategories";
$table_name_child_sub_categories="ChildSubCategories";
$table_name_brand="Brand";
$table_name_product="Product";
$table_name_product_image ="ProductPicture";

$table_name_product_rating_picture ="ReviewPicture";
$table_name_rating="Rating";

$table_name_product_attribute="ProductAttribute";
$table_name_attribute_item="AttributeItem";

$table_name_product_question="ProductQuestion";
$table_name_question_answer="QuestionAnswer";

$table_name_user="User";
$table_name_user_meta="UserMeta";

$table_name_cart="Cart";
$table_name_cart_meta="CartMeta";

$table_name_payment_method="PaymentMethod";
$table_name_sale="Sale";
$table_name_sale_meta="SaleMeta";

$table_name_featured_categories="HomeFeaturedCategories";

$table_name_featured_banner="FeaturedBanner";
$table_name_featured_banner_meta="FeaturedBannerMeta";

$table_name_coupon="Coupon";
$table_name_coupon_meta="CouponMeta";

$table_name_search="Search";
$table_name_favourites="Favourite";
$table_name_tags="Tags";
$table_name_following="Following";

$table_name_shipping="Shipping";
$table_name_customized_shipping="CustomizedShipping";
$table_name_product_shipping="ProductShipping";

$table_name_shipping_packages="ShippingPackages";

$table_name_list_of_orders="ListOfOrders";
$table_name_order_meta="OrderMeta";

$table_name_user_payment_method="UserPaymentMethod";

$table_name_refund="Refund";
$table_name_refund_meta="RefundMeta";

$table_name_dispute="Dispute";
$table_name_contact_us="ContactUs";

$table_name_privacy_policy="PrivacyPolicy";
$table_name_about_us="AboutUs";


$_POST = json_decode(file_get_contents('php://input'), true);

if (isset($_POST["functionality"])) {
$object=$_POST["functionality"];
}


/*if (isset($_SERVER['HTTP_AUTHORIZED_API_KEY'])){
	$apiKey=$_SERVER['HTTP_AUTHORIZED_API_KEY'];


	if(!checkApiKeyVerification( validate($apiKey) ) ){
		$object="failed";	



	}	

  }else{
  	$object="failed";
    
  }
*/


if (isset($_POST["language_id"])) {
   $language_id=$_POST["language_id"];
}

if (isset($_POST["city_id"])) {
   $city_id=$_POST["city_id"];
}

if (isset($_POST["category_id"])) {
   $category_id=$_POST["category_id"];
}

if (isset($_POST["skip_ids"])) {
   $skip_ids=$_POST["skip_ids"];
}

if (isset($_POST["product_id"])) {
   $product_id=$_POST["product_id"];
}

if (isset($_POST["question_id"])) {
   $question_id=$_POST["question_id"];
}

if (isset($_POST["category_type"])) {
   $category_type=$_POST["category_type"];
}


if (isset($_POST["attributes"])) {
   $attributes=$_POST["attributes"];
}


if (isset($_POST["quantity"])) {
   $quantity=$_POST["quantity"];
}


if (isset($_POST["shipping_id"])) {
   $shipping_id=$_POST["shipping_id"];
}


if (isset($_POST["user_id"])) {
   $user_id=$_POST["user_id"];
}


if (isset($_POST["rate_id"])) {
   $rate_id=$_POST["rate_id"];
}


if (isset($_POST["carrier"])) {
   $carrier=$_POST["carrier"];
}


if (isset($_POST["service"])) {
   $service=$_POST["service"];
}

if (isset($_POST["rate"])) {
   $rate=$_POST["rate"];
}

if (isset($_POST["delivery_days"])) {
   $delivery_days=$_POST["delivery_days"];
}

if (isset($_POST["currency"])) {
   $currency=$_POST["currency"];
}

if (isset($_POST["to_postal_code"])) {
   $to_postal_code=$_POST["to_postal_code"];
}

if (isset($_POST["brand_id"])) {
   $brand_id=$_POST["brand_id"];
}

if (isset($_POST["type"])) {
   $type=$_POST["type"];
}

if (isset($_POST["categories_id"])) {
   $categories_id=$_POST["categories_id"];
}

if (isset($_POST["banner_id"])) {
   $banner_id=$_POST["banner_id"];
}

if (isset($_POST["search"])) {
   $search=$_POST["search"];
}


if (isset($_POST["id"])) {
   $id=$_POST["id"];
}


if (isset($_POST["action"])) {
   $action=$_POST["action"];
}


if (isset($_POST["address"])) {
   $address=$_POST["address"];
}

if (isset($_POST["apartment"])) {
   $apartment=$_POST["apartment"];
}

if (isset($_POST["postal_code"])) {
   $postal_code=$_POST["postal_code"];
}

if (isset($_POST["country"])) {
   $country=$_POST["country"];
}

if (isset($_POST["phone"])) {
   $phone=$_POST["phone"];
}

if (isset($_POST["city"])) {
   $city=$_POST["city"];
}

if (isset($_POST["note"])) {
   $note=$_POST["note"];
}


if (isset($_POST["address_id"])) {
   $address_id=$_POST["address_id"];
}


if (isset($_POST["cart_id"])) {
   $cart_id=$_POST["cart_id"];
}


if (isset($_POST["coupon_code"])) {
   $coupon_code=$_POST["coupon_code"];
}


if (isset($_POST["weight"])) {
   $weight=$_POST["weight"];
}

if (isset($_POST["courier_id"])) {
   $courier_id=$_POST["courier_id"];
}

if (isset($_POST["question"])) {
   $question=escape_string($_POST["question"]);
}

if (isset($_POST["answer"])) {
   $answer=escape_string($_POST["answer"]);
}

if (isset($_POST["total_amount"])) {
   $total_amount=$_POST["total_amount"];
}

if (isset($_POST["shipping_fee"])) {
   $shipping_fee=$_POST["shipping_fee"];
}

if (isset($_POST["currency_symbol"])) {
   $currency_symbol=$_POST["currency_symbol"];
}

if (isset($_POST["currency_code"])) {
   $currency_code=$_POST["currency_code"];
}

if (isset($_POST["order_detail"])) {
   $order_detail=$_POST["order_detail"];
}

if (isset($_POST["discounted_amount"])) {
   $discounted_amount=$_POST["discounted_amount"];
}

if (isset($_POST["type"])) {
   $type=$_POST["type"];
}

if (isset($_POST["picture"])) {
   $picture=$_POST["picture"];
}

if (isset($_POST["rating"])) {
   $rating=$_POST["rating"];
}

if (isset($_POST["order_id"])) {
    $order_id=$_POST["order_id"];
}

if (isset($_POST["review"])) {
    $review=escape_string($_POST["review"]);
}

if (isset($_POST["card_no"])) {
    $card_no=$_POST["card_no"];
}

if (isset($_POST["stripe_token"])) {
    $stripe_token=$_POST["stripe_token"];
}

if (isset($_POST["save_card"])) {
    $save_card=$_POST["save_card"];
}

if (isset($_POST["token"])) {
    $token=$_POST["token"];
}

if (isset($_POST["card_company_name"])) {
    $card_company_name=$_POST["card_company_name"];
}


if (isset($_POST["review_id"])) {
    $review_id=$_POST["review_id"];
}

if (isset($_POST["subject"])) {
    $subject=$_POST["subject"];
}

if (isset($_POST["detail"])) {
    $detail=$_POST["detail"];
}


if (isset($_POST["detail"])) {
    $detail=$_POST["detail"];
}


if (isset($_POST["user_phone_email"])) {
    $user_phone_email=$_POST["user_phone_email"];
}

if (isset($_POST["password"])) {
    if ($_POST["password"]!="null") {
      $password=md5($_POST["password"]);
    }
    else{
      $password=$_POST["password"];
    }
    
}

if (isset($_POST["login_type"])) {
    $login_type=$_POST["login_type"];
}


if (isset($_POST["first_name"])) {
    $first_name=$_POST["first_name"];
}

if (isset($_POST["last_name"])) {
    $last_name=$_POST["last_name"];
}

if (isset($_POST["email_address"])) {
    $email_address=$_POST["email_address"];
}

if (isset($_POST["phone"])) {
    $phone=$_POST["phone"];
}


if (isset($_POST["feature_type"])) {
    $feature_type=$_POST["feature_type"];
}


if (isset($_POST["price"])) {
    $price=$_POST["price"];
}

if (isset($_POST["sub_ctg_id"])) {
    $sub_ctg_id=$_POST["sub_ctg_id"];
}

if (isset($_POST["sorting_type"])) {
    $sorting_type=$_POST["sorting_type"];
}






/*

It is used for formatting of json response

*/
class Data 
{

  public $code="";
  public $message="";
  public $list_of_data=[];
  
  


} 





/*

It is used for formatting of json response

*/
class UserFavouritesFollowing 
{

  public $id="";
  public $key="";
  public $value="";
  
  


} 



/*

It is used for formatting of json response

*/
class HistoryData 
{



  public $id="";
  public $order_no="";

  public $customer_name="";
  public $customer_address="";
  public $customer_apartment="";
  public $customer_city="";

  public $total_bill="";
  public $discount_bill="";
  public $shipping_fee=""; 

  public $currency_code="";
  public $currency_symbol="";

  public $courier_logo="";
  public $courier_name="";
  public $courier_service="";
  public $courier_delivery_day="";

  public $list_of_product=[];
  
  


} 



/*

It is used for formatting of Trending Data into Object

*/
class PrivacyPolicy 
{

  public $code="";
  public $message="";
  public $privacy="";

}    



if ($object=="retrieve_cities") {

  # For retrieving popular videos
  retrieve_cities();

}
else if ($object=="retrieve_categories") {

  # For retrieving popular videos
  retrieve_categories();

}
else if ($object=="retrieve_sub_categories") {

  # For retrieving popular videos
  retrieve_sub_categories($category_id);

}
else if ($object=="retrieve_categorized_product") {

  # For retrieving popular videos
  retrieve_categorized_product($category_id,$sub_ctg_id,$category_type,$feature_type,$skip_ids);

}
else if ($object=="retrieve_specific_product") {

  # For retrieving popular videos
  retrieve_specific_product($product_id);

}
else if ($object=="retrieve_questions") {

  # For retrieving popular videos
  retrieve_questions($product_id);

}
else if ($object=="retrieve_answer") {

  # For retrieving popular videos
  retrieve_answer($question_id);

}
else if ($object=="retrieve_specific_product_rating") {

  # For retrieving popular videos
  retrieve_specific_product_rating($product_id);

}
else if ($object=="retrieve_related_product") {

  # For retrieving popular videos
  retrieve_related_product($product_id);

}
else if ($object=="add_product_into_cart") {

  # For retrieving popular videos
  add_product_into_cart($product_id,$user_id,$brand_id,$price,$attributes,$quantity,$courier_id);

}
else if ($object=="retrieve_cart_product") {

  # For retrieving popular videos
  retrieve_cart_product($user_id);

}
else if ($object=="delete_product_from_cart") {

  # For retrieving popular videos
  delete_product_from_cart($cart_id);

}
else if ($object=="retrieve_product_in_billing") {

  # For retrieving popular videos
  retrieve_product_in_billing($user_id);

}
else if ($object=="retrieve_specific_product_shipping_rates") {

  # For retrieving popular videos
  retrieve_specific_product_shipping_rates($address_id,$product_id,$quantity,$cart_id,$courier_id);

}
else if ($object=="retrieve_specific_store_detail") {

  # For retrieving popular videos
  retrieve_specific_store_detail($brand_id);

}
else if ($object=="retrieve_store_product") {

  # For retrieving popular videos
  retrieve_store_product($brand_id,$category_id,$category_type,$sorting_type,$skip_ids);

}
else if ($object=="retrieve_featured_categories") {

  # For retrieving popular videos
  retrieve_featured_categories();

}
else if ($object=="retrieve_home_categorized_products") {

  # For retrieving popular videos
  retrieve_home_categorized_products($categories_id);

}
else if ($object=="retrieve_hot_data") {

  # For retrieving popular videos   
  retrieve_hot_data();

}
else if ($object=="retrieve_sale_data") {

  # For retrieving popular videos 
  retrieve_sale_data();

}
else if ($object=="retrieve_coupon_data") {

  # For retrieving popular videos 
  retrieve_coupon_data($type);

}
else if ($object=="retrieve_all_brand") {

  # For retrieving popular videos 
  retrieve_all_brand($skip_ids);

}
else if ($object=="retrieve_featured_banner_products") {

  # For retrieving popular videos 
  retrieve_featured_banner_products($banner_id,$type,$skip_ids);

}
else if ($object=="retrieve_trending_searches") {

  # For retrieving popular videos 
  retrieve_trending_searches();

}
else if ($object=="retrieve_favourites_data") {

  # For retrieving popular videos 
  retrieve_favourites_data($user_id,$type,$skip_ids);

}
else if ($object=="retrieve_searches_products") {

  # For retrieving popular videos 
  retrieve_searches_products($search);

}
else if ($object=="change_favourite_status") {

  # For retrieving popular videos 
  change_favourite_status($id,$user_id,$type,$action);

}
else if ($object=="change_follow_status") {

  # For retrieving popular videos 
  change_follow_status($id,$user_id,$type,$action);

}
else if ($object=="update_product_quantity_delete") {

  # For retrieving popular videos  
  update_product_quantity_delete($id,$quantity,$type);

}
else if ($object=="retrieve_available_addresses") {

  # For retrieving popular videos 
  retrieve_available_addresses($user_id);

}
else if ($object=="delete_specific_address") {

  # For retrieving popular videos 
  delete_specific_address($address_id);

}
else if ($object=="add_billing_address") {

  # For retrieving popular videos 
  add_billing_address($user_id,$address,$apartment,$city,$postal_code,$country,$phone,$note);

}
else if ($object=="redeem_coupon") {

  # For retrieving popular videos 
  redeem_coupon($user_id,$coupon_code);

}
else if ($object=="retrieve_customized_shipping_packages") {

  # For retrieving popular videos 
  retrieve_customized_shipping_packages($product_id,$quantity,$weight,$id);

}
else if ($object=="retrieve_available_shipping") {

  # For retrieving popular videos 
  retrieve_available_shipping($product_id);

}
else if ($object=="add_question_into_product") {

  # For retrieving popular videos 
  add_question_into_product($user_id,$product_id,$question);

}
else if ($object=="add_answer_into_question") {

  # For retrieving popular videos 
  add_answer_into_question($user_id,$question_id,$answer);

}
else if ($object=="proceed_to_checkout") {

  # For retrieving popular videos 
  proceed_to_checkout($user_id,$address_id,$total_amount,$shipping_fee,$currency_symbol,$currency_code,$discounted_amount,$token,$order_detail);

}
else if ($object=="retrieve_history") {

  # For retrieving popular videos 
  retrieve_history($user_id,$type);

}
else if ($object=="add_review") {

  # For retrieving popular videos 
  add_reviews($order_id,$user_id,$brand_id,$product_id,$rating,$review,$picture);

}
else if ($object=="retrieve_specific_order_review_rating") {

  # For retrieving popular videos 
  retrieve_specific_order_review_rating($order_id);

}
else if ($object=="save_billing_card") {

  # For retrieving popular videos 
  save_billing_card($user_id,$card_company_name,$card_no,$stripe_token,$save_card);

}
else if ($object=="retrieve_specific_user_billing_cards") {

  # For retrieving popular videos 
  retrieve_specific_user_billing_cards($user_id);

}
else if ($object=="adding_refund_specific_order") {

  # For retrieving popular videos 
  adding_refund_specific_order($user_id,$brand_id,$order_id,$review,$picture);

}
else if ($object=="retrieve_specific_order_refund_request") {

  # For retrieving popular videos 
  retrieve_specific_order_refund_request($order_id);

}
else if ($object=="retrieve_specific_user_report") {

  # For retrieving popular videos 
  retrieve_specific_user_report($user_id,$type);

}
else if ($object=="add_dispute_specific_refund_request") {

  # For retrieving popular videos 
  add_dispute_specific_refund_request($user_id,$order_id);

}
else if ($object=="retrieve_specific_user_review") {

  # For retrieving popular videos 
  retrieve_specific_user_review($user_id);

}
else if ($object=="delete_specific_review") {

  # For retrieving popular videos 
  delete_specific_review($review_id);

}
else if ($object=="add_contact_us") {

  # For retrieving popular videos 
  add_contact_us($user_id,$subject,$detail);

}
else if ($object=="retrieve_user_following") {

  # For retrieving popular videos 
  retrieve_user_following($user_id);

}
else if ($object=="login_user") {

  # For retrieving popular videos 
  login_user($user_phone_email,$password,$login_type);

}
else if ($object=="register_user") {

  register_user($first_name,$last_name,$email_address,$phone,$password);

}
else if ($object=="update_profile") {

  update_profile($user_id,$first_name,$last_name,$password,$picture);

}
else if ($object=="retrieve_profile_detail") {

  retrieve_profile_detail($user_id);

}
else if ($object=="retrieve_privacy_policy") {

  retrieve_privacy_policy();

}
else if ($object=="retrieve_about_us") {

  retrieve_about_us();

}

/*else if ($object=="send_test_request_to_places_api") {

  send_test_request_to_places_api();

}*/





/* 
     Function for retrieving data for Categories

*/

function retrieve_categories() {
  
  $list_of_data = [];
  $data = new Data();


  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_categories'];
  $query = "SELECT * FROM $table WHERE enable = '0' ORDER BY position ASC";

  //echo $query;

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 
      array_push($list_of_data, [
        'id' => $row['id'] , 
        'name' => $row['name'] ,
        'image' => $row['image'] ,
        'data' => retrieve_sub_categories($row['id']) , 
        'brand' => retrieve_categories_brand($row['id'])
    ]);

  }


   if ( count($list_of_data) > 0) {
     
      $data -> list_of_data = $list_of_data;
      $data -> code ="202";
      $data -> message ="Data Retrieve Successfully";

   }else{

      $data -> code ="206";
      $data -> message ="No data available";

   }

  
   $result = json_encode($data);
   echo "$result";

}



function retrieve_sub_categories($id) {
  
  $list_of_data = [];
  $data = new Data();


  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_sub_categories'];
  $query = "SELECT sub_ctg.* , ctg.name as category_name FROM $table as sub_ctg 
  INNER JOIN Categories as ctg ON ctg.id = sub_ctg.category_id
  WHERE sub_ctg.category_id = '$id' AND sub_ctg.enable = '0' ";

  //echo $query;

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 
      array_push($list_of_data, [
        'id' => $row['id'] , 
        'name' => $row['name'] ,
        'data' => retrieve_child_categories($row['id']) 
    ]);

  }


  /* if ( count($list_of_data) > 0) {
     
      $data -> list_of_data = $list_of_data;
      $data -> code ="202";
      $data -> message ="Data Retrieve Successfully";

   }else{

      $data -> code ="206";
      $data -> message ="No data available";

   }

  
   $result = json_encode($data);
   echo "$result";*/

   return $list_of_data;

}



function retrieve_child_categories($id) {
  
  $list_of_data = [];

  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_child_sub_categories'];
  $query = "SELECT * FROM $table 
  WHERE sub_category_id = '$id' AND enable = '0' ";

  ///echo $query;

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 
      array_push($list_of_data, [
        'id' => $row['id'] , 
        'name' => $row['name'] ,
        'image' => $row['image'] 
    ]);

  }

  return $list_of_data; 

}


function retrieve_categories_brand($id) {
  
  $list_of_data = [];
  $data = new Data();


  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_brand'];
  $query = "SELECT brand.* , total_product.product_count , total_review.review_count , total_review.avg_rating  FROM $table as brand 
  LEFT JOIN 
  (

    SELECT product.brand_id as id, count(rating.id) as review_count , AVG(rating.rating) as avg_rating FROM Product as product 
    INNER JOIN Rating as rating ON product.id = rating.product_id
    

  ) as total_review ON total_review.id = brand.id 
  LEFT JOIN 
  (

    SELECT product.brand_id as id, count(product.id) as product_count FROM Product as product 
    

  ) as total_product ON total_product.id = brand.id
  WHERE brand.category_id = '$id' AND brand.enable = '0' ";

  ///echo $query;

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 
      array_push($list_of_data, [
        'id' => $row['id'] , 
        'name' => $row['name'] ,
        'image' => $row['image'] ,
        'cover_photo' => $row['cover_photo'],
        'items' => $row['product_count'],
        'reviews' => $row['review_count'],
        'rating' => $row['avg_rating']

    ]);

  }


   return $list_of_data;

}




/* 
     Function for retrieving data for Categorized Product

*/

function retrieve_categorized_product($id,$sub_ctg_id,$type,$feature_type,$skip_ids) {
  
  $list_of_data = [];
  $data = new Data();


  /* For finding nearest places by keeping in view given radius */  

  
  if ($type == "sub_category") {

      $table = $GLOBALS['table_name_child_sub_categories'];

      if ($feature_type == "Popular") {
          
             $query = "SELECT product.*  FROM $table as child_sub_ctg 
             INNER JOIN Product as product  ON product.child_category_id = child_sub_ctg.id AND product.enable = '0' %s
             WHERE /*child_sub_ctg.id = '$id' AND*/ child_sub_ctg.sub_category_id = '$sub_ctg_id' AND child_sub_ctg.enable = '0' LIMIT 10";

        } 
        else if ($feature_type == "Most Reviews") {
          
             $query = "SELECT product.* , rating.total_review as review_count
             FROM $table as child_sub_ctg 
             INNER JOIN Product as product  ON product.child_category_id = child_sub_ctg.id AND product.enable = '0' %s
              LEFT JOIN (

                SELECT product_id ,count(*) as total_review FROM Rating  

             ) rating ON rating.product_id = product.id
             WHERE /*child_sub_ctg.id = '$id' AND */ child_sub_ctg.sub_category_id = '$sub_ctg_id' AND child_sub_ctg.enable = '0'  ORDER BY review_count DESC LIMIT 10";

        } 
        else if ($feature_type == "Newest") {
          
             $query = "SELECT product.* 
             FROM  ChildSubCategories as child_sub_ctg 
             INNER JOIN Product as product ON product.child_category_id = child_sub_ctg.id AND product.enable = '0' AND 
             date(product.date_created) = (SELECT min(date(`date_created`)) FROM Product where date(`date_created`) < date(now())) %s
             WHERE /*child_sub_ctg.id = '$id' AND*/ child_sub_ctg.sub_category_id = '$sub_ctg_id' AND child_sub_ctg.enable = '0' LIMIT 10";

        } 
        else if ($feature_type == "Low Price") {
          
             $query = "SELECT product.* FROM $table as child_sub_ctg 
             INNER JOIN Product as product  ON product.child_category_id = child_sub_ctg.id AND product.enable = '0' %s
             WHERE /*child_sub_ctg.id = '$id' AND*/ child_sub_ctg.sub_category_id = '$sub_ctg_id' AND child_sub_ctg.enable = '0' ORDER BY product.price+0 ASC LIMIT 10 ";

        } 
        else if ($feature_type == "High Price") {
          
             $query = "SELECT product.* FROM $table as child_sub_ctg 
             INNER JOIN Product as product  ON product.child_category_id = child_sub_ctg.id AND product.enable = '0' %s
             WHERE /*child_sub_ctg.id = '$id' AND*/ child_sub_ctg.sub_category_id = '$sub_ctg_id' AND child_sub_ctg.enable = '0' ORDER BY product.price+0 DESC LIMIT 10 ";

        } 
        else{

            $query = "SELECT product.*  FROM $table as child_sub_ctg 
             INNER JOIN Product as product  ON product.child_category_id = child_sub_ctg.id AND product.enable = '0' %s
             WHERE child_sub_ctg.sub_category_id = '$id' AND child_sub_ctg.enable = '0' LIMIT 10";

        }


     

  }
  else if ($type == "child_sub_category_id") {

      
      $table = $GLOBALS['table_name_child_sub_categories'];
      if ($feature_type == "Popular") {
          
             $query = "SELECT product.*  FROM $table as child_sub_ctg 
             INNER JOIN Product as product  ON product.child_category_id = child_sub_ctg.id AND product.enable = '0' %s
             WHERE child_sub_ctg.id = '$id' /*AND child_sub_ctg.sub_category_id = '$sub_ctg_id'*/ AND child_sub_ctg.enable = '0' LIMIT 10";

        } 
        else if ($feature_type == "Most Reviews") {
          
             $query = "SELECT product.* , rating.total_review as review_count
             FROM $table as child_sub_ctg 
             INNER JOIN Product as product  ON product.child_category_id = child_sub_ctg.id AND product.enable = '0' %s
              LEFT JOIN (

                SELECT product_id ,count(*) as total_review FROM Rating  

             ) rating ON rating.product_id = product.id
             WHERE child_sub_ctg.id = '$id' /*AND  child_sub_ctg.sub_category_id = '$sub_ctg_id'*/ AND child_sub_ctg.enable = '0'  ORDER BY review_count DESC LIMIT 10";

        } 
        else if ($feature_type == "Newest") {
          
             $query = "SELECT product.* 
             FROM  ChildSubCategories as child_sub_ctg 
             INNER JOIN Product as product ON product.child_category_id = child_sub_ctg.id AND product.enable = '0' AND 
             date(product.date_created) = (SELECT min(date(`date_created`)) FROM Product where date(`date_created`) < date(now())) %s
             WHERE child_sub_ctg.id = '$id' /*AND child_sub_ctg.sub_category_id = '$sub_ctg_id'*/ AND child_sub_ctg.enable = '0' LIMIT 10";

        } 
        else if ($feature_type == "Low Price") {
          
             $query = "SELECT product.* FROM $table as child_sub_ctg 
             INNER JOIN Product as product  ON product.child_category_id = child_sub_ctg.id AND product.enable = '0' %s
             WHERE child_sub_ctg.id = '$id' /*AND child_sub_ctg.sub_category_id = '$sub_ctg_id'*/ AND child_sub_ctg.enable = '0' ORDER BY product.price+0 ASC LIMIT 10 ";

        } 
        else if ($feature_type == "High Price") {
          
             $query = "SELECT product.* FROM $table as child_sub_ctg 
             INNER JOIN Product as product  ON product.child_category_id = child_sub_ctg.id AND product.enable = '0' %s
             WHERE child_sub_ctg.id = '$id' /*AND child_sub_ctg.sub_category_id = '$sub_ctg_id'*/ AND child_sub_ctg.enable = '0' ORDER BY product.price+0 DESC LIMIT 10 ";

        } 
        else{

             $table = $GLOBALS['table_name_product'];
             $query = "SELECT * FROM $table as product WHERE  product.child_category_id = '$id' AND product.enable = '0' %s LIMIT 10";

        }


     

  }


  if (is_null($skip_ids)) {
     $query = sprintf($query," ");
  }
  else {
     $query = sprintf($query," AND product.id NOT IN (".$skip_ids.") ");
  }


  ///echo $query;

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 
      array_push($list_of_data, [
        'id' => $row['id'] , 
        'images' => retrieve_product_images($row['id']) ,
        'brand' => retrieve_product_brand($row['id']) ,
        'cover_image' => $row['image'] ,
        'name' => $row['name'] ,
        'price' => $row['price'] ,
        'rating' => retrieve_product_average_rating($row['id']) ,
        'sold' => retrieve_product_sale($row['id'])
         
    ]);

  }


   if ( count($list_of_data) > 0) {
     
      $data -> list_of_data = $list_of_data;
      $data -> code ="202";
      $data -> message ="Data Retrieve Successfully";

   }else{

      $data -> code ="206";
      $data -> message ="No data available";

   }

  
   $result = json_encode($data);
   echo "$result";

}




function retrieve_product_images($id) {
  
  $list_of_data = [];

  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_product_image'];
  $query = "SELECT * FROM $table 
  WHERE product_id = '$id' AND enable = '0' ";

  ///echo $query;

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 
      array_push($list_of_data, [
        'id' => $row['id'] , 
        'image' => $row['image'] 
    ]);

  }

  return $list_of_data; 

}


function retrieve_product_brand($id) {
  
  $list_of_data = [];

  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_brand'];
  $query = "SELECT * FROM $table 
  WHERE id = '$id' AND enable = '0' ";

  ///echo $query;

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 
      array_push($list_of_data, [
        'id' => $row['id'] , 
        'name' => $row['name'] , 
        'image' => $row['image'] 
    ]);

  }

  return $list_of_data; 

}


function retrieve_product_average_rating($id) {
  
  $avg_rating;

  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_rating'];
  $query = "SELECT  AVG(rating.rating) as avg_rating 
  FROM $table as rating
  WHERE rating.product_id = '$id' AND rating.enable = '0' ";

  ///echo $query;

  $result=queryRunner($query);
  while ($row = rowRetrieverObject($result)) { 
    $avg_rating =  $row -> avg_rating;
  }

  return $avg_rating; 

}

function retrieve_specific_rating_picture($id) {
  
  $list_of_data = [];

  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_product_rating_picture'];
  $query = "SELECT review_picture.id , review_picture.image FROM $table as review_picture 
  WHERE review_picture.review_id = '$id' AND review_picture.enable = '0' ";

  ///echo $query;

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 
      array_push($list_of_data, [
        'id' => $row['id'] , 
        'image' => $row['image'] 
    ]);

  }

  return $list_of_data; 

}


function retrieve_specific_user($id) {
  
  $list_of_data = [];

  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_user'];
  $query = "SELECT * FROM $table 
  WHERE id = '$id' AND enable = '0' ";

  ///echo $query;

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 
      array_push($list_of_data, [
        'id' => $row['id'] , 
        'name' => $row['first_name']." ".$row['last_name'] , 
        'image' => $row['picture'] 
    ]);

  }

  return $list_of_data; 

}



/* 
     Function for retrieving data for Specific Product

*/

function retrieve_specific_product($id) {
  
  $list_of_data = [];
  $data = new Data();


     /* For finding nearest places by keeping in view given radius */  

  
      $table = $GLOBALS['table_name_product'];
      $query = "SELECT * FROM $table as product WHERE  product.id = '$id' AND product.enable = '0' ";


      ///echo $query;

      $result=queryRunner($query);
      while ($row = rowRetriever($result)) { 
          array_push($list_of_data, [
            'id' => $row['id'] , 
            'images' => retrieve_product_images($row['id']) ,
            'brand' => retrieve_product_brand($row['id']) ,
            'cover_image' => $row['image'] ,
            'name' => $row['name'] ,
            'description' => $row['description'] ,
            'price' => $row['price'] ,
            'processing_time' => $row['processing_time'] ,
            'avg_rating' => retrieve_product_average_rating( $row['id']  ),
            'discount' => retrieve_product_sale_type( $row['id'] ),
            'rating' => retrieve_product_rating($row['id']) ,
            'sold' => retrieve_product_sale($row['id']) ,
            'attribute' => retrieve_product_attribute($row['id']) ,
            'shipping' => retrieve_shipping_rates($row['id']),
            'faq' => retrieve_product_questions($row['id']) ,
            'related_product' => retrieve_related_product($row['id']) 

            
             
        ]);

      }


   if ( count($list_of_data) > 0) {
     
      $data -> list_of_data = $list_of_data;
      $data -> code ="202";
      $data -> message ="Data Retrieve Successfully";

   }else{

      $data -> code ="206";
      $data -> message ="No data available";

   }

  
   $result = json_encode($data);
   echo "$result";

}




function retrieve_product_rating($id) {
  
  $list_of_data = [];

  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_rating'];
  $query = "SELECT rating.id ,  AVG(rating.rating) as avg_rating , rating.rating , user.id as user_id ,concat(user.first_name,' ',user.last_name) as name , user.picture , rating.date_created , rating.review FROM $table as rating
  INNER JOIN User as user ON user.id = rating.user_id AND user.enable = '0'
  WHERE rating.product_id = '$id' AND rating.enable = '0' GROUP BY rating.product_id ";

  ///echo $query;

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 
    array_push($list_of_data, [
        'id' => $row['id'] , 
        'user_id' => $row['user_id'] , 
        'user_image' => $row['picture'] , 
        'name' => $row['name'] , 
        'rating' => $row['rating'] ,
        'review' => $row['review'] ,
        'avg_rating' => $row['avg_rating'] ,
        'image' => retrieve_specific_rating_picture($row['id']) ,
        'date_created' => $row['date_created'] 
    ]);
        
   
  }

  return $list_of_data; 

}

function retrieve_product_sale($id) {
  
  $list_of_data = [];

  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_order_meta'];
  $query = "SELECT COUNT(*) as total_sales 
  FROM $table 
  WHERE product_id = '$id' ";

  ///echo $query;

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 
    $total_sales = $row['total_sales'];
    
  }

  return $total_sales; 

}

function retrieve_product_sale_type($id) {
  
  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_sale'];
  $query = "SELECT sales.discount , sale_meta.type
  FROM $table as sales
  INNER JOIN SaleMeta as sale_meta ON sale_meta.id = sales.sale_type
  WHERE sales.product_id = '$id' ";

  ///echo $query;

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 
    $discount = $row['discount'].':'.$row['type'];
    
  }

  return $discount; 

}



function retrieve_product_attribute($id) {
  
  $list_of_data = [];

  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_product_attribute'];
  $query = "SELECT product_attribute.*
  FROM $table as product_attribute
  WHERE product_attribute.product_id = '$id' AND product_attribute.enable = '0' ";

  ///echo $query;

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 
      array_push($list_of_data, [
        'id' => $row['id'] , 
        'name' => $row['name'] ,
        'item' => retrieve_product_attribute_item($row['id']) 
    ]);

  }

  return $list_of_data; 

}


function retrieve_product_attribute_item($id) {
  
  $list_of_data = [];

  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_attribute_item'];
  $query = "SELECT attr_item.*
  FROM $table as attr_item
  WHERE attr_item.attribute_id = '$id' AND attr_item.enable = '0' ";

  ///echo $query;

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 
      array_push($list_of_data, [
        'id' => $row['id'] , 
        'name' => $row['name'] ,
        'image' => $row['image'] ,
        'price' => $row['price'] 
    ]);

  }

  return $list_of_data; 

}

function retrieve_product_questions($id) {
  
  $list_of_data = [];

  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_product_question'];
  $query = "SELECT question.*
  FROM $table as question
  WHERE question.product_id = '$id' AND question.enable = '0' ";

  ///echo $query;

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 
      array_push($list_of_data, [
        'id' => $row['id'] , 
        'name' => $row['name'] ,
        'answer' => retrieve_question_answer($row['id']) 
    ]);

  }

  return $list_of_data; 

}

function retrieve_question_answer($id) {
  
  $list_of_data = [];

  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_question_answer'];
  $query = "SELECT answer.*
  FROM $table as answer
  WHERE answer.question_id = '$id' AND answer.enable = '0' ";

  ///echo $query;

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 
      array_push($list_of_data, [
        'id' => $row['id'] , 
        'answer' => $row['answer'] ,
        'user' => retrieve_specific_user($row['user_id'])
    ]);

  }

  return $list_of_data; 

}

function retrieve_shipping_rates($product_id) {
  
  $list_of_data = [];

  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_product_shipping'];
  $query = "SELECT customized_shipping.*
  FROM $table as shipping
  INNER JOIN CustomizedShipping as customized_shipping ON customized_shipping.id = shipping.shipping_id
  WHERE shipping.product_id = '$product_id' ";

  ///echo $query;

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 
      array_push($list_of_data, [
        'id' => $row['id'] , 
        'logo' => $row['logo'] ,
        'name' => $row['name'] ,
        'estimated_delivery_days' => $row['estimated_delivery_days']
    ]);

  }

  return $list_of_data; 

}





function retrieve_specific_product_shipping_rates($address_id,$product_id,$quantity,$cart_id,$courier_id) {
  
    $list_of_data = [];
    $data = new Data();
    $international_shipping;

    $table = $GLOBALS['table_name_product'];
    $query = "UPDATE Cart SET courier_id = '$courier_id' WHERE id = '$cart_id' ";
    $result=queryRunner($query);
    

     ///table_name_cart


    $table = $GLOBALS['table_name_cart'];
    $query = "SELECT cart.* , product.weight , SUM((product.weight * cart.quantity)) as total_weight 
    FROM $table as cart
    INNER JOIN Product as product ON product.id = cart.product_id AND product.enable = '0'
    WHERE cart.id IN ('$cart_id') AND cart.enable = '0' ";

    $result=queryRunner($query);
    while ($row = rowRetriever($result)) { 
         
         $weight = $row['total_weight'];

     }



    $table = $GLOBALS['table_name_product_shipping'];
    $query = "SELECT custom_shipping.* FROM CustomizedShipping as custom_shipping 
    WHERE id = '$courier_id'  ";

    $result=queryRunner($query);
    while ($row = rowRetriever($result)) { 
          
          ////$weight = $row['weight'];

          if ($row['type'] == "international") {
              $international_shipping = true; 
           break; 
          }
          elseif ($row['type'] == "customized") {
              $international_shipping = false;
           break;   

          }

    }

    
    if (!$international_shipping) {
      
      retrieve_customized_shipping_packages($product_id,$quantity,$weight,$courier_id);

      return;
    }


    $table = $GLOBALS['table_name_shipping'];
    $query = "SELECT shipping.*  FROM $table as shipping
    WHERE shipping.cart_id = '$cart_id'  ";

    ///echo $query." <BR>";

    $result=queryRunner($query);
    while ($row = rowRetriever($result)) { 
          array_push($list_of_data, [
            'id' => $row['rate_id'] , 
            'shipment_id' => $row['shipment_id'] , 
            'carrier' => $row['carrier'] ,
            'service' => $row['service'] ,
            'rate' => $row['rate']  ,
            'delivery_days' => $row['delivery_days'] ,
            'currency' => $row['currency'] 
           ]);

    }

    if ( count($list_of_data) > 0) {
       
            $data -> list_of_data = $list_of_data;
            $data -> code ="202";
            $data -> message ="Data Retrieve Successfully";

             $result = json_encode($data);
             echo "$result";
             return;

    }

    
   
    


    

    $table = $GLOBALS['table_name_user_meta'];
    $query = "SELECT meta.* , concat(user.first_name,' ',user.last_name) as customer_name , user.email_address as customer_email 
    FROM $table as meta
    INNER JOIN User as user ON user.id = meta.user_id
    WHERE meta.id = '$address_id'  ";

    ///echo "$query";

    $result=queryRunner($query);
    while ($row = rowRetriever($result)) { 
         $toAddress = $row['address'];
         $toApartment = $row['apartment'];
         $toCity = $row['city'];
         $toPostalCode = $row['postal_code'];
         $toCountry = $row['country'];
         $toPhone = $row['phone'];
         $toCustomerName = $row['customer_name'];
         $toCustomerEmail= $row['customer_email'];

     }

    

    $fromAddress = \EasyPost\Address::create(array(
        /*'city' => 'San Francisco',*/
        'zip' => '54810'
       ));

    $toAddress = \EasyPost\Address::create(array(
      
      'name' => $toCustomerName,
      'street1' => $toAddress,
      'street2' => $toApartment,
      'city' => $toCity,
      'zip' => $toPostalCode,
      'country' => $toCountry ,
      'phone' => $toPhone ,
      'email' => $toCustomerEmail

     ));

    $parcel = \EasyPost\Parcel::create(array(
      "predefined_package" => 'Parcel',
      "weight" => $weight
    ));

    $shipment = \EasyPost\Shipment::create(array(
      "to_address" => $toAddress,
      "from_address" => $fromAddress,
      "parcel" => $parcel
    ));

    foreach ($shipment->rates as $rate) {

          $query = "INSERT INTO Shipping (cart_id,rate_id,shipment_id,carrier,service,rate,delivery_days,currency) 
                    VALUES ('$cart_id','$rate->id','$rate->shipment_id','$rate->carrier','$rate->service','$rate->rate'
                    ,'$rate->delivery_days','$rate->currency')";

          $result=queryRunner($query); 

          array_push($list_of_data, [
            'id' => $rate->id , 
            'shipment_id' => $rate->shipment_id , 
            'carrier' => $rate->carrier ,
            'service' => $rate->service ,
            'rate' => $rate->rate  ,
            'delivery_days' => $rate->delivery_days ,
            'currency' => $rate->currency 
          ]);

    }

  

    if ( count($list_of_data) > 0) {
       
        $data -> list_of_data = $list_of_data;
        $data -> code ="202";
        $data -> message ="Data Retrieve Successfully";

     }else{

        $data -> code ="206";
        $data -> message ="No data available";

     }

    
     $result = json_encode($data);
     echo "$result";

}





/*function retrieve_questions($id) {
  
  $list_of_data = [];
  $data = new Data();


  $table = $GLOBALS['table_name_product_question'];
  $query = "SELECT question.*
  FROM $table as question
  WHERE question.product_id = '$id' AND question.enable = '0' ";


  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 
      array_push($list_of_data, [
        'id' => $row['id'] , 
        'name' => $row['name'] ,
        'answer' => retrieve_question_answer($row['id']) 
    ]);

  }


   if ( count($list_of_data) > 0) {
     
      $data -> list_of_data = $list_of_data;
      $data -> code ="202";
      $data -> message ="Data Retrieve Successfully";

   }else{

      $data -> code ="206";
      $data -> message ="No data available";

   }

  
   $result = json_encode($data);
   echo "$result";


}*/


function retrieve_answer($id) {
  
  $list_of_data = [];
   $data = new Data();

  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_question_answer'];
  $query = "SELECT answer.*
  FROM $table as answer
  WHERE answer.question_id = '$id' AND answer.enable = '0' ";

  ///echo $query;

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 
      array_push($list_of_data, [
        'id' => $row['id'] , 
        'answer' => $row['answer'] ,
        'user' => retrieve_specific_user($row['user_id'])
    ]);

  }

     if ( count($list_of_data) > 0) {
     
      $data -> list_of_data = $list_of_data;
      $data -> code ="202";
      $data -> message ="Data Retrieve Successfully";

   }else{

      $data -> code ="206";
      $data -> message ="No data available";

   }

  
   $result = json_encode($data);
   echo "$result";

}




function retrieve_specific_product_rating($id) {
  
  $list_of_data = [];
  $data = new Data();

  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_rating'];
  $query = "SELECT rating.id ,  rating.rating , user.id as user_id ,concat(user.first_name,' ',user.last_name) as name , user.picture , rating.date_created , rating.review FROM $table as rating
  INNER JOIN User as user ON user.id = rating.user_id AND user.enable = '0'
  WHERE rating.product_id = '$id' AND rating.enable = '0' ";

  ///echo $query;

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 
    array_push($list_of_data, [
        'id' => $row['id'] , 
        'user_id' => $row['user_id'] , 
        'user_image' => $row['picture'] , 
        'name' => $row['name'] , 
        'rating' => $row['rating'] ,
        'review' => $row['review'] ,
        'image' => retrieve_specific_rating_picture($row['id']) ,
        'date_created' => $row['date_created'] 
    ]);
        
   
  }

   if ( count($list_of_data) > 0) {
     
      $data -> list_of_data = $list_of_data;
      $data -> code ="202";
      $data -> message ="Data Retrieve Successfully";

   }else{

      $data -> code ="206";
      $data -> message ="No data available";

   }

  
   $result = json_encode($data);
   echo "$result";

}



function retrieve_related_product($id) {
  
  $list_of_data = [];
  $data = new Data();


  /* For finding nearest places by keeping in view given radius */  

  
   $table = $GLOBALS['table_name_product'];
   $query = "SELECT pro.* FROM $table as product 
   INNER JOIN Product as pro ON pro.child_category_id = product.child_category_id AND pro.id <> '$id'
   WHERE  product.id = '$id' AND product.enable = '0' "; 
  ///echo $query;

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 
      array_push($list_of_data, [
        'id' => $row['id'] , 
        'images' => retrieve_product_images($row['id']) ,
        'brand' => retrieve_product_brand($row['id']) ,
        'cover_image' => $row['image'] ,
        'name' => $row['name'] ,
        'price' => $row['price'] ,
        'rating' => retrieve_product_average_rating($row['id']) ,
        'sold' => retrieve_product_sale($row['id']) 
         
    ]);

  }


   /*if ( count($list_of_data) > 0) {
     
      $data -> list_of_data = $list_of_data;
      $data -> code ="202";
      $data -> message ="Data Retrieve Successfully";

   }else{

      $data -> code ="206";
      $data -> message ="No data available";

   }

  
   $result = json_encode($data);
   echo "$result";*/
   return $list_of_data;

}




function add_product_into_cart($id,$user_id,$brand_id,$price,$attributes,$quantity,$courier_id) {
  
  $list_of_data = [];
  $attribute_id = [];
  $data = new Data();

 /// echo "$attributes";

  if (!is_null($attributes)) {
    
     $attribute_id =  array_filter(explode(',', $attributes)); 
     if (count($attribute_id)<=0) {
       $attribute_id =  array($attributes);
     }
     ///var_dump($attribute_id);

  }


  /* For finding nearest places by keeping in view given radius */  

  
   $table = $GLOBALS['table_name_cart'];
   $query = "INSERT INTO $table (user_id,brand_id,price,product_id,quantity,courier_id) VALUES ('$user_id','$brand_id','$price','$id','$quantity','$courier_id') "; 
   $result=queryRunner($query);
   $last_inserted_id = findLastInsertId();

  if ($result!=null) {

    for ($i=0; $i < count($attribute_id) ; $i++) { 
 
          $query_attr = "INSERT INTO CartMeta (cart_id,attribute_id) VALUES ('$last_inserted_id','$attribute_id[$i]') "; 
          $result_attr=queryRunner($query_attr);

    }
          
  }


   if ( $result != null) {
     
      $data -> code ="202";
      $data -> message ="Data Retrieve Successfully";

   }else{

      $data -> code ="206";
      $data -> message ="No data available";

   }

  
   $result = json_encode($data);
   echo "$result";
 

}




function retrieve_cart_product($user_id) {
  
  $list_of_data = [];
  $attribute_id = [];
  $data = new Data();


  /* For finding nearest places by keeping in view given radius */  

  
   $table = $GLOBALS['table_name_cart'];
   $query = "  SELECT product.* ,cart.id as cart_id , cart.quantity ,cart.selector, GROUP_CONCAT(cart_meta.attribute_id) as attribute_id , cart.price as cart_price
   FROM $table as cart
  INNER JOIN Product as product ON product.id = cart.product_id 
  LEFT JOIN CartMeta as cart_meta ON cart_meta.cart_id = cart.id
  WHERE cart.user_id = '$user_id' AND cart.enable = '0' AND cart.status = '0' GROUP BY cart_meta.cart_id ";

  ////echo $query; 

   $result=queryRunner($query);
   while ($row = rowRetriever($result)) { 
      array_push($list_of_data, [
        'id' => $row['cart_id'] , 
        'image' => retrieve_product_images($row['id']) ,
        'brand' => retrieve_product_brand($row['id']) ,
        'name' => $row['name'] ,
        'price' => $row['cart_price'] ,
        'selector' => $row['selector'] ,
        'rating' => retrieve_product_average_rating($row['id']) ,
        'quantity' => $row['quantity'] ,
        'attribute' => retrieve_cart_product_attribute($row['attribute_id']) 
         
    ]);

  }




   if ( count($list_of_data) > 0) {
     
      $data -> list_of_data = $list_of_data;
      $data -> code ="202";
      $data -> message ="Data Retrieve Successfully";

   }else{

      $data -> code ="206";
      $data -> message ="No data available";

   }

  
   $result = json_encode($data);
   echo "$result";
 

}


function delete_product_from_cart($cart_id) {
  
  $list_of_data = [];
  $attribute_id = [];
  $data = new Data();


  /* For finding nearest places by keeping in view given radius */  

  
   $table = $GLOBALS['table_name_cart'];
   $query = "DELETE FROM $table WHERE id  = '$cart_id' ";

  ////echo $query; 

   $result=queryRunner($query);
  




   if ($result != null) {
     

      $data -> code ="202";
      $data -> message ="Data Retrieve Successfully";

   }else{

      $data -> code ="206";
      $data -> message ="No data available";

   }

  
   $result = json_encode($data);
   echo "$result";
 

}


function retrieve_cart_product_attribute($id) {
  
  $list_of_data = [];


  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_attribute_item'];
  $query = "SELECT * FROM $table
  WHERE id IN ('$id')";

  ///echo $query; 

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 
      array_push($list_of_data, [
        'id' => retrieve_attribute_id($row['attribute_id']) , 
        'name' => retrieve_attribute_name($row['attribute_id']) ,
        'item' => retrieve_cart_product_attribute_item($row['id']) 
    ]);

  }

  return $list_of_data; 

}


function retrieve_attribute_name($id) {
  
  $name;

  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_attribute_item'];
  $query = "SELECT attr_item.name
  FROM ProductAttribute as attr_item
  WHERE attr_item.id = '$id' AND attr_item.enable = '0' ";

  ///echo $query;

  $result=queryRunner($query);
  while ($row = rowRetrieverObject($result)) { 
      $name = $row -> name;
  }

  return $name; 

}

function retrieve_attribute_id($id) {
  
  $id;

  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_attribute_item'];
  $query = "SELECT attr_item.id
  FROM ProductAttribute as attr_item
  WHERE attr_item.id = '$id' AND attr_item.enable = '0' ";

  ///echo $query;

  $result=queryRunner($query);
  while ($row = rowRetrieverObject($result)) { 
      $id = $row -> id;
  }

  return $id; 

}


function retrieve_cart_product_attribute_item($id) {
  
  $list_of_data = [];

  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_attribute_item'];
  $query = "SELECT attr_item.*
  FROM $table as attr_item
  WHERE attr_item.id IN ('$id') AND attr_item.enable = '0' ";

  ///echo $query;

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 
      array_push($list_of_data, [
        'id' => $row['id'] , 
        'name' => $row['name'] ,
        'image' => $row['image'] ,
        'price' => $row['price'] 
    ]);

  }

  return $list_of_data; 

}


function retrieve_product_in_billing($user_id) {
  
  $list_of_data = [];
  $list_of_address = [];
  $attribute_id = [];
  $data = new Data();


  /* For finding nearest places by keeping in view given radius */  

  
   $table = $GLOBALS['table_name_cart'];
   $query = "  SELECT product.* ,cart.id as cart_id ,cart.quantity , cart.courier_id , cart_meta.attr_id as attribute_id , cart.price as cart_price
   FROM $table as cart
  INNER JOIN Product as product ON product.id = cart.product_id 
  /*INNER JOIN CartMeta as cart_meta ON cart_meta.cart_id = cart.id*/
  LEFT JOIN (

    SELECT cart_id , GROUP_CONCAT(attribute_id) as attr_id  FROM CartMeta GROUP BY cart_id 

  ) cart_meta ON cart_meta.cart_id = cart.id
  WHERE cart.user_id = '$user_id' AND cart.enable = '0' AND  cart.selector = '0' AND  cart.status = '0' GROUP BY cart.courier_id , cart_meta.attr_id ";

  ////echo $query; 

   $result=queryRunner($query);
   while ($row = rowRetriever($result)) {

      $total = $row['price'] * $row['quantity'];
      $insurance = ($total * 1 ) / 100;

      array_push($list_of_data, [
        'id' => $row['id'] , 
        'cart_id' => $row['cart_id'] ,
        'sub_category_id' => $row['sub_category_id'] , 
        'image' => retrieve_product_images($row['id']) ,
        'brand' => retrieve_product_brand($row['brand_id']) ,
        'name' => $row['name'] ,
        'price' => $row['cart_price'] ,
        'rating' => retrieve_product_average_rating($row['id']) ,
        'quantity' => $row['quantity'] ,
        'attribute' => retrieve_cart_product_attribute($row['attribute_id']) ,
        'shipping_insurance' => round($insurance,2) ,
        'tariff_insurance' => '0.56' ,
        'courier_id' => $row['courier_id']  

         
    ]);

  }

    $table = $GLOBALS['table_name_user'];
    $query = "SELECT user_meta.* , concat(user.first_name,' ',user.last_name) as name  
    FROM $table as user
    INNER JOIN UserMeta as user_meta ON user_meta.user_id = user.id
    WHERE user.enable = '0' AND user.id='$user_id'";

    ///echo $query;

    $result=queryRunner($query);
    while ($row = rowRetriever($result)) { 

         $result=queryRunner($query);
            while ($row = rowRetriever($result)) { 
                array_push($list_of_address, [
                  'id' => $row['id'] ,
                  'user_name' => $row['name'] ,
                  'address' => $row['address'] ,
                  'apartment' => $row['apartment'] ,
                  'city' => $row['city'] ,
                  'postal_code' => $row['postal_code'] ,
                  'country' => $row['country'],
                  'phone' => $row['phone']
                   
              ]);

            }

    }




   if ( count($list_of_data) > 0) {
     
      $data -> list_of_data = $list_of_data;
      $data -> payment_method =  retrieve_billing_methods();
      $data -> list_of_billing_address =  $list_of_address;
      $data -> code ="202";
      $data -> message ="Data Retrieve Successfully";

   }else{

      $data -> code ="206";
      $data -> message ="No data available";

   }

  
   $result = json_encode($data);
   echo "$result";
 

}



function retrieve_billing_methods() {
  
  $list_of_data = [];


  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_payment_method'];
  $query = "SELECT * FROM $table
  WHERE enable = '0' ";

  ///echo $query; 

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 
      array_push($list_of_data, [
        'id' => $row['id'] , 
        'name' => $row['name'] ,
        'image' => $row['image']
    ]);

  }

  return $list_of_data; 

}



function retrieve_specific_shipment_rate($quantity,$service,$shipment_id) {
  
  $list_of_data = [];

    ///echo $service;  
    $fromAddress = \EasyPost\Address::create(array(
        /*'city' => 'San Francisco',*/
        'zip' => '54810'
       ));

    $toAddress = \EasyPost\Address::create(array(
      
      /*'city' => 'Faisalabad',*/
      'zip' => '38600'
    ));

    $parcel = \EasyPost\Parcel::create(array(
      "predefined_package" => 'Parcel',
      "weight" => 10 * $quantity
    ));

    $shipment = \EasyPost\Shipment::create(array(
      "to_address" => $toAddress,
      "from_address" => $fromAddress,
      "parcel" => $parcel
    ));

    ////$shipment = \EasyPost\Shipment::retrieve($shipment_id);
    ///var_dump($shipment->get_rates());

    foreach ($shipment->rates as $rate) { 

          ///if ($rate->service==$service) {
            
               array_push($list_of_data, [
                'id' => $rate->id , 
                'shipment_id' => $rate->shipment_id , 
                'carrier' => $rate->carrier ,
                'service' => $rate->service ,
                'rate' => $rate->rate  ,
                'delivery_days' => $rate->delivery_days ,
                'currency' => $rate->currency 

               ]);

          ///}

         

      }



  return $list_of_data; 

}



function retrieve_specific_store_detail($id) {
  
    $list_of_categories = [];
    $list_of_data = [];
    $list_of_latest_data = [];
    $list_of_sale_data = [];
    $data = new Data();

    /* For finding nearest places by keeping in view given radius */  

  
      $table = $GLOBALS['table_name_brand'];
      $query = "SELECT brand.sub_category_id FROM $table as brand
      WHERE brand.id ='$id' AND brand.enable ='0' ";


      $result=queryRunner($query);
      while ($row = rowRetriever($result)) { 

          $sub_category_id = $row['sub_category_id'];

          $query_child_ctg = "SELECT  sub_ctg.id , sub_ctg.name as name , GROUP_CONCAT(child_sub_ctg.id) as child_id 
          FROM ChildSubCategories as child_sub_ctg
          INNER JOIN SubCategories as sub_ctg ON sub_ctg.id = child_sub_ctg.sub_category_id
          WHERE child_sub_ctg.sub_category_id IN ($sub_category_id) AND child_sub_ctg.enable ='0' 
          GROUP BY name ";

          $i = 0;

          $result_child=queryRunner($query_child_ctg);
          while ($row_child = rowRetriever($result_child)) { 

                ++$i;

                array_push($list_of_categories, [
                'category_id' => $row_child['id'] , 
                'category_name' => $row_child['name'] 
                 
                ]);  

                if ($i < 3) {

                  $detail = $row_child['child_id'].":".$id;
                    
                  array_push($list_of_data, [
                  'category_id' => $row_child['id'] , 
                  'category_name' => $row_child['name'] , 
                  'data' => retrieve_specific_store_product($detail,"child_sub_category_id",null) 
                   
                   ]);

                }  

          }

      }

  

    if ( count($list_of_data) > 0) {
       
        $data -> list_of_data = $list_of_data;
        $data -> list_of_latest_data = retrieve_specific_brand_latest_product($id);
        $data -> list_of_sale_data = retrieve_specific_brand_sale_product($id);
        $data -> list_of_categories = $list_of_categories;
        $data -> code ="202";
        $data -> message ="Data Retrieve Successfully";

     }else{

        $data -> code ="206";
        $data -> message ="No data available";

     }

    
     $result = json_encode($data);
     echo "$result";

}



function retrieve_specific_store_product($id,$type,$skip_ids) {
  
  $list_of_data = [];
  $data = new Data();


  /* For finding nearest places by keeping in view given radius */  

  
  if ($type == "sub_category") {

      $table = $GLOBALS['table_name_child_sub_categories'];
      $query = "SELECT product.* FROM $table as child_sub_ctg 
      INNER JOIN Product as product  ON product.child_category_id = child_sub_ctg.id AND product.enable = '0'
      WHERE child_sub_ctg.sub_category_id = '$id' AND child_sub_ctg.enable = '0' ";

  }
  else if ($type == "child_sub_category_id") {

      $table = $GLOBALS['table_name_product'];

      $dt = array_filter(explode(':', $id));
      $ctg_id = $dt[0];
      $brand_id = $dt[1];

      $query = "SELECT * FROM $table as product WHERE product.child_category_id IN ($ctg_id) AND product.enable = '0' AND product.brand_id = '$brand_id' LIMIT 10";

  }


  ///echo $query;


  ///echo $query;

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 
      array_push($list_of_data, [
        'id' => $row['id'] , 
        'images' => retrieve_product_images($row['id']) ,
        'brand' => retrieve_product_brand($row['id']) ,
        'cover_image' => $row['image'] ,
        'name' => $row['name'] ,
        'price' => $row['price'] ,
        'rating' => retrieve_product_average_rating($row['id']) ,
        'sold' => retrieve_product_sale($row['id'])
         
    ]);

  }


   return $list_of_data;

}


function retrieve_specific_brand_latest_product($id) {
  
  $list_of_data = [];
  ///$data = new Data();


  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_product'];
  $query = "SELECT * FROM $table as product WHERE product.brand_id = '$id' AND product.enable = '0' 
  AND DATE(product.date_created) >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH) LIMIT 6";

  ///echo $query;

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 
      array_push($list_of_data, [
        'id' => $row['id'] , 
        'images' => retrieve_product_images($row['id']) ,
        'brand' => retrieve_product_brand($row['id']) ,
        'cover_image' => $row['image'] ,
        'name' => $row['name'] ,
        'price' => $row['price'] ,
        'rating' => retrieve_product_average_rating($row['id']) ,
        'sold' => retrieve_product_sale($row['id'])
         
    ]);

  }

  //echo count($list_of_data);


   return $list_of_data;

}


function retrieve_specific_brand_sale_product($id) {
  
  $list_of_data = [];
  ///$data = new Data();


  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_sale'];
  $query = "SELECT product.* , sale.discount , meta.type , DATEDIFF(sale.end_date, NOW() ) AS days 
  FROM $table as sale 
  INNER JOIN Product as product ON product.id = sale.product_id 
  INNER JOIN SaleMeta as meta ON meta.id = sale.sale_type 
  WHERE sale.brand_id = '$id' AND NOW() BETWEEN TIMESTAMP(sale.start_date) AND TIMESTAMP(sale.end_date) ";

  ///echo $query;
  

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 
      array_push($list_of_data, [
        'id' => $row['id'] , 
        'images' => retrieve_product_images($row['id']) ,
        'brand' => retrieve_product_brand($row['id']) ,
        'cover_image' => $row['image'] ,
        'name' => $row['name'] ,
        'price' => $row['price'] ,
        'discount' => $row['discount'] ,
        'type' => $row['type'] ,
        'days_left' => $row['days'] ,
        'rating' => retrieve_product_average_rating($row['id']) ,
        'sold' => retrieve_product_sale($row['id'])
         
    ]);

  }

  //echo count($list_of_data);

   return $list_of_data;

}



function retrieve_store_product($id,$sub_category_id,$type,$sorting_type,$skip_ids) {
  
  $list_of_data = [];
  $data = new Data();


  if ($type == "sub_category") {

    $table = $GLOBALS['table_name_child_sub_categories'];

    if ($sorting_type == "Popular") {
          
             $query = "SELECT product.*  FROM $table as child_sub_ctg 
             INNER JOIN Product as product  ON product.child_category_id = child_sub_ctg.id AND product.enable = '0' %s
             WHERE /*child_sub_ctg.id = '$id' AND*/ child_sub_ctg.sub_category_id = '$sub_category_id' AND child_sub_ctg.enable = '0' LIMIT 10";

    } 
    else if ($sorting_type == "Most Reviews") {
          
             $query = "SELECT product.* , rating.total_review as review_count
             FROM $table as child_sub_ctg 
             INNER JOIN Product as product  ON product.child_category_id = child_sub_ctg.id AND product.enable = '0' %s
              LEFT JOIN (

                SELECT product_id ,count(*) as total_review FROM Rating  

             ) rating ON rating.product_id = product.id
             WHERE /*child_sub_ctg.id = '$id' AND */ child_sub_ctg.sub_category_id = '$sub_category_id' AND child_sub_ctg.enable = '0'  ORDER BY review_count DESC LIMIT 10";

    } 
    else if ($sorting_type == "Newest") {
          
             $query = "SELECT product.* 
             FROM  ChildSubCategories as child_sub_ctg 
             INNER JOIN Product as product ON product.child_category_id = child_sub_ctg.id AND product.enable = '0' AND 
             date(product.date_created) = (SELECT min(date(`date_created`)) FROM Product where date(`date_created`) < date(now())) %s
             WHERE /*child_sub_ctg.id = '$id' AND*/ child_sub_ctg.sub_category_id = '$sub_category_id' AND child_sub_ctg.enable = '0' LIMIT 10";

    } 
    else if ($sorting_type == "Low Price") {
          
             $query = "SELECT product.* FROM $table as child_sub_ctg 
             INNER JOIN Product as product  ON product.child_category_id = child_sub_ctg.id AND product.enable = '0' %s
             WHERE /*child_sub_ctg.id = '$id' AND*/ child_sub_ctg.sub_category_id = '$sub_category_id' AND child_sub_ctg.enable = '0' ORDER BY product.price+0 ASC LIMIT 10 ";

    } 
    else if ($sorting_type == "High Price") {
          
             $query = "SELECT product.* FROM $table as child_sub_ctg 
             INNER JOIN Product as product  ON product.child_category_id = child_sub_ctg.id AND product.enable = '0' %s
             WHERE /*child_sub_ctg.id = '$id' AND*/ child_sub_ctg.sub_category_id = '$sub_category_id' AND child_sub_ctg.enable = '0' ORDER BY product.price+0 DESC LIMIT 10 ";

    }
    else{

      $table = $GLOBALS['table_name_product'];
      $query = "SELECT product.* FROM ChildSubCategories as child_sub_ctg 
       INNER JOIN Product as product ON product.child_category_id = child_sub_ctg.id AND product.brand_id = '$id' %s
       WHERE child_sub_ctg.sub_category_id = '$sub_category_id' AND child_sub_ctg.enable = '0' LIMIT 10";

     }

    
  }
  else{

     $table = $GLOBALS['table_name_product'];



     if ($sorting_type == "Popular") {
          
             $query = "SELECT * FROM $table as product WHERE product.brand_id = $id AND product.enable = '0'  %s  LIMIT 10";

     } 
     else if ($sorting_type == "Most Reviews") {
          
             $query = "SELECT product.* , rating.total_review as review_count FROM $table as product  
             LEFT JOIN (

                SELECT product_id ,count(*) as total_review FROM Rating  

             ) rating ON rating.product_id = product.id
             WHERE product.brand_id = $id AND product.enable = '0' %s   ORDER BY review_count DESC LIMIT 10";

     } 
     else if ($sorting_type == "Newest") {
          
             $query = "SELECT * FROM $table as product WHERE product.brand_id = $id AND product.enable = '0' AND
             date(product.date_created) = (SELECT min(date(`date_created`)) FROM Product where date(`date_created`) < date(now()) ) %s  LIMIT 10";

     } 
     else if ($sorting_type == "Low Price") {
          
             $query = "SELECT * FROM $table as product WHERE product.brand_id = $id AND product.enable = '0' %s  ORDER BY product.price+0 ASC LIMIT 10 ";

     } 
     else if ($sorting_type == "High Price") {
          
             $query = "SELECT * FROM $table as product WHERE product.brand_id = $id AND product.enable = '0' %s  ORDER BY product.price+0 DESC LIMIT 10 ";

     } 
     else{

         $query = "SELECT * FROM $table as product WHERE product.brand_id = $id AND product.enable = '0' %s LIMIT 10";

     }

     
  }

  if (is_null($skip_ids)) {
     $query = sprintf($query," ");
  }
  else {
     $query = sprintf($query," AND product.id NOT IN (".$skip_ids.") ");
  }

  ///echo $query;

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 
          array_push($list_of_data, [
            'id' => $row['id'] , 
            'images' => retrieve_product_images($row['id']) ,
            'brand' => retrieve_product_brand($row['id']) ,
            'cover_image' => $row['image'] ,
            'name' => $row['name'] ,
            'price' => $row['price'] ,
            'rating' => retrieve_product_average_rating($row['id']) ,
            'sold' => retrieve_product_sale($row['id'])
             
        ]);

      }

 

 
   if ( count($list_of_data) > 0) {
       
        $data -> list_of_data = $list_of_data;
        $data -> code ="202";
        $data -> message ="Data Retrieve Successfully";

     }else{

        $data -> code ="206";
        $data -> message ="No data available";

     }

    
     $result = json_encode($data);
     echo "$result";

}


function retrieve_featured_categories() {
  
  $list_of_data = [];
  $data = new Data();


 $table = $GLOBALS['table_name_featured_categories'];
 $query = "SELECT * FROM $table WHERE enable = '0'";

 $result=queryRunner($query);
 while ($row = rowRetriever($result)) { 
          array_push($list_of_data, [
            'id' => $row['id'] , 
            'name' => $row['name'] ,
            'child_sub_categories' => $row['child_sub_categories'] 
             
        ]);

      }

 

 
   if ( count($list_of_data) > 0) {
       
        $data -> list_of_data = $list_of_data;
        $data -> code ="202";
        $data -> message ="Data Retrieve Successfully";

     }else{

        $data -> code ="206";
        $data -> message ="No data available";

     }

    
     $result = json_encode($data);
     echo "$result";

}



function retrieve_home_categorized_products($categories_id) {
  
  $list_of_data = [];
  $list_of_categories = [];
  $data = new Data();


 $table = $GLOBALS['table_name_child_sub_categories'];
 $query = "SELECT * FROM $table WHERE enable = '0' AND  id IN ($categories_id) ";

 ///echo $query;

 $result=queryRunner($query);
 while ($row = rowRetriever($result)) { 
          array_push($list_of_categories, [
            'id' => $row['id'] , 
            'name' => $row['name'] ,
            'image' => $row['image'] 
             
  ]);

  }


 $query_product = "SELECT * FROM Product WHERE enable = '0' AND  child_category_id IN ($categories_id) LIMIT 20";
 ///echo $query_product;

 $result_product=queryRunner($query_product);
 while ($row_product = rowRetriever($result_product)) { 
          array_push($list_of_data, [
            'id' => $row_product['id'] , 
            'images' => retrieve_product_images($row_product['id']) ,
            'brand' => retrieve_product_brand($row_product['id']) ,
            'cover_image' => $row_product['image'] ,
            'name' => $row_product['name'] ,
            'price' => $row_product['price'] ,
            'rating' => retrieve_product_average_rating($row_product['id']) ,
            'sold' => retrieve_product_sale($row_product['id'])
             
        ]);

      }

 

 
   if ( count($list_of_data) > 0) {
       
        $data -> list_of_categories = $list_of_categories;
        $data -> list_of_data = $list_of_data;
        $data -> code ="202";
        $data -> message ="Data Retrieve Successfully";

     }else{

        $data -> code ="206";
        $data -> message ="No data available";

     }

    
     $result = json_encode($data);
     echo "$result";

}



function retrieve_hot_data() {
  
  $list_of_data = [];
  $list_of_featured = [];
  $list_of_brand = [];
  $data = new Data();


 $table = $GLOBALS['table_name_featured_banner'];
 $query = "SELECT featured_banner.* , featured.detail FROM $table as featured_banner
 INNER JOIN (

  SELECT  featured_id as id , GROUP_CONCAT(product_id) as detail FROM FeaturedBannerMeta GROUP BY featured_id

 ) featured ON featured.id = featured_banner.id
 WHERE enable = '0'";

 $result=queryRunner($query);
 while ($row = rowRetriever($result)) { 
          array_push($list_of_featured, [
            'id' => $row['id'] , 
            'name' => $row['name'] ,
            'image' => $row['image'] ,
            'type' => $row['type'] ,
            'detail' => $row['detail'] 
             
  ]);

  }


 $table = $GLOBALS['table_name_brand'];
 $query = "SELECT brand.* , total_product.product_count , total_review.review_count , total_review.avg_rating  FROM $table as brand 
  LEFT JOIN 
  (

    SELECT product.brand_id as id, count(rating.id) as review_count , AVG(rating.rating) as avg_rating FROM Product as product 
    INNER JOIN Rating as rating ON product.id = rating.product_id
    

  ) as total_review ON total_review.id = brand.id 
  LEFT JOIN 
  (

    SELECT product.brand_id as id, count(product.id) as product_count FROM Product as product 
    

  ) as total_product ON total_product.id = brand.id
  WHERE  brand.enable = '0' AND brand.featured = '1' ";

  ////echo $query;

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 
      array_push($list_of_brand, [
        'id' => $row['id'] , 
        'name' => $row['name'] ,
        'image' => $row['image'] ,
        'cover_photo' => $row['cover_photo'],
        'items' => $row['product_count'],
        'reviews' => $row['review_count'],
        'rating' => $row['avg_rating']

    ]);

  }


 $query_product = "SELECT * FROM Product WHERE enable = '0' LIMIT 60";
 $result_product=queryRunner($query_product);
 while ($row_product = rowRetriever($result_product)) { 
          array_push($list_of_data, [
            'id' => $row_product['id'] , 
            'images' => retrieve_product_images($row_product['id']) ,
            'brand' => retrieve_product_brand($row_product['id']) ,
            'cover_image' => $row_product['image'] ,
            'name' => $row_product['name'] ,
            'price' => $row_product['price'] ,
            'rating' => retrieve_product_average_rating($row_product['id']) ,
            'sold' => retrieve_product_sale($row_product['id'])
             
        ]);

      }

 

 
   if ( count($list_of_featured) > 0) {
       
        $data -> list_of_featured = $list_of_featured;
        $data -> list_of_brand = $list_of_brand;
        $data -> list_of_data = $list_of_data;
        $data -> code ="202";
        $data -> message ="Data Retrieve Successfully";

     }else{

        $data -> code ="206";
        $data -> message ="No data available";

     }

    
     $result = json_encode($data);
     echo "$result";

}



function retrieve_sale_data() {
  
  $list_of_data = [];
  $list_of_featured = [];
  $list_of_brand = [];
  $data = new Data();


 $table = $GLOBALS['table_name_categories'];
 $query = "SELECT GROUP_CONCAT(sub_ctg.id) as sub_ctg_id, GROUP_CONCAT(sub_ctg.name) as sub_ctg_name
 FROM $table as ctg
 INNER JOIN SubCategories as sub_ctg ON sub_ctg.category_id = ctg.id AND sub_ctg.enable = '0'
 WHERE ctg.enable = '0' 
 GROUP BY ctg.id";

 $result=queryRunner($query);
 while ($row = rowRetriever($result)) { 


          $sub_ctg_id = array_filter(explode(',', $row['sub_ctg_id']));
          $sub_ctg_name = array_filter(explode(',', $row['sub_ctg_name']));

          for ($i=0; $i < count($sub_ctg_name) ; $i++) { 

              if (is_null($sub_ctg_id[$i])) {
                continue;
              }

              $data_list = retrieve_specific_child_categories_products($sub_ctg_id[$i]);

              if (count($data_list)<=0) {
                continue;
              }
            
              array_push($list_of_data, [
                  'id' => $sub_ctg_id[$i] , 
                  'name' => $sub_ctg_name[$i] ,
                  'list_of_data' => $data_list

               ]);

          }

  }

 
   if ( count($list_of_data) > 0) {
       
        $data -> list_of_data = $list_of_data;
        $data -> code ="202";
        $data -> message ="Data Retrieve Successfully";

     }else{

        $data -> code ="206";
        $data -> message ="No data available";

     }

    
     $result = json_encode($data);
     echo "$result";

}



function retrieve_specific_child_categories_products($id) {
  
  $list_of_data = [];
  $list_of_categories = [];
  $data = new Data();


 $table = $GLOBALS['table_name_child_sub_categories'];
 $query = "SELECT product.* , sale.sale_type , sale.discount ,DATEDIFF(sale.end_date, CURDATE()) AS days_left , TIMEDIFF( sale.end_date , CURDATE()) AS time_left 
 FROM $table as child_sub_ctg 
 INNER JOIN Product as product ON product.child_category_id = child_sub_ctg.id
 INNER JOIN Sale as sale ON sale.product_id = product.id AND sale.enable = '0' AND NOW() BETWEEN TIMESTAMP(sale.start_date) AND TIMESTAMP(sale.end_date)
 WHERE child_sub_ctg.enable = '0' AND  child_sub_ctg.sub_category_id IN ($id) ";

 ///echo $query;

 $result_product=queryRunner($query);
 while ($row_product = rowRetriever($result_product)) { 
          array_push($list_of_data, [
            'id' => $row_product['id'] , 
            'images' => retrieve_product_images($row_product['id']) ,
            'brand' => retrieve_product_brand($row_product['id']) ,
            'cover_image' => $row_product['image'] ,
            'name' => $row_product['name'] ,
            'price' => $row_product['price'] ,
            'rating' => retrieve_product_average_rating($row_product['id']) ,
            'sold' => retrieve_product_sale($row_product['id']) ,
            'days_left' => $row_product['days_left'] ,
            'time_left' => $row_product['time_left'] ,
            'sale_type' => $row_product['sale_type'] ,
            'discount' => $row_product['discount'] 
             
 ]);

 }


 return $list_of_data;

}



function retrieve_coupon_data($type) {
  
  $list_of_data = [];
  $data = new Data();


 $table = $GLOBALS['table_name_coupon'];
 $query = "SELECT coupon.* , coupon_meta.name as coupon_type , CASE coupon.nature 
  WHEN '1' THEN brand.name
  WHEN '2' THEN  child_sub_ctg.name
  WHEN '3' THEN product.name
  WHEN '4' THEN 'All'
  ELSE 'NO'
  END as category_type 
   FROM $table as coupon 
   INNER JOIN CouponMeta as coupon_meta ON coupon_meta.id = coupon.type

  LEFT JOIN Brand as brand ON brand.id = coupon.child_sub_category_id AND coupon.nature='1'
  LEFT JOIN ChildSubCategories as child_sub_ctg ON child_sub_ctg.id = coupon.child_sub_category_id AND coupon.nature='2'
  LEFT JOIN Product as product ON product.id = coupon.child_sub_category_id AND coupon.nature='3'

  WHERE coupon.enable = '0' AND  coupon.nature IN ('$type') AND
  (( coupon.user_limit = '0' AND coupon.duration_limit = '0'  AND NOW() BETWEEN TIMESTAMP(coupon.start_date) AND TIMESTAMP(coupon.end_date) 
    AND coupon.user_count > coupon.usage_count ) 
    
    OR
    
    ( coupon.duration_limit = '0' AND coupon.user_limit = '1'  AND NOW() BETWEEN TIMESTAMP(coupon.start_date) AND TIMESTAMP(coupon.end_date) ) 
    
    OR
    
    ( coupon.user_limit = '0' AND coupon.duration_limit = '1' AND coupon.user_count > coupon.usage_count  ) 

     OR
    
    ( coupon.user_limit = '1' AND coupon.duration_limit = '1'  ) 
  
   )";

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 

    array_push($list_of_data, [
                'id' => $row['id'] , 
                'category_type' => $row['category_type'] , 
                'name' => $row['name'] ,
                'tagline' => $row['tagline'] ,
                'code' => $row['code'] ,
                'offer' => $row['offer'] ,
                'coupon_type' => $row['type'] ,
                'expire_date' => $row['end_date'] 
                 
     ]);

     }

 
 if ( count($list_of_data) > 0) {
       
        $data -> list_of_data = $list_of_data;
        $data -> code ="202";
        $data -> message ="Data Retrieve Successfully";

  }else{

        $data -> code ="206";
        $data -> message ="No data available";

   }

    
 $result = json_encode($data);
 echo "$result";

}


function retrieve_specific_brand_coupon($id) {
  
      $list_of_data = [];
      $list_of_categories = [];
      $data = new Data();


       $table = $GLOBALS['table_name_coupon'];
       $query = "SELECT coupon.* , coupon_meta.name as coupon_type , CASE coupon.nature 
        WHEN '1' THEN brand.name
        WHEN '2' THEN  child_sub_ctg.name
        WHEN '3' THEN product.name
        ELSE 'NO'
        END as category_type 
         FROM $table as coupon 
         INNER JOIN CouponMeta as coupon_meta ON coupon_meta.id = coupon.type

        LEFT JOIN Brand as brand ON brand.id = coupon.child_sub_category_id AND coupon.nature='1'
        LEFT JOIN ChildSubCategories as child_sub_ctg ON child_sub_ctg.id = coupon.child_sub_category_id AND coupon.nature='2'
        LEFT JOIN Product as product ON product.id = coupon.child_sub_category_id AND coupon.nature='3'

        WHERE coupon.enable = '0' AND  coupon.brand_id IN ($id) ";

         ///echo $query;

      /* 

        SELECT coupon.* , coupon_meta.name as coupon_type , brand.* , child_sub_ctg.* , product.*
       FROM Coupon as coupon 
       INNER JOIN CouponMeta as coupon_meta ON coupon_meta.id = coupon.type

      LEFT JOIN Brand as brand ON brand.id = coupon.child_sub_category_id AND coupon.nature="1"
      LEFT JOIN ChildSubCategories as child_sub_ctg ON child_sub_ctg.id = coupon.child_sub_category_id AND coupon.nature="2"
      LEFT JOIN Product as product ON product.id = coupon.child_sub_category_id AND coupon.nature="3"

      WHERE coupon.enable = '0' AND  coupon.brand_id IN (3)


      SELECT coupon.* , coupon_meta.name as coupon_type , CASE coupon.nature 
      WHEN '1' THEN brand.name
      WHEN '2' THEN  child_sub_ctg.name
      WHEN '3' THEN product.name
      ELSE 'NO'
      END as title 
       FROM Coupon as coupon 
       INNER JOIN CouponMeta as coupon_meta ON coupon_meta.id = coupon.type

      LEFT JOIN Brand as brand ON brand.id = coupon.child_sub_category_id AND coupon.nature="1"
      LEFT JOIN ChildSubCategories as child_sub_ctg ON child_sub_ctg.id = coupon.child_sub_category_id AND coupon.nature="2"
      LEFT JOIN Product as product ON product.id = coupon.child_sub_category_id AND coupon.nature="3"

      WHERE coupon.enable = '0' AND  coupon.brand_id IN (3)






       */

         $result=queryRunner($query);
         while ($row = rowRetriever($result)) { 

                  if (!is_null($row['user_count']) && $row['user_count'] <=0) {
                      continue;
                  }

                  array_push($list_of_data, [
                    'id' => $row['id'] , 
                    'category_type' => $row['category_type'] , 
                    'name' => $row['name'] ,
                    'tagline' => $row['tagline'] ,
                    'code' => $row['code'] ,
                    'offer' => $row['offer'] ,
                    'coupon_type' => $row['type'] ,
                    'expire_date' => $row['end_date'] 
                     
         ]);

         }


         return $list_of_data;

}






function retrieve_all_brand($skip_ids) {
  
  $list_of_data = [];
  $data = new Data();

  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_brand'];
  $query = "SELECT brand.* , ctg.name as category_name , product.items FROM $table as brand 
  INNER JOIN Categories as ctg ON ctg.id = brand.category_id
  LEFT JOIN 
  (
    Select brand_id , count(*) as items FROM Product WHERE enable = '0'    
  ) product ON product.brand_id = brand.id 

  WHERE  brand.enable = '0' %s";

    if (is_null($skip_ids)) {
     $query = sprintf($query," LIMIT 10");
  }
  else {
     $query = sprintf($query," AND brand.id NOT IN (".$skip_ids.") LIMIT 10");
  }

  //echo $query;

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 

     $rating = array_filter(explode ("," , retrieve_specific_brand_average_rating($row['id'])));

      array_push($list_of_data, [
        'id' => $row['id'] , 
        'category_name' => $row['category_name'] ,
        'name' => $row['name'] ,
        'cover_photo' => $row['cover_photo'] ,
        'image' => $row['image'] ,
        'rating' => $rating[0],
        'count' => $rating[1],
        'items' => $row['items']
    ]);

  }




    if ( count($list_of_data) > 0) {
       
        $data -> list_of_data = $list_of_data;
        $data -> code ="202";
        $data -> message ="Data Retrieve Successfully";

  }else{

        $data -> code ="206";
        $data -> message ="No data available";

   }

    
 $result = json_encode($data);
 echo "$result";

}


function retrieve_specific_brand_average_rating($id) {
  
 $table = $GLOBALS['table_name_rating'];
 $query = "SELECT IF(rating.rating IS NOT NULL, AVG(rating.rating) , '0')  as avg_rating ,  count(rating.rating) as rating_count
 FROM $table as rating  
 INNER JOIN Product as product ON product.id = rating.product_id AND product.enable = '0' 
 INNER JOIN Brand as brand ON brand.id = product.brand_id AND brand.enable = '0' and brand.id = '$id'
 ";

 ///echo $query;

 $result=queryRunner($query);
 while ($row = rowRetriever($result)) { 

   $avg_rating = $row['avg_rating'].",".$row['rating_count'];
  
 }


 return $avg_rating;

}



function retrieve_featured_banner_products($banner_id,$type,$skip_ids) {
  
  $list_of_data = [];
  $data = new Data();

  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_featured_banner_meta'];
  
  if ($type == "list") {
   
          $query = "SELECT product.* , (SELECT sale_type FROM FeaturedBanner WHERE id = '$banner_id' AND enable = '0') as sale_type ,
          (SELECT sale_price FROM FeaturedBanner WHERE id = '$banner_id' AND enable = '0') as sale_price
          FROM $table as featured
          INNER JOIN Product as product ON product.id = featured.product_id %s
          WHERE featured.enable = '0' AND featured.featured_id = $banner_id  LIMIT 10";


          if (!is_null($skip_ids)) {
             $query = sprintf($query," AND product.id NOT IN (".$skip_ids.") ");
          }
          else{
            $query = sprintf($query," ");
          }
           


          //echo $query;
          $result=queryRunner($query);
          while ($row = rowRetriever($result)) { 
              array_push($list_of_data, [
                'id' => $row['id'] , 
                'images' => retrieve_product_images($row['id']) ,
                'brand' => retrieve_product_brand($row['id']) ,
                'cover_image' => $row['image'] ,
                'name' => $row['name'] ,
                'price' => $row['price'] ,
                'rating' => retrieve_product_average_rating($row['id']) ,
                'sale_type' => $row['sale_type'] ,
                'sale_price' => $row['sale_price'] ,
                'sold' => retrieve_product_sale($row['id'])
                 
            ]);

          }  

  }
  else if ($type == "product"){

          ///$table = $GLOBALS['table_name_product'];
          $query = "SELECT product.* , (SELECT sale_type FROM FeaturedBanner WHERE id = '$banner_id' AND enable = '0') as sale_type ,
          (SELECT sale_price FROM FeaturedBanner WHERE id = '$banner_id' AND enable = '0') as sale_price
          FROM $table as featured
          INNER JOIN Product as product ON product.id = featured.product_id 
          WHERE featured.enable = '0' AND featured.featured_id = $banner_id  ";


          $result=queryRunner($query);
          while ($row = rowRetriever($result)) { 
                array_push($list_of_data, [
                  'id' => $row['id'] , 
                  'images' => retrieve_product_images($row['id']) ,
                  'brand' => retrieve_product_brand($row['id']) ,
                  'cover_image' => $row['image'] ,
                  'name' => $row['name'] ,
                  'description' => $row['description'] ,
                  'price' => $row['price'] ,
                  'avg_rating' => retrieve_product_average_rating($row['id']) ,
                  'rating' => retrieve_product_rating($row['id']) ,
                  'sold' => retrieve_product_sale($row['id']) ,
                  'attribute' => retrieve_product_attribute($row['id']) ,
                  /*'shipping' => retrieve_shipping_rates(),*/
                  'faq' => retrieve_product_questions($row['id']) ,
                  'related_product' => retrieve_related_product($row['id']) 

                  
                   
            ]);

          }

  }


  
  if ( count($list_of_data) > 0) {
       
        $data -> list_of_data = $list_of_data;
        $data -> code ="202";
        $data -> message ="Data Retrieve Successfully";

  }else{

        $data -> code ="206";
        $data -> message ="No data available";

   }

    
 $result = json_encode($data);
 echo "$result";

}





function retrieve_trending_searches() {
  
  $list_of_data = [];
  $data = new Data();


  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_search'];
  $query = "SELECT search.*  FROM $table as search
  WHERE search.enable = '0'  GROUP BY search.name LIMIT 10";

  //echo $query;

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 

      array_push($list_of_data, [
        'id' => $row['id'] , 
        'name' => $row['name'] 
    ]);

  }


    if ( count($list_of_data) > 0) {
       
        $data -> list_of_data = $list_of_data;
        $data -> code ="202";
        $data -> message ="Data Retrieve Successfully";

  }else{

        $data -> code ="206";
        $data -> message ="No data available";

   }

    
 $result = json_encode($data);
 echo "$result";

}



function retrieve_favourites_data($user_id,$type,$skip_ids) {
  
  $list_of_data = [];
  $data = new Data();


  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_favourites'];



  if ($type == "favourite_store") {

         $query = "SELECT favourites.id , brand.id as brand_id , brand.name as brand_name , brand.cover_photo , brand.image  ,
          category.name as category_name , product.items 
          FROM Favourite as favourites
          INNER JOIN Brand as brand ON brand.id = favourites.meta_value
          INNER JOIN Categories as category ON category.id = brand.category_id
          LEFT JOIN 
          (
            Select brand_id , count(*) as items FROM Product WHERE enable = '0'    
          ) product ON product.brand_id = brand.id 
          WHERE favourites.user_id = '$user_id'  AND favourites.enable = '0' AND favourites.meta_key = '$type' ";

          $result=queryRunner($query);
          while ($row = rowRetriever($result)) { 

           $rating = array_filter(explode ("," , retrieve_specific_brand_average_rating($row['brand_id'])));
           array_push($list_of_data, [
                    'id' => $row['id'] , 
                    'brand_id' => $row['brand_id'] ,
                    'category_name' => $row['category_name'] ,
                    'name' => $row['brand_name'] ,
                    'cover_photo' => $row['cover_photo'] ,
                    'image' => $row['image'] ,
                    'rating' => $rating[0],
                    'count' => $rating[1],
                    'items' => $row['items']
                ]);
              

          }

         
      
  } 
  else if ($type == "favourite_product") {
         
          $query = "SELECT product.* , favourites.id as favourite_id 
          FROM $table as favourites
          INNER JOIN Product as product ON product.id = favourites.meta_value %s
          WHERE favourites.user_id = '$user_id' AND favourites.enable = '0' AND favourites.meta_key = '$type' LIMIT 10";


          if (!is_null($skip_ids)) {
             $query = sprintf($query," AND product.id NOT IN (".$skip_ids.") ");
          }
          else{
            $query = sprintf($query," ");
          }
           


          //echo $query;
          $result=queryRunner($query);
          while ($row = rowRetriever($result)) { 
              array_push($list_of_data, [
                'id' => $row['favourite_id'] ,
                'product_id' => $row['id'] , 
                'images' => retrieve_product_images($row['id']) ,
                'brand' => retrieve_product_brand($row['id']) ,
                'cover_image' => $row['image'] ,
                'name' => $row['name'] ,
                'price' => $row['price'] ,
                'rating' => retrieve_product_average_rating($row['id']) ,
                'sale_type' => $row['sale_type'] ,
                'sale_price' => $row['sale_price'] ,
                'sold' => retrieve_product_sale($row['id'])
                 
            ]);

          } 


  }


  ///echo $query;



    if ( count($list_of_data) > 0) {
       
        $data -> list_of_data = $list_of_data;
        $data -> code ="202";
        $data -> message ="Data Retrieve Successfully";

  }else{

        $data -> code ="206";
        $data -> message ="No data available";

   }

    
 $result = json_encode($data);
 echo "$result";

}




function retrieve_searches_products($search) {
  
  $list_of_data = [];
  $data = new Data();


  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_tags'];
  $query = "SELECT product.*  FROM $table as tags
  INNER JOIN Product as product ON product.id = tags.product_id
  WHERE tags.enable = '0' AND tags.name like '%$search%'";

  ///echo $query;

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 

       $result=queryRunner($query);
          while ($row = rowRetriever($result)) { 
              array_push($list_of_data, [
                'id' => $row['id'] ,
                'images' => retrieve_product_images($row['id']) ,
                'brand' => retrieve_product_brand($row['id']) ,
                'cover_image' => $row['image'] ,
                'name' => $row['name'] ,
                'price' => $row['price'] ,
                'rating' => retrieve_product_average_rating($row['id']) ,
                'sale_type' => $row['sale_type'] ,
                'sale_price' => $row['sale_price'] ,
                'sold' => retrieve_product_sale($row['id'])
                 
            ]);

          }

  }


    if ( count($list_of_data) > 0) {
       
        $data -> list_of_data = $list_of_data;
        $data -> code ="202";
        $data -> message ="Data Retrieve Successfully";

  }else{

        $data -> code ="206";
        $data -> message ="No data available";

   }

    
 $result = json_encode($data);
 echo "$result";

}



function change_favourite_status($id,$user_id,$type,$action) {
  
  $list_of_data = [];
  $data = new Data();


  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_favourites'];

  if ($action == "delete") {

    $query = "DELETE  FROM $table WHERE meta_value = '$id' AND user_id = '$user_id' ";

  }
  else if ($action == "insert") {

    $query = "INSERT INTO $table (user_id,meta_key,meta_value)  VALUE('$user_id','$type','$id')";

  }
  

  echo $query;

  $result=queryRunner($query);
  

}



function change_follow_status($id,$user_id,$type,$action) {
  
  $list_of_data = [];
  $data = new Data();


  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_following'];

  if ($action == "delete") {

    $query = "DELETE  FROM $table WHERE meta_value = '$id' AND user_id = '$user_id' ";

  }
  else if ($action == "insert") {

    $query = "INSERT INTO $table (user_id,meta_key,meta_value)  VALUE('$user_id','$type','$id')";

  }
  

  ///echo $query;

  $result=queryRunner($query);
  

}



function update_product_quantity_delete($id,$quantity,$type) {
  
  $list_of_data = [];
  $data = new Data();


  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_cart'];

  if ($type == "delete") {

    $query = "DELETE  FROM $table WHERE id = '$id' ";

  }
  else if ($type == "update") {

    $query = "UPDATE $table SET quantity = '$quantity' WHERE id = '$id' ";

  }
  else if ($type == "update_cart_product") {

    $query = "UPDATE $table SET selector = '$quantity' WHERE id = '$id' ";

  }
  

  ///echo $query;

  $result=queryRunner($query);
  

}



function retrieve_available_addresses($user_id) {
  
  $list_of_data = [];
  $data = new Data();


  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_user'];
  $query = "SELECT user_meta.* , concat(user.first_name,' ',user.last_name) as name  
  FROM $table as user
  INNER JOIN UserMeta as user_meta ON user_meta.user_id = user.id
  WHERE user.enable = '0' AND user.id='$user_id'";

  ///echo $query;

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 

       $result=queryRunner($query);
          while ($row = rowRetriever($result)) { 
              array_push($list_of_data, [
                'id' => $row['id'] ,
                'user_name' => $row['name'] ,
                'address' => $row['address'] ,
                'apartment' => $row['apartment'] ,
                'city' => $row['city'] ,
                'postal_code' => $row['postal_code'] ,
                'country' => $row['country'],
                'phone' => $row['phone']
                 
            ]);

          }

  }





    if ( count($list_of_data) > 0) {
       
        $data -> list_of_data = $list_of_data;
        $data -> code ="202";
        $data -> message ="Data Retrieve Successfully";

  }else{

        $data -> code ="206";
        $data -> message ="No data available";

   }

    
 $result = json_encode($data);
 echo "$result";

}

function delete_specific_address($address_id) {
  
  $list_of_data = [];
  $data = new Data();


  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_user_meta'];
  $query = "DELETE FROM $table 
  WHERE id='$address_id' ";

  ///echo $query;

  $result=queryRunner($query);

  if ($result!=null) {
       
        $data -> code ="202";
        $data -> message ="Data Retrieve Successfully";

  }else{

        $data -> code ="206";
        $data -> message ="No data available";

   }

    
 $result = json_encode($data);
 echo "$result";

}




function add_billing_address($user_id,$address,$apartment,$city,$postal_code,$country,$phone,$note) {
  
  $list_of_data = [];
  $data = new Data();


  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_user_meta'];
  $query = "INSERT INTO $table (user_id,address,apartment,city,postal_code,country,phone,note) VALUES ('$user_id' , '$address' , '$apartment' , '$city' , '$postal_code' , '$country' , '$phone' , '$note')";

  ///echo $query;

  $result=queryRunner($query);
 


  if ( $result != null) {
       
      
        $data -> code ="202";
        $data -> message ="Data Retrieve Successfully";

  }else{

        $data -> code ="206";
        $data -> message ="No data available";

   }

    
 $result = json_encode($data);
 echo "$result";

}


function redeem_coupon($user_id,$coupon_code) {
  
  $list_of_data = [];
  $data = new Data();


  /*SELECT coupon.* , coupon_category.name as coupon_category_name , 
    coupon_meta.name as coupon_type
  FROM Coupon as coupon
  INNER JOIN CouponMeta as coupon_meta ON coupon_meta.id = coupon.type
  INNER JOIN CouponCategory as coupon_category ON coupon_category.id = coupon.nature
  
  LEFT JOIN Coupon as time_coupon ON time_coupon.duration_limit = '0' AND NOW() BETWEEN TIMESTAMP(time_coupon.start_date) AND TIMESTAMP(time_coupon.end_date) 
  AND time_coupon.id = coupon.id
  
  LEFT JOIN Coupon as count_cond ON count_cond.user_limit = '0' AND  count_cond.user_count > '0' AND count_cond.id = coupon.id
  
  WHERE  
  ( coupon.user_limit = '1' AND coupon.duration_limit = '1' AND  coupon.code = 'ABCFGH' AND coupon.enable = '0'  ) AND
  
  (( coupon.duration_limit = '0'  AND  coupon.code = 'ABCFGH' AND coupon.enable = '0' AaND NOW() BETWEEN TIMESTAMP(coupon.start_date) AND TIMESTAMP(coupon.end_date) ) OR
  ( coupon.duration_limit = '1' AND  coupon.code = 'ABCFGH' AND coupon.enable = '0'  )) AND
  
  (( coupon.user_limit = '0' AND  coupon.code = 'ABCFGH' AND coupon.enable = '0' AND coupon.user_count >0 ) OR
  ( coupon.user_limit = '1' AND  coupon.code = 'ABCFGH' AND coupon.enable = '0'  ))*/


  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_coupon'];
  $query = "SELECT coupon.* , coupon_category.name as coupon_category_name , coupon_meta.name as coupon_type
  FROM $table as coupon
  INNER JOIN CouponMeta as coupon_meta ON coupon_meta.id = coupon.type
  INNER JOIN CouponCategory as coupon_category ON coupon_category.id = coupon.nature
    
  WHERE  
  ( coupon.user_limit = '1' AND coupon.duration_limit = '1' AND  coupon.code = '$coupon_code' AND coupon.enable = '0'  )
  
  OR

  ( coupon.user_limit = '0' AND coupon.duration_limit = '0' AND  coupon.code = '$coupon_code' AND coupon.enable = '0' AND NOW() BETWEEN TIMESTAMP(coupon.start_date) AND TIMESTAMP(coupon.end_date) AND coupon.user_count >0 ) 
  
  OR
  
  ( coupon.duration_limit = '0' AND coupon.user_limit = '1' AND  coupon.code = '$coupon_code' AND coupon.enable = '0' AND NOW() BETWEEN TIMESTAMP(coupon.start_date) AND TIMESTAMP(coupon.end_date) ) 
  
  OR
  
 ( coupon.user_limit = '0' AND coupon.duration_limit = '1' AND  coupon.code = '$coupon_code' AND coupon.enable = '0' AND coupon.user_count >0 )

   ";

  ///echo "$query";


  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 

       if ($row['coupon_category_name'] == "Store") {
          $term_id = $row['brand_id'];
       }
       else{
          $term_id = $row['child_sub_category_id'];
       }

       array_push($list_of_data, [
                'id' => $row['id'] ,
                'name' => $row['name'] ,
                'term_id' =>  $term_id  ,
                'tagline' => $row['tagline'] ,
                'code' => $row['code'] ,
                'type' => $row['coupon_type'] ,
                'offer' => $row['offer'] ,
                'nature' => $row['coupon_category_name'],
                'price_discount_value' => $row['price_discount_value'],
                'duration_limit' => $row['duration_limit'] ,
                'user_limit' => $row['user_limit'] 
                 
            ]);

  }


  if ( count($list_of_data) > 0) {
       
        $data -> list_of_data = $list_of_data;
        $data -> code ="202";
        $data -> message ="Data Retrieve Successfully";

  }else{

        $data -> code ="206";
        $data -> message ="No data available";

   }

    
 $result = json_encode($data);
 echo "$result";

}


function retrieve_customized_shipping_packages($product_id,$quantity,$weight,$courier_id) {
  
  $list_of_data = [];
  $list_of_services_packages = [];
  $data = new Data();

  ////$weight =  $weight;


  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_customized_shipping'];
  $query = "SELECT custom_shipping.id as courier_id , custom_shipping.logo as courier_logo , custom_shipping.name as courier_name , 
  custom_shipping.type as courier_type , custom_shipping.currency_code as currency_code , custom_shipping.currency_symbol as currency_symbol ,
  shipping_packages.id as package_id , shipping_packages.name as package_name , shipping_packages.delivery_days as delivery_days ,
  meta.id as package_meta_id , meta.from_weight as from_weight , meta.to_weight as to_weight , meta.rate as rate 
  FROM $table as custom_shipping
  INNER JOIN ShippingPackages as shipping_packages ON shipping_packages.customized_shipping_id = custom_shipping.id  AND shipping_packages.enable = '0'
  INNER JOIN (

      SELECT term_id as term_id , id , from_weight , to_weight , rate FROM ShippingPackagesMeta  

  ) meta ON meta.term_id = shipping_packages.id 
  
  WHERE custom_shipping.id = '$courier_id' ";

  ///echo "$query";

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 

     array_push($list_of_data, [
                'courier_id' => $row['courier_id'] ,
                'courier_logo' => $row['courier_logo'] ,
                'courier_name' => $row['courier_name'] ,

                'delivery_days' => $row['delivery_days'] ,
                'currency_code' => $row['currency_code'] ,
                'currency_symbol' => $row['currency_symbol'] ,
                
                'package_id' => $row['package_id'] ,
                'package_name' => $row['package_name'] ,

                'from_weight' => $row['from_weight'] ,
                'to_weight' => $row['to_weight'] ,

                'rate' => $row['rate'] 
                 
      ]);

  }

  for ($i=0; $i < count($list_of_data) ; $i++) { 


     $fromWeight = $list_of_data[$i]['from_weight'];
     $toWeight =  $list_of_data[$i]['to_weight'];

     if ($weight >= $fromWeight && $weight <= $toWeight) {

      
        array_push($list_of_services_packages, [
                  'id' => $list_of_data[$i]['courier_id'] ,
                  'shipment_id' => $list_of_data[$i]['package_id'] ,
                  'logo' => $list_of_data[$i]['courier_logo'] ,
                  'carrier' => $list_of_data[$i]['courier_name'] ,
                  'service' => $list_of_data[$i]['package_name'] ,
                  'rate' => $list_of_data[$i]['rate'] ,
                  'delivery_days' => $list_of_data[$i]['delivery_days'] ,
                  'currency' => $list_of_data[$i]['currency_code'] 
                   
        ]); 
    
        
     }
     else if ( $weight >= $fromWeight && $toWeight == "-1") {
       
       $total_kg = $weight / 1024;
       $old_value = $i-1;
       $price = $list_of_data[$old_value]['rate'];
       $total_price = $price + ($total_kg * $list_of_data[$i]['rate']);
       $total_price = round($total_price,2);

       ///echo "Total Kg = ".$total_kg." Total Price = ".$total_price." ";
       array_push($list_of_services_packages, [
                  'id' => $list_of_data[$i]['courier_id'] ,
                  'shipment_id' => $list_of_data[$i]['package_id'] ,
                  'logo' => $list_of_data[$i]['courier_logo'] ,
                  'carrier' => $list_of_data[$i]['courier_name'] ,
                  'service' => $list_of_data[$i]['package_name'] ,
                  'rate' => $total_price ,
                  'delivery_days' => $list_of_data[$i]['delivery_days'] ,
                  'currency' => $list_of_data[$i]['currency_code'] 
                  
                  
                   
        ]); 

     }


  }

  if ( count($list_of_services_packages) > 0) {
       
        $data -> list_of_data = $list_of_services_packages;
        $data -> code ="202";
        $data -> message ="Data Retrieve Successfully";

  }else{

        $data -> code ="206";
        $data -> message ="No data available";

   }

    
  $result = json_encode($data);
  echo "$result";

}


function retrieve_available_shipping($id) {
  
  $list_of_data = [];
  $data = new Data();


     /* For finding nearest places by keeping in view given radius */  

  
      $table = $GLOBALS['table_name_product'];
      $query = "SELECT * FROM $table as product 
      INNER JOIN ProductShipping as product_shipping ON product_shipping.product_id =  product.id 
      INNER JOIN CustomizedShipping as customized_shipping ON customized_shipping.id = product_shipping.shipping_id
      WHERE product.id = '$id' AND product.enable = '0' ";


      ///echo $query;

      $result=queryRunner($query);
      while ($row = rowRetriever($result)) { 
          array_push($list_of_data, [
            'id' => $row['id'] , 
            'logo' => $row['logo'] ,
            'name' => $row['name'] ,
            'estimated_delivery_days' => $row['estimated_delivery_days']
        ]);

      }


     if ( count($list_of_data) > 0) {
       
        $data -> list_of_data = $list_of_data;
        $data -> code ="202";
        $data -> message ="Data Retrieve Successfully";

     }else{

        $data -> code ="206";
        $data -> message ="No data available";

     }

    
     $result = json_encode($data);
     echo "$result";

}


function retrieve_questions($id) {
  
  $list_of_data = [];
  $data = new Data();

  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_product_question'];
  $query = "SELECT question.*
  FROM $table as question
  WHERE question.product_id = '$id' AND question.enable = '0' ";

  ///echo $query;

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 
      array_push($list_of_data, [
        'id' => $row['id'] , 
        'name' => $row['name'] ,
        'answer' => retrieve_question_answer($row['id']) 
    ]);

  }


   if ( count($list_of_data) > 0) {
     
      $data -> list_of_data = $list_of_data;
      $data -> code ="202";
      $data -> message ="Data Retrieve Successfully";

   }else{

      $data -> code ="206";
      $data -> message ="No data available";

   }

  
   $result = json_encode($data);
   echo "$result";


}



function add_question_into_product($user_id,$product_id,$question) {
  
  $list_of_data = [];
  $data = new Data();

  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_product_question'];
  $query = "INSERT INTO $table(user_id,product_id,name) VALUES('$user_id','$product_id','$question')";

  $result=queryRunner($query);


   return retrieve_questions($product_id);


}


function add_answer_into_question($user_id,$question_id,$answer) {
  
  $list_of_data = [];
  $data = new Data();

  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_question_answer'];
  $query = "INSERT INTO $table(user_id,question_id,answer) VALUES('$user_id','$question_id','$answer')";

  $result=queryRunner($query);


   return retrieve_answer($question_id);


}


function proceed_to_checkout($user_id,$address_id,$total_amount,$shipping_fee,$currency_symbol,$currency_code,$discounted_amount,$stripe_token,$order_detail) {
  
  $list_of_data = [];
  $data = new Data();

  if (is_null($discounted_amount)) {
    $discounted_amount = "0";
  }

  /* For finding nearest places by keeping in view given radius */  

  $random_no = generateRandomNumber(4);

  $table = $GLOBALS['table_name_question_answer'];
  $query = "INSERT INTO ListOfOrders (order_no,user_id,address_id,total_amount,shipping_fee,currency_symbol,currency_code,discounted_amount) 
  VALUES('$random_no','$user_id','$address_id','$total_amount','$shipping_fee','$currency_symbol','$currency_code','$discounted_amount')";

  ////echo $query;

  $result=queryRunner($query);
  $order_id = findLastInsertId();

  for ($i=0; $i < count($order_detail) ; $i++) { 
    
      $cart_id = $order_detail[$i]['cart_id'];  
      $product_id = $order_detail[$i]['product_id'];  
      $brand_id = $order_detail[$i]['brand_id'];  
      $quantity = $order_detail[$i]['quantity'];  
      $price = $order_detail[$i]['price'];  
      $attribute_id = $order_detail[$i]['attribute_id'];  

      $shipping_id = $order_detail[$i]['shipping_id'];
      $package_id = $order_detail[$i]['package_id'];
      $courier_rate = $order_detail[$i]['courier_rate'];  

      $coupon_id = $order_detail[$i]['coupon_id'];
      $discounted_amount = $order_detail[$i]['discounted_amount'];  

      $query = "INSERT INTO OrderMeta (term_id , brand_id , product_id , attribute_id , quantity , price , coupon_id , discounted_amount , shipping_id
      , package_id , courier_rate) 
      VALUES('$order_id','$brand_id','$product_id','$attribute_id','$quantity','$price','$coupon_id','$discounted_amount','$shipping_id' 
       , '$package_id' , '$courier_rate' )";      
      $result=queryRunner($query);


      $query = "UPDATE Cart SET status = 1 WHERE id = '$cart_id' ";
      $result=queryRunner($query);

  }


  $status =  chargePayment($stripe_token,($total_amount+$shipping_fee),$currency_code);
  

  if ( $status == "206") {
       
        $data -> code ="206";
        $data -> message ="No data available";

        

  }else{

        $query = "UPDATE ListOfOrders SET transaction_token = '$status' WHERE id = '$order_id' ";
        $result=queryRunner($query);

        $data -> code ="202";
        $data -> message ="Data Retrieve Successfully";

  }

    
  $result = json_encode($data);
  echo "$result";


}



function chargePayment($stripe_token,$amount,$currency_code){

  $stripe_keys = [];
  $currency_symbol_list = [];
  $code;
  $message;
  //$productOrder = new ProductOrder();
  
  /*$public_token = $GLOBALS['stripe_public_token'];
  $private_token = $GLOBALS['stripe_private_token'];*/
  

    /*$query="SELECT meta_value as currency_symbol FROM RestaurantMeta WHERE term_id='$restaurant_id' AND meta_key = '_restaurant_currency_name_' ";
    $result=queryRunner($query);
    while ($row = rowRetriever($result)) { 
         array_push($currency_symbol_list, [
          'currency_symbol' => $row['currency_symbol']

        ]);
     }

    $currency_symbol = $currency_symbol_list[0]['currency_symbol'];

    \Stripe\Stripe::setApiKey($private_token);  /// For Testing purpose , uncomment this line*/

    $total_amount = $amount * 100;
    try {

    //$charge = \Stripe\Charge::create(['amount' => 2000, 'currency' => 'usd', "customer" => $customer->id]);
    // Charge the Customer instead of the card
    $charge_object = \Stripe\Charge::create(array(
      "amount" => $total_amount, # amount in cents, again
      "currency" => $currency_code,
      "customer" => $stripe_token)
    );

    $code = $charge_object -> id;
    ///var_dump($charge_object);

    } catch(\Stripe\Exception\CardException $e) {
    // Since it's a decline, \Stripe\Exception\CardException will be caught

    echo 'Status is:' . $e->getHttpStatus() . '\n';
    echo 'Type is:' . $e->getError()->type . '\n';
    echo 'Code is:' . $e->getError()->code . '\n';

    // param is '' in this case

    /*echo 'Param is:' . $e->getError()->param . '\n';
    echo 'Message is:' . $e->getError()->message . '\n';*/

    $code = "206";
    $message = $e->getError()->message;

  } catch (\Stripe\Exception\RateLimitException $e) {
    // Too many requests made to the API too quickly

    /*echo 'Message is:' . $e->getError()->message . '\n';*/

    $code = "206";
    $message = $e->getError()->message;

  } catch (\Stripe\Exception\InvalidRequestException $e) {
    // Invalid parameters were supplied to Stripe's API

    /*echo 'Message is:' . $e->getError()->message . '\n';*/

    $code = "206";
    $message = $e->getError()->message;

  } catch (\Stripe\Exception\AuthenticationException $e) {
    // Authentication with Stripe's API failed
    // (maybe you changed API keys recently)

    /*echo 'Message is:' . $e->getError()->message . '\n';*/

    $code = "206";
    $message = $e->getError()->message;

  } catch (\Stripe\Exception\ApiConnectionException $e) {
    // Network communication with Stripe failed

    /*echo 'Message is:' . $e->getError()->message . '\n';*/

    $code = "206";
    $message = $e->getError()->message;

  } catch (\Stripe\Exception\ApiErrorException $e) {
    // Display a very generic error to the user, and maybe send
    // yourself an email

    /*echo 'Message is:' . $e->getError()->message . '\n';*/

    $code = "206";
    $message = $e->getError()->message;

  } catch (Exception $e) {
    // Something else happened, completely unrelated to Stripe

    /*echo 'Message is:' . $e->getError()->message . '\n';*/

    $code = "206";
    $message = $e->getError()->message;

  } 

  /*if ($code == "202") {
    
   $productOrder -> code ="202";
   $productOrder -> message = "Order Successfully";
   $productOrder -> order_id = $order_id;

  }else{

    $productOrder -> code ="206";
    $productOrder -> message = $message;

  }*/

  ///echo "Code = ".$code+ " Message = ".$message;
  return $code;
  ///$result = json_encode($productOrder);
    //echo "$result";

}


function retrieve_history($user_id,$type) {
  
  $list_of_order = [];
  $data = new Data();
  

  $type_conditon;
  if ($type == "-1") {
    $type_conditon = "";
  }
  else{
    $type_conditon = " AND list_of_order.status = ".$type;
  }

  $table = $GLOBALS['table_name_list_of_orders'];
  $query = "SELECT list_of_order.* ,concat(user.first_name ,' ',user.last_name) as customer_name , user_meta.address , user_meta.apartment , user_meta.city , shipping.logo ,
   shipping.name as shipping_name , packages.name as package_name , packages.delivery_days 
  FROM $table as list_of_order

 
  INNER JOIN (

    SELECT term_id , shipping_id as shipping_id , package_id as package_id FROM OrderMeta 
    GROUP BY term_id

  ) order_meta ON order_meta.term_id = list_of_order.id 
  INNER JOIN UserMeta as user_meta ON user_meta.id = list_of_order.address_id
  INNER JOIN User as user ON user.id = list_of_order.user_id
  LEFT JOIN CustomizedShipping as shipping ON shipping.id IN (order_meta.shipping_id)
  LEFT JOIN ShippingPackages as packages ON packages.customized_shipping_id IN (shipping.id)

  WHERE list_of_order.user_id = '$user_id' AND list_of_order.enable = '0' %s ";

  $query = sprintf($query,$type_conditon);

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) {

      $historyData = new HistoryData();

      $historyData -> id = $row['id'];
      $historyData -> order_no = $row['order_no'];

      $historyData -> customer_name = $row['customer_name'];
      $historyData -> customer_address = $row['address'];
      $historyData -> customer_apartment = $row['apartment'];
      $historyData -> customer_city = $row['city'];

      $historyData -> total_bill = $row['total_amount'];
      $historyData -> discount_bill = $row['discounted_amount'];
      $historyData -> shipping_fee = $row['shipping_fee'];

      $historyData -> currency_code = $row['currency_code'];
      $historyData -> currency_symbol = $row['currency_symbol'];

      $historyData -> courier_logo = $row['logo'];
      $historyData -> courier_name = $row['shipping_name'];
      $historyData -> courier_service = $row['package_name'];
      $historyData -> courier_delivery_day = $row['delivery_days'];

      $historyData -> list_of_product = retrieve_specific_order_products($row['id']);

      array_push($list_of_order, $historyData);

  }


  /*SELECT list_of_order.* , user_meta.* , shipping.* , packages.* , meta.*
  FROM ListOfOrders as list_of_order

  INNER JOIN OrderMeta as meta ON meta.term_id = list_of_order.id
  INNER JOIN (

    SELECT term_id , shipping_id as shipping_id , package_id as package_id FROM OrderMeta 
    GROUP BY term_id

  ) order_meta ON order_meta.term_id = list_of_order.id 
  INNER JOIN UserMeta as user_meta ON user_meta.user_id = list_of_order.address_id
  LEFT JOIN CustomizedShipping as shipping ON shipping.user_id IN (order_meta.shipping_id)
  LEFT JOIN ShippingPackages as packages ON packages.customized_shipping_id IN (packages.package_id)

  WHERE list_of_order.user_id = '1' AND user_id.enable = '0'


  
    INNER JOIN Brand as brand ON brand.id = meta.brand_id
  INNER JOIN Product as product ON product.id = meta.product_id
  LEFT JOIN ProductAttribute as product_attr ON product_attr.product_id = meta.attribute_id



  */


   if ( count($list_of_order) > 0) {
     
      $data -> list_of_data = $list_of_order;
      $data -> code ="202";
      $data -> message ="Data Retrieve Successfully";

   }else{

      $data -> code ="206";
      $data -> message ="No data available";

   }

  
   $result = json_encode($data);
   echo "$result";


}




function retrieve_specific_order_products($order_id) {

  $list_of_data = [];
  $table = $GLOBALS['table_name_list_of_orders'];
  $query = "SELECT order_meta.* , brand.name as brand_name , product.name as product_name  , product.image , IF(rating.rating IS NOT NULL, rating.rating , '0') as rating
   FROM OrderMeta as order_meta

   INNER JOIN Brand as brand ON brand.id = order_meta.brand_id 
   INNER JOIN Product as product ON product.id = order_meta.product_id
   LEFT JOIN Rating as rating ON rating.order_id = order_meta.id
   
   WHERE order_meta.term_id = '$order_id'";

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) {

      array_push($list_of_data, [
            'id' => $row['id'] , 
            'brand_id' => $row['brand_id'] ,
            'product_id' => $row['product_id'] ,
             'brand_name' => $row['brand_name'] ,
            'product_name' => $row['product_name'] ,
            'rating' => $row['rating'] ,
            'product_image' => $row['image'] ,
            'attribute' => retrieve_cart_product_attribute_item($row['attribute_id']) ,
            'quantity' => $row['quantity'] ,
            'price' => $row['price'] 
        ]);

  }

  return $list_of_data;


}



function add_reviews($order_id,$user_id,$brand_id,$product_id,$rating,$review,$pictures) {
  
  $list_of_data = [];
  $data = new Data();


  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_rating'];
  $query = "INSERT INTO $table (user_id,order_id,brand_id,product_id,rating,review) VALUES ('$user_id' , '$order_id' , '$brand_id' , '$product_id' , '$rating' , '$review' )";

  $result=queryRunner($query);
  $review_id = findLastInsertId();
  $folder_path = "admin/uploads/image/review_image/";

  for( $i = 0; $i<count($pictures); $i++ ) {
            

    $pictureData =  base64_decode($pictures[$i]['picture']);
    $picture_name = $pictures[$i]['picture'];
    $pictureName=($order_id.'_'.$i).'_rating_'.rand().'.webp';

    file_put_contents($folder_path.$pictureName, $pictureData);
    $query= "INSERT INTO ReviewPicture (review_id, image ) VALUES ('$review_id' , '$pictureName' )";
    ///echo "$query";
    $result=queryRunner($query);


    }
 


  if ( $result != null) {
       
      
        $data -> code ="202";
        $data -> message ="Data Retrieve Successfully";

  }else{

        $data -> code ="206";
        $data -> message ="No data available";

   }

    
 $result = json_encode($data);
 echo "$result";

}





function retrieve_specific_order_review_rating($order_id) {
  
  $list_of_data = [];
  $data = new Data();


  $table = $GLOBALS['table_name_rating'];
  $query = "SELECT rating.id ,  rating.review , rating_meta.image   FROM $table as rating
  LEFT JOIN (

    Select review_id as id , GROUP_CONCAT(image) as image  FROM ReviewPicture GROUP BY review_id

  ) rating_meta ON rating_meta.id = rating.id 
  WHERE rating.order_id = '$order_id'  ";


  $result=queryRunner($query);
  while ($row = rowRetriever($result)) {

    array_push($list_of_data, [
            'id' => $row['id'] , 
            'review' => $row['review'] ,
            'image' => $row['image'] 
        ]);

  }


   if ( count($list_of_data) > 0) {
     
      $data -> list_of_data = $list_of_data;
      $data -> code ="202";
      $data -> message ="Data Retrieve Successfully";

   }else{

      $data -> code ="206";
      $data -> message ="No data available";

   }

  
   $result = json_encode($data);
   echo "$result";


}



function save_billing_card($user_id,$card_comapny_name,$card_no,$stripe_token,$save_card) {
  
  $list_of_data = [];
  $data = new Data();

  $customer_id = create_customer_in_stripe($user_id,$stripe_token);

  if ($save_card == "0" ) {
   
    $table = $GLOBALS['table_name_rating'];
    $query = "INSERT INTO UserPaymentMethod(term_id,card_company_name,card_no,card_token) VALUES('$user_id','$card_comapny_name','$card_no','$customer_id') ";


    $result=queryRunner($query);
   

    if ( $result != null) {
       
        $data -> customer_id = $customer_id;
        $data -> code ="202";
        $data -> message ="Data Retrieve Successfully";

      }else{

        $data -> code ="206";
        $data -> message ="No data available";

      }

  }
  else{

      $data -> customer_id = $customer_id;
      $data -> code ="202";
      $data -> message ="Data Retrieve Successfully";

  }

  

   $result = json_encode($data);
   echo "$result";


}




function retrieve_specific_user_billing_cards($user_id) {
  
  $list_of_data = [];
  $data = new Data();

   
  $table = $GLOBALS['table_name_user_payment_method'];
  $query = "SELECT  user_payment_method.id , user_payment_method.card_company_name , user_payment_method.card_no  , payment_method.image , user_payment_method.card_token
  FROM $table as user_payment_method 
  INNER JOIN PaymentMethod as payment_method ON payment_method.name = user_payment_method.card_company_name
  WHERE user_payment_method.term_id = '$user_id' ";
  $result=queryRunner($query);
  while ($row = rowRetriever($result)) {

    array_push($list_of_data, [
            'id' => $row['id'] , 
            'card_company_name' => $row['card_company_name'] ,
            'card_no' => $row['card_no'] ,
            'image' => $row['image'] ,
            'card_token' => $row['card_token'] 
        ]);

  }



   if ( count($list_of_data) > 0) {
     
      $data -> list_of_data = $list_of_data;
      $data -> code ="202";
      $data -> message ="Data Retrieve Successfully";

   }else{

      $data -> code ="206";
      $data -> message ="No data available";

   }
  

   $result = json_encode($data);
   echo "$result";


}



function adding_refund_specific_order($user_id,$brand_id,$order_id,$review,$pictures) {
  
  $list_of_data = [];
  $data = new Data();

   
  $table = $GLOBALS['table_name_refund'];
  $query = "INSERT INTO $table(user_id,brand_id,term_id,reason) VALUES('$user_id','$brand_id','$order_id','$review') ";
  $result=queryRunner($query);

  $refund_id = findLastInsertId();
  $folder_path = "admin/uploads/image/refund_image/";

  for( $i = 0; $i<count($pictures); $i++ ) {
            

    $pictureData =  base64_decode($pictures[$i]['picture']);
    $picture_name = $pictures[$i]['picture'];
    $pictureName=($order_id.'_'.$i).'_refund_'.rand().'.webp';

    file_put_contents($folder_path.$pictureName, $pictureData);
    $query= "INSERT INTO RefundMeta (term_id, image ) VALUES ('$refund_id' , '$pictureName' )";
    $result=queryRunner($query);


  }


   if ( $result != null) {
     
    
      $data -> code ="202";
      $data -> message ="Data Retrieve Successfully";

   }else{

      $data -> code ="206";
      $data -> message ="No data available";

   }
  

   $result = json_encode($data);
   echo "$result";


}

function retrieve_specific_order_refund_request($order_id) {
  
  $list_of_data = [];
  $data = new Data();

   
  $table = $GLOBALS['table_name_refund'];
  $query = "SELECT  refund.id , refund.term_id as order_id , refund.reason , refund.response , refund_meta.refund_image
  FROM $table as refund 
  INNER JOIN (

   SELECT term_id as refund_id , id , GROUP_CONCAT(image) as refund_image  FROM RefundMeta GROUP BY refund_id 


  ) refund_meta ON refund_meta.refund_id = refund.id
  WHERE refund.term_id = '$order_id' ";

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) {

    array_push($list_of_data, [
            'id' => $row['id'] ,
            'order_id' => $row['order_id'] , 
            'reason' => $row['reason'] , 
            'response' => $row['response'] , 
            'refund_image' => $row['refund_image'] 
        ]);

  }



   if ( count($list_of_data) > 0) {
     
      $data -> list_of_data = $list_of_data;
      $data -> code ="202";
      $data -> message ="Data Retrieve Successfully";

   }else{

      $data -> code ="206";
      $data -> message ="No data available";

   }
  

   $result = json_encode($data);
   echo "$result";


}




function retrieve_specific_user_report($user_id,$type) {
  
  $list_of_data = [];
  $data = new Data();


   if ($type == "0") {
    
      $table = $GLOBALS['table_name_refund'];
      $query = "SELECT  refund.id , refund.term_id as order_id , refund.status as status , 
      product.name as product_name , product.image as product_image , order_meta.price , order_meta.quantity , 'refund' as type
      FROM $table as refund 
     
       INNER JOIN OrderMeta as order_meta ON order_meta.id = refund.term_id
      INNER JOIN Product as product ON product.id = order_meta.product_id
      
      WHERE refund.user_id = '$user_id' ";

   }
   else{

      $table = $GLOBALS['table_name_dispute'];
      $query = "SELECT  refund.id , refund.term_id as order_id , dispute.status as status , 
      product.name as product_name , product.image as product_image , order_meta.price , order_meta.quantity , 'dispute' as type

      FROM $table as dispute 
      INNER JOIN Refund as refund ON refund.id = dispute.term_id

       INNER JOIN OrderMeta as order_meta ON order_meta.id = refund.term_id
      INNER JOIN Product as product ON product.id = order_meta.product_id

      WHERE dispute.user_id = '$user_id' AND dispute.enable = '0' ORDER BY  status ASC";

      ///echo $query;

   }



   

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) {

    array_push($list_of_data, [
            'id' => $row['id'] ,
            'order_id' => $row['order_id'] ,
             'product_image' => $row['product_image'] ,  
            'product_name' => $row['product_name'] , 
            'price' => $row['price'] , 
            'quantity' => $row['quantity'] , 
            'status' => $row['status']  ,
            'type' => $row['type']  
          
        ]);

  }



   if ( count($list_of_data) > 0) {
     
      $data -> list_of_data = $list_of_data;
      $data -> code ="202";
      $data -> message ="Data Retrieve Successfully";

   }else{

      $data -> code ="206";
      $data -> message ="No data available";

   }
  

   $result = json_encode($data);
   echo "$result";


}


function add_dispute_specific_refund_request($user_id,$order_id) {
  
  $list_of_data = [];
  $data = new Data();

   
  $table = $GLOBALS['table_name_dispute'];
  $query = "INSERT INTO $table(user_id,term_id) VALUES('$user_id','$order_id') ";
  $result=queryRunner($query);

   if ( $result != null) {
     
    
      $data -> code ="202";
      $data -> message ="Data Retrieve Successfully";

   }else{

      $data -> code ="206";
      $data -> message ="No data available";

   }
  

   $result = json_encode($data);
   echo "$result";


}


function retrieve_specific_user_review($user_id) {
  
  $list_of_data = [];
  $data = new Data();

  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_rating'];
  $query = "SELECT rating.id , rating.rating , user.id as user_id ,concat(user.first_name,' ',user.last_name) as name , user.picture , rating.date_created , rating.review FROM User as user 
  INNER JOIN Rating as rating ON rating.user_id = user.id 
  WHERE user.id = '$user_id' AND user.enable = '0' ";

  ///echo $query;

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 
    array_push($list_of_data, [
        'id' => $row['id'] , 
        'user_id' => $row['user_id'] , 
        'user_image' => $row['picture'] , 
        'name' => $row['name'] , 
        'rating' => $row['rating'] ,
        'review' => $row['review'] ,
        'image' => retrieve_specific_rating_picture($row['id']) ,
        'date_created' => $row['date_created'] 
    ]);
        
   
  }

   if ( count($list_of_data) > 0) {
     
      $data -> list_of_data = $list_of_data;
      $data -> code ="202";
      $data -> message ="Data Retrieve Successfully";

   }else{

      $data -> code ="206";
      $data -> message ="No data available";

   }

  
   $result = json_encode($data);
   echo "$result";

}


function delete_specific_review($review_id) {
  
  $list_of_data = [];
  $data = new Data();

  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_rating'];
  $query = "DELETE FROM $table 
  WHERE id ='$review_id' ";

  ///echo $query;

  $result=queryRunner($query);

  if ($result!=null) {
     
      $data -> code ="202";
      $data -> message ="Data Retrieve Successfully";

  }else{

      $data -> code ="206";
      $data -> message ="No data available";

  }

  
   $result = json_encode($data);
   echo "$result";

}


function add_contact_us($user_id,$subject,$detail) {
  
  $list_of_data = [];
  $data = new Data();

   
  $table = $GLOBALS['table_name_contact_us'];
  $query = "INSERT INTO $table(user_id,subject,detail) VALUES('$user_id','$subject','$detail') ";
  $result=queryRunner($query);

   if ( $result != null) {
     
    
      $data -> code ="202";
      $data -> message ="Data Retrieve Successfully";

   }else{

      $data -> code ="206";
      $data -> message ="No data available";

   }
  

   $result = json_encode($data);
   echo "$result";


}


function retrieve_user_following($user_id) {
  
  $list_of_data = [];
  $data = new Data();

   
  $table = $GLOBALS['table_name_following'];
  $query = "SELECT brand.* , ctg.name as category_name , product.items FROM $table as following 
  INNER JOIN Brand as brand ON brand.id = following.meta_value AND brand.enable = '0'
  INNER JOIN Categories as ctg ON ctg.id = brand.category_id
  LEFT JOIN 
  (
    Select brand_id , count(*) as items FROM Product WHERE enable = '0'    
  ) product ON product.brand_id = brand.id 

  WHERE following.user_id ='$user_id' AND following.enable = '0' ";
  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 

     $rating = array_filter(explode ("," , retrieve_specific_brand_average_rating($row['id'])));

      array_push($list_of_data, [
        'id' => $row['id'] , 
        'category_name' => $row['category_name'] ,
        'name' => $row['name'] ,
        'cover_photo' => $row['cover_photo'] ,
        'image' => $row['image'] ,
        'rating' => $rating[0],
        'count' => $rating[1],
        'items' => $row['items']
    ]);

  }

   if (count($list_of_data)>0) {
     
      $data -> list_of_data = $list_of_data;
      $data -> code ="202";
      $data -> message ="Data Retrieve Successfully";

   }else{

      $data -> code ="206";
      $data -> message ="No data available";

   }
  

   $result = json_encode($data);
   echo "$result";


}


function login_user($user_phone_email,$password,$type) {
  
  $list_of_data = [];
  $data = new Data();

   
  $table = $GLOBALS['table_name_user'];
  $query = "SELECT user.id , user.picture , user.first_name , user.last_name , user.email_address , user.phone_number , fav.detail as favourite_detail ,
  fol.detail as following_detail
  FROM $table as user
  LEFT JOIN (

    SELECT user_id , GROUP_CONCAT(id,':',meta_key,':', meta_value) as detail FROM Favourite 

  ) fav ON fav.user_id =  user.id
  LEFT JOIN (

    SELECT user_id , GROUP_CONCAT(id,':',meta_key,':', meta_value) as detail FROM Following 

  ) fol ON fol.user_id =  user.id
  WHERE user.password  = '$password' AND user.enable = '0' AND %s ";
  
  if($type == "phone"){
     $query = sprintf($query,"user.phone_number='$user_phone_email' ");
  }
  else{
     $query = sprintf($query,"user.email_address='$user_phone_email' ");
  }

  ///echo "$query";
 

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 

     ////$rating = array_filter(explode ("," , retrieve_specific_brand_average_rating($row['id'])));
     $fav_list = [];
     $fol_list = [];

     if ($row['favourite_detail'] != " " || $row['favourite_detail'] != null) {
       
        $fav_arr = array_filter(explode(',', $row['favourite_detail']));
        for ($i=0; $i < count($fav_arr) ; $i++) { 

             $fav_detail_arr = array_filter(explode(':', $fav_arr[$i]));

             $fav = new UserFavouritesFollowing();

             $fav -> id = $fav_detail_arr[0];
             $fav -> key = $fav_detail_arr[1];
             $fav -> value = $fav_detail_arr[2];

             array_push($fav_list,$fav);
        }

     }

     if ($row['following_detail'] != " " || $row['following_detail'] != null) {
       
        $fav_arr = array_filter(explode(',', $row['following_detail']));
        for ($i=0; $i < count($fav_arr) ; $i++) { 

             $fav_detail_arr = array_filter(explode(':', $fav_arr[$i]));

             $fav = new UserFavouritesFollowing();

             $fav -> id = $fav_detail_arr[0];
             $fav -> key = $fav_detail_arr[1];
             $fav -> value = $fav_detail_arr[2];

             array_push($fol_list,$fav);
        }

     }

      array_push($list_of_data, [
        'id' => $row['id'] ,
        'picture' => $row['picture'] ,
        'first_name' => $row['first_name'] ,
        'last_name' => $row['last_name'] ,
        'email_address' => $row['email_address'] ,
        'phone_number' => $row['phone_number'] ,
        'favourite_detail' => $fav_list ,
        'following_detail' => $fol_list ,

        
    ]);

  }

   if (count($list_of_data)>0) {
     
      $data -> list_of_data = $list_of_data;
      $data -> code ="202";
      $data -> message ="Data Retrieve Successfully";

   }else{

      $data -> code ="206";
      $data -> message ="No data available";

   }
  

   $result = json_encode($data);
   echo "$result";


}


function register_user($first_name,$last_name,$email_address,$phone,$password) {
  
  $list_of_data = [];
  $data = new Data();

  if(!is_user_available($email_address,$phone)){

    $table = $GLOBALS['table_name_user'];
    $query = "INSERT INTO $table(first_name,last_name,email_address,phone_number,password) VALUES('$first_name','$last_name','$email_address','$phone','$password') ";
    $result=queryRunner($query);

  }
   
  

  if ($result != null) {

      $data -> code ="202";
      $data -> message ="Data Retrieve Successfully";

  }else{

      $data -> code ="206";
      $data -> message ="No data available";

  }
  

   $result = json_encode($data);
   echo "$result";


}



function is_user_available($email_address,$phone_number) {
  
  $list_of_data = [];
  $data = new Data();

   
  $table = $GLOBALS['table_name_user'];
  $query = "SELECT COUNT(*) as count
  FROM $table 
  WHERE email_address = '$email_address' AND phone_number = '$phone_number' ";

  //echo "$query";
   

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) {
    $count = $row['count'];
  }
  //echo "Size Array= ".count(rowRetriever($result));

  if($count>0){
    return true;
  }
  else{
    return false;
  }
 

}


function update_profile($user_id,$first_name,$last_name,$password,$pictures) {
  
  $list_of_data = [];
  $picture_query_part;
  $data = new Data();


  if ($pictures != null || $pictures != "" || isset($pictures) || !empty($pictures)) {

      $folder_path = "admin/uploads/image/user_image/";
      $pictureData =  base64_decode($pictures);
      $pictureName=($user_id.'_'.$i).'_profile_'.rand().'.webp';
      file_put_contents($folder_path.$pictureName, $pictureData);

      $picture_query_part = " , picture = '$pictureName' ";

  }
  

  $query= "UPDATE User SET first_name = '$first_name' , last_name = '$last_name'   %s WHERE id = '$user_id' ";
  $query = sprintf($query,$picture_query_part);
  $result=queryRunner($query);

  if ($password!="null") {

     $query= "UPDATE User SET password = '$password' WHERE id = '$user_id' ";
     $result=queryRunner($query);

  }
  
   if ( $result != null) {
     
      $data -> code ="202";
      $data -> user_picture = $pictureName;
      $data -> message ="Data Retrieve Successfully";
     

   }else{

      $data -> code ="206";
      $data -> message ="No data available";

   }
  

   $result = json_encode($data);
   echo "$result";


}


function retrieve_profile_detail($user_id) {
  
  $list_of_data = [];
  $data = new Data();

   
  $table = $GLOBALS['table_name_user'];
  $query = "SELECT picture , first_name , last_name , email_address , phone_number , password
   FROM $table WHERE id ='$user_id' AND enable = '0' ";

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 

      array_push($list_of_data, [
        'id' => $row['id'] , 
        'picture' => $row['picture'] ,
        'first_name' => $row['first_name'] ,
        'last_name' => $row['last_name'] ,
        'email_address' => $row['email_address'] ,
        'phone_number' => $row['phone_number'] ,
        'password' => $row['password'] 
    ]);

  }

   if (count($list_of_data)>0) {
     
      $data -> list_of_data = $list_of_data;
      $data -> code ="202";
      $data -> message ="Data Retrieve Successfully";

   }else{

      $data -> code ="206";
      $data -> message ="No data available";

   }
  

   $result = json_encode($data);
   echo "$result";


}




function retrieve_privacy_policy() {
  
  $list_of_data = [];
  $data = new Data();

   
  $table = $GLOBALS['table_name_privacy_policy'];
  $query = "SELECT * FROM $table ";

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 

      array_push($list_of_data, [
        'id' => $row['id'] , 
        'subject' => $row['subject'] ,
        'detail' => $row['detail'] 
    ]);

  }

   if (count($list_of_data)>0) {
     
      $data -> list_of_data = $list_of_data;
      $data -> code ="202";
      $data -> message ="Data Retrieve Successfully";

   }else{

      $data -> code ="206";
      $data -> message ="No data available";

   }
  

   $result = json_encode($data);
   echo "$result";


}


function retrieve_about_us() {
  
  $list_of_data = [];
  $data = new Data();

   
  $table = $GLOBALS['table_name_about_us'];
  $query = "SELECT * FROM $table ";

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 

      array_push($list_of_data, [
        'id' => $row['id'] , 
        'subject' => $row['subject'] ,
        'detail' => $row['detail'] 
    ]);

  }

   if (count($list_of_data)>0) {
     
      $data -> list_of_data = $list_of_data;
      $data -> code ="202";
      $data -> message ="Data Retrieve Successfully";

   }else{

      $data -> code ="206";
      $data -> message ="No data available";

   }
  

   $result = json_encode($data);
   echo "$result";


}




function send_test_request_to_places_api() {
  
  
      $curl = curl_init();
    curl_setopt_array($curl, array(
    CURLOPT_URL => "https://maps.googleapis.com/maps/api/place/autocomplete/json?input=1600+Amphitheatre&key=%3CAPI_KEY%3E&sessiontoken=1234567890",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 100,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_POSTFIELDS => $newJsonString,
    CURLOPT_HTTPHEADER => array(
    "cache-control: no-cache"
    ),
    ));
    $response = curl_exec($curl);
    $err = curl_error($curl);

    var_dump($response);


}




/* 
     Function for retrieving data for Popular Videos 

*/

function retrieve_home($id) {
  
  $list_of_data = [];
  $data = new Data();


  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_style'];
  $query = "INSERT INTO $table (product_id,quantity) VALUES ()";

  //echo $query;

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 
      array_push($list_of_data, [
        'id' => $row['id'] , 
        'name' => $row['name'] ,
        'orientation' => retrieve_style_orientation($row['orientation']) ,
        'type' => retrieve_style_type($row['type']) ,
        'tags' => retrieve_style_tags($row['tags']) ,
        'actions' => retrieve_style_actions($row['actions']) ,
        'setting' => retrieve_style_setting($row['setting']) ,
        'banner' => retrieve_style_banner($row['id']) ,
        'data' => retrieve_style_data($row['type']) ,
      ]);

  }

   
   if ( count($list_of_data) > 0) {
     
      $data -> list_of_data = $list_of_data;
      $data -> code ="202";
      $data -> message ="Data Retrieve Successfully";

   }else{

      $data -> code ="206";
      $data -> message ="No data available";

   }

  
   $result = json_encode($data);
   echo "$result";

}



function retrieve_style_type($id) {
  
  $name;


  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_type_style'];
  $query = "SELECT name FROM $table 
  WHERE id = '$id' AND enable = '0' ";

  ///echo $query;

  $result=queryRunner($query);
  while ($row = rowRetrieverObject($result)) { 
      $name = $row -> name;

  }

  return $name; 

}

function retrieve_style_tags($id) {
  
  $name;


  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_tag_style'];
  $query = "SELECT name FROM $table 
  WHERE id = '$id' AND enable = '0' ";

  ///echo $query;

  $result=queryRunner($query);
  while ($row = rowRetrieverObject($result)) { 
      $name = $row -> name;

  }

  return $name; 

}

function retrieve_style_orientation($id) {
  
  $name;


  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_orientation_style'];
  $query = "SELECT name FROM $table 
  WHERE id = '$id' AND enable = '0' ";

  ///echo $query;

  $result=queryRunner($query);
  while ($row = rowRetrieverObject($result)) { 
      $name = $row -> name;

  }

  return $name; 

}

function retrieve_style_actions($id) {
  
  $name;

  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_action_style'];
  $query = "SELECT name FROM $table 
  WHERE id = '$id' AND enable = '0' ";

  //echo $query;

  $result=queryRunner($query);
  while ($row = rowRetrieverObject($result)) { 
      $name = $row -> name;

  }

  return $name; 

}

function retrieve_style_setting($id) {
  
  $list_of_data = [];
  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_setting_style'];
  $query = "SELECT name FROM $table 
  WHERE id = '$id' AND enable = '0' ";

  ///echo $query;

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 
      array_push($list_of_data, [
        'name' => $row['name'] 

        
      ]);

  }


  return $list_of_data; 

}

function retrieve_style_banner($id) {
  
  $list_of_data = [];
  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_banner_style'];
  $query = "SELECT * FROM $table 
  WHERE style_id = '$id' AND enable = '0' ";

  ///echo $query;

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 
      array_push($list_of_data, [
      	'id' => $row['id'] ,
        'name' => $row['name'] , 
        'image' => $row['image'] 
      ]);

  }


  return $list_of_data; 

}

function retrieve_style_data($id) {
  
  $name;
  $list_of_data = [];

  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_type_style'];
  $query = "SELECT name FROM $table 
  WHERE id = '$id' AND enable = '0' ";

  ///echo $query;

  $result=queryRunner($query);
  while ($row = rowRetrieverObject($result)) { 
      $name = $row -> name;

  }

  ///echo $name;

  if ($name == "Categorized") {
  	
	  $query = "SELECT * FROM Categories WHERE  enable = '0' ";

	  ///echo $query;

	  $result=queryRunner($query);
	  while ($row = rowRetriever($result)) { 
	      array_push($list_of_data, [
	      	'id' => $row['id'] ,
	      	'name' => $row['name'] ,
	        'products' => retrieve_categorized_product($row['id'])
	      ]);

	  }


  }
  else if ($name == "Trending"  ) {
  	
  	  $id = [];
	  $query = "SELECT  id , SUM(quantity) as sales FROM ProductOrder 
	  WHERE enable = '0' AND DATE(date_created) >= DATE_SUB(CURDATE(), INTERVAL 2 WEEK)
	  GROUP BY product_id
	  ORDER BY sales DESC LIMIT 8";

	  ///echo $query;

	  $result=queryRunner($query);
	  while ($row = rowRetriever($result)) { 
	      array_push($id, $row['id']);
	  }

	  $idList = implode(',', $id); 
  


	  array_push($list_of_data, [
	      	'name' => $name ,
	        'products' => retrieve_categorized_product_by_ids($idList)
	      ]);


  }
  else if ( $name == "Top Selling" ) {
  	
	  $id = [];
	  $query = "SELECT  id , SUM(quantity) as sales FROM ProductOrder 
	  WHERE enable = '0' AND DATE(date_created) >= DATE_SUB(CURDATE(), INTERVAL 2 WEEK)
	  GROUP BY product_id
	  ORDER BY sales DESC LIMIT 8";

	  ///echo $query;

	  $result=queryRunner($query);
	  while ($row = rowRetriever($result)) { 
	      array_push($id, $row['id']);
	  }

	  $idList = implode(',', $id); 
  


	  array_push($list_of_data, [
	      	'name' => $name ,
	        'products' => retrieve_categorized_product_by_ids($idList)
	      ]);



  }

  return $list_of_data; 

}



function retrieve_categorized_product_by_ids($ids) {
  
  $list_of_data = [];
  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_product'];
  $query = "SELECT * FROM $table WHERE id IN ($ids)  AND enable = '0' ";

  ///echo $query;

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 
      array_push($list_of_data, [
      	'id' => $row['id'] ,
      	'store_id' => $row['store_id'] ,
      	'image' => retrieve_product_banner($row['id']) , 
        'name' => $row['name'] , 
        'price' => $row['price'] , 
        'attribute' => retrieve_product_attribute($row['id'])  ,
        'review' => retrieve_product_rating($row['id'])  
      ]);

  }


  return $list_of_data; 

}


function retrieve_product_banner($id) {
  
  $list_of_data = [];
  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_product_image'];
  $query = "SELECT * FROM $table 
  WHERE product_id = '$id' AND enable = '0' ";

  ///echo $query;

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 
      array_push($list_of_data, [
      	'id' => $row['id'] ,
        'name' => $row['name'] , 
        'image' => $row['image'] 
      ]);

  }


  return $list_of_data; 

}








/* 
     Function for retrieving data for Cities

*/

function retrieve_cities() {
  
  $list_of_data = [];
  $data = new Data();


  /* For finding nearest places by keeping in view given radius */  

 /* $table = $GLOBALS['table_name_city'];
  $query = "SELECT * FROM $table WHERE enable = '0' ";

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 
      array_push($list_of_data, [
        'id' => $row['id'] , 
        'name' => $row['name'] ,
        'latitude' => $row['latitude'] ,
        'longitude' => $row['longitude']
      ]);

  }
*/
   $list_of_data = retrieve_configurations();

   if ( count($list_of_data) > 0) {
     
      ////$data -> list_of_data = $list_of_data;
      $data -> configurations = $list_of_data;
      $data -> code ="202";
      $data -> message ="Data Retrieve Successfully";

   }else{

      $data -> code ="206";
      $data -> message ="No data available";

   }

  
   $result = json_encode($data);
   echo "$result";

}


function retrieve_configurations() {
  
  $list_of_data = [];
  /* For finding nearest places by keeping in view given radius */  

  $table = $GLOBALS['table_name_configuration'];
  $query = "SELECT * FROM $table ";

  //echo $query;

  $result=queryRunner($query);
  while ($row = rowRetriever($result)) { 
      array_push($list_of_data, [
        'id' => $row['id'] , 
        'name' => $row['meta_key'] ,
        'value' => $row['meta_value'] ,
        'value_02' => $row['meta_value_02'] 
      ]);

  }


  return $list_of_data; 

}








?>