<?php
/**
* @var ecatalog_products_retrieved should be false, but it will be set to true if there are products found
*/
$ecatalog_products_retrieved = false;
/**
* @var ecatalog_products should be null if there are ecatalog_products_retrieved is false.
*/
$ecatalog_products = null;
/**
* @var ecatalog_products should be false, but it will be set to true if there are products found
*/
$ecatalog_current_product = null;
/**
* @var ecatalog_query_filter data passed will be array;
*/
$ecatalog_query_filters = array();

/**
* Query all the products in products table
* Here is an inline example:
* <code>
* <?php
*  $products = ecatalog_query_products('url_slug='.$url);
* ?>
* </code>
* @return void
*/
function ecatalog_query_products($str_query) {

    global $ecatalog_query_filters;
    
    parse_str($str_query, $ecatalog_query_filters);
}
/**
* ecatalog_have_products will check if there are product existed or selected
* Note: ecatalog_query_products should be called first
* Here is an inline example:
* <code>
* <?php
*  ecatalog_query_products('url_slug=);
*  if(ecatalog_have_products()){}
* ?>
* </code>
* @return int
*/
function ecatalog_have_products() {
    global $ecatalog_products;
    global $ecatalog_products_retrieved;
    global $ecatalog_query_filters;

    if ($ecatalog_products_retrieved == false) {
        $ecatalog_products_retrieved = true;
        $ecatalog_products = ecatalog_get_products($ecatalog_query_filters);
    }

    return count($ecatalog_products) > 0;
}
/**
* ecatalog_product_count will count the ecatalog_products array
* Note: ecatalog_query_products should be called first
* Here is an inline example:
* <code>
* <?php
*  ecatalog_query_products('url_slug=);
*  if(ecatalog_product_count() > 0){}
* ?>
* </code>
* @return void
*/
function ecatalog_product_count() {
    global $ecatalog_products;
    echo count($ecatalog_products);
}
/**
* ecatalog_the_product shift the array and give the ecatalog_current_product and product
* Here is an inline example:
* <code>
* <?php
*  ecatalog_query_products('url_slug=);
*  if(ecatalog_product_count() > 0){
*   ecatalog_the_product(); 
*   }
* ?>
* </code>
* @return void
*/
function ecatalog_the_product() {
    global $ecatalog_products;
    global $ecatalog_current_product;
    $ecatalog_current_product = array_shift($ecatalog_products);
}
/**
* ecatalog_get_product_name will return the current product name
* Note: ecatalog_query_products should be called first
* Here is an inline example:
* <code>
* <?php
*  echo ecatalog_get_product_name();
* ?>
* </code>
* @return string | product name
*/
function ecatalog_get_product_name() {
    global $ecatalog_current_product;
    return $ecatalog_current_product['product_name'];
}
/**
* ecatalog_meta_title will return the current product meta title
* Note: ecatalog_query_products should be called first
* Here is an inline example:
* <code>
* <?php
*  echo ecatalog_meta_title();
* ?>
* </code>
* @return string | meta title
*/
function ecatalog_meta_title(){
    global $ecatalog_current_product;
    return $ecatalog_current_product['seo_title'];
}
/**
* ecatalog_meta_description will return the current product meta description
* Note: ecatalog_query_products should be called first
* Here is an inline example:
* <code>
* <?php
*  echo ecatalog_meta_description();
* ?>
* </code>
* @return string | meta description
*/
function ecatalog_meta_description(){
    global $ecatalog_current_product;
    return $ecatalog_current_product['seo_description'];
}
/**
* ecatalog_product_name will return the current product meta description
* Note: ecatalog_query_products should be called first
* Here is an inline example:
* <code>
* <html>
*  <p><?php ecatalog_product_name();?> </p>
* </html>
* </code>
* @return string | meta description
*/
function ecatalog_product_name() {
    echo ecatalog_get_product_name();
}
/**
* ecatalog_get_featured_image will return the current product featured image url
* Note: ecatalog_query_products should be called first
* Here is an inline example:
* <code>
* <?php
*  echo ecatalog_get_featured_image()
* ?>
* </code>
* @return string | featured image url
*/
function ecatalog_get_featured_image() {
    global $ecatalog_current_product;
    return $ecatalog_current_product['featured_image_url'];
}
/**
* ecatalog_featured_image will echo the current product featured image url
* Note: ecatalog_query_products should be called first
* Here is an inline example:
* <code>
* <html>
*  <image src="<?php ecatalog_featured_image(); ?>" alt=""/>
* </html>
* </code>
* @return void
*/
function ecatalog_featured_image() {
    echo ecatalog_get_featured_image();
}
/**
* ecatalog_get_product_permalink will return the current product permanent link
* Note: ecatalog_query_products should be called first
* Here is an inline example:
* <code>
* <?php
*  echo ecatalog_get_product_permalink();
* ?>
* </code>
* @return string | current product permanent link
*/
function ecatalog_get_product_permalink() {
    global $ecatalog_current_product;
    return get_bloginfo('installation_url') . '/products/' . $ecatalog_current_product['url_slug'];
}
/**
* ecatalog_product_permalink will echo the current product permanent link
* Note: ecatalog_query_products should be called first
* Here is an inline example:
* <code>
* <html>
*  <a href="<?php ecatalog_product_permalink()?">Link</a>
* </html>
* </code>
* @return void
*/
function ecatalog_product_permalink() {
    echo ecatalog_get_product_permalink();
}
/**
* ecatalog_get_url_slug will return the current product url slug
* Note: ecatalog_query_products should be called first
* Here is an inline example:
* <code>
* <?php
*  echo ecatalog_get_url_slug();
* ?>
* </code>
* @return string | return the current product url slug
*/
function ecatalog_get_url_slug() {
    global $ecatalog_current_product;
    return $ecatalog_current_product['url_slug'];
}
/**
* ecatalog_url_slug will echo the current product url slug
* Note: ecatalog_query_products should be called first
* Here is an inline example:
* <code>
* <html
*  <a href="website.com/<?php ecatalog_url_slug() ?>">Product Name</a>
* <html>
* </code>
* @return void
*/
function ecatalog_url_slug() {
    echo ecatalog_get_url_slug();
}
/**
* ecatalog_get_products will query based on categories and id
* Note: ecatalog_query_products should be called first
* Here is an inline example:
* <code>
* <?php
*  $posts = ecatalog_get_products(array('id' => $product_id));
* ?>
* </code>
* @return array | Array of Objects Product
*/
function ecatalog_get_products($options = array()) {
    global $db;
    $ecatalog_query_filters = array();
    $category_filter = array();
    $join_str = '';
    $posts_per_page = null;

    # Set default WHERE filters here. The product key is the column to filter.

    $ecatalog_query_filters['product_status'] = 'active';

    # Merge $options into the existing query filters.
    # Filters specified in $options will overwrite the options in $ecatalog_query_filters.

    $ecatalog_query_filters = array_merge($ecatalog_query_filters, $options);

    if (isset($ecatalog_query_filters['posts_per_page'])) {
        $posts_per_page = $ecatalog_query_filters['posts_per_page'];
        unset($ecatalog_query_filters['posts_per_page']);
    }

    if (isset($ecatalog_query_filters['category'])) {
        //  $category_filter
        # products_categories_relationship

        $ecatalog_query_filters['products_categories_relationship.category_id'] = explode(',', $ecatalog_query_filters['category']);
        $join_str = 'Inner Join products_categories_relationship on products.id = products_categories_relationship.product_id';
        unset($ecatalog_query_filters['category']);
    }

    $additional_filters_sql_array = array();


    foreach ($ecatalog_query_filters as $key => $value) {

        // str_replace($value, $key, $additional_filters_sql_array)
        $key = str_replace('.', '`.`', $key);
        if ((array) $value !== $value) {
            $additional_filters_sql_array[] = "`$key` = '$value'";
        } else {
            $additional_filters_sql_array[] = "`$key` IN('" . implode("','", $value) . "')";
        }
    }


    $additional_filters_sql = implode(' AND ', $additional_filters_sql_array);
    $additional_filters_sql = count($additional_filters_sql_array) > 0 ? 'Where ' . $additional_filters_sql : '';

    $limit_sql = $posts_per_page == null ? '' : 'Limit ' . $posts_per_page;

    $ecatalog_products_retrieved = array();
    $order = get_product_order_display(SESSION::get('order_type'));
    $result = $db->query("SELECT DISTINCT products.* FROM `products` $join_str $additional_filters_sql ".$order." $limit_sql ");
//    echo "SELECT DISTINCT products.* FROM `products` $join_str $additional_filters_sql ORDER BY `id` DESC $limit_sql";
    while ($row = $db->fetch($result, 'assoc')) {
        $ecatalog_products_retrieved[] = $row;
    }

    return $ecatalog_products_retrieved;
}
/**
* ecatalog_get_product will return product based on categories and id
* Note: ecatalog_query_products should be called first
* Here is an inline example:
* <code>
* <?php
*  $product = ecatalog_get_product($product_id);
* ?>
* </code>
* @return array | array current products 
*/
function ecatalog_get_product($product_id = null, $options = array()) {
    global $ecatalog_current_product;
    if ($product_id == null) {
        return $ecatalog_current_product;
    } else {
        $posts = ecatalog_get_products(array('id' => $product_id));
        if(isset($posts[0]))
            return $posts[0];
    }
}
/**
* ecatalog_get_product_images will return based on product id
* Note: ecatalog_query_products should be called first
* Here is an inline example:
* <code>
* <?php
*  $product_images = ecatalog_get_product_images(array('product_id' => $id));
* ?>
* </code>
* @return array | array current products images
*/
function ecatalog_get_product_images($options = array()) {
    global $db;
    $ecatalog_product_image = array();
    $result = $db->query("Select * From `products_gallery_images` Where `product_id` = '".$options['product_id']."'");
    while ($row = $db->fetch($result, 'assoc')) {
        $ecatalog_product_image[] = $row;
    }
    return $ecatalog_product_image;
}
/**
* ecatalog_get_categories will return categories based on categories and product_id
* Note: ecatalog_query_products should be called first
* Here is an inline example:
* <code>
* <?php
*   $categories = ecatalog_get_categories();
* ?>
* </code>
* @return array | array categories
*/
function ecatalog_get_categories($options = array()) {
    //var_dump($options);
    global $db;
    $ecatalog_query_filters = array();
    $posts_per_page = null;

    # Set default WHERE filters here. The product key is the column to filter.
    #
    # Merge $options into the existing query filters.
    # Filters specified in $options will overwrite the options in $ecatalog_query_filters.

    $ecatalog_query_filters = array_merge($ecatalog_query_filters, $options);
    // var_dump($options);

    if (isset($ecatalog_query_filters['product_id'])) {
        $ecatalog_query_filters['id'] = array();
        $result = $db->query("SELECT * FROM `products_categories_relationship` WHERE `product_id` = '" . $ecatalog_query_filters['product_id'] . "'");
      //  echo "SELECT * FROM `products_categories_relationship` WHERE `product_id` = '" . $ecatalog_query_filters['product_id'] . "'";
        while ($row = $db->fetch($result, 'assoc')) {
            $ecatalog_query_filters['id'][] = $row['category_id'];
        }
        unset($ecatalog_query_filters['product_id']);
    }
    /*
      if (isset($ecatalog_query_filters['posts_per_page'])) {
      $posts_per_page = $ecatalog_query_filters['posts_per_page'];
      unset($ecatalog_query_filters['posts_per_page']);
      }
     * 
     */
    $additional_filters_sql_array = array();


    foreach ($ecatalog_query_filters as $key => $value) {
        if ((array) $value == $value) {
            $additional_filters_sql_array[] = "`$key` IN('".implode("','",$value)."')";
        } else {
            $additional_filters_sql_array[] = "`$key` = '$value'";
        }
    }


    $additional_filters_sql = implode(' AND ', $additional_filters_sql_array);
    $additional_filters_sql = count($additional_filters_sql_array) > 0 ? 'Where ' . $additional_filters_sql."" : '';

    $limit_sql = $posts_per_page == null ? '' : 'Limit ' . $posts_per_page;
    $additional_filters_sql .= $additional_filters_sql == '' ? 'WHERE hide_category = "N"': "AND `hide_category` = 'N' ";
    $ecatalog_categories = array();
    $result = $db->query("SELECT * FROM `product_categories` $additional_filters_sql ORDER BY `sort_order` $limit_sql ");

    while ($row = $db->fetch($result, 'assoc')) {
        $ecatalog_categories[] = $row;
    }

    return $ecatalog_categories;
}
/**
* ecatalog_get_categories will return based on categories and product_id
* Note: ecatalog_query_products should be called first
* Here is an inline example:
* <code>
* <?php
*   $breadcrumb_categories = ecatalog_get_product_category_hierarchy($ecatalog_category['id']);
* ?>
* </code>
* @return array | array categories
*/
function ecatalog_get_product_category_hierarchy($category_id) {
    global $db;
    $category_hierarchy = array();
    $categories = ecatalog_get_categories(array('id' => $category_id));
    $category = $categories[0];
    $category_hierarchy[] = $category;
    while ($category['category_parent'] != 0) {
        $categories = ecatalog_get_categories(array('id' => $category['category_parent']));
        $category = $categories[0];
        $category_hierarchy[] = $category;
    }
    return array_reverse($category_hierarchy);
}
/**
* ecatalog_get_product_category_link will query based on categories and product_id
* Note: ecatalog_query_products should be called first
* Here is an inline example:
* <code>
* <html>
*   <a href="<?php echo ecatalog_get_product_category_link($breadcrumb_category['id']); ?>" title="<?php echo $breadcrumb_category['category_name']; ?>">Sample</a>
* </html>
* </code>
* @return array | array categories links
*/
function ecatalog_get_product_category_link($category_id) {


    $category_slug_hierarchy = array_map(function($item) {
        return $item['url_slug'];
    }, ecatalog_get_product_category_hierarchy($category_id));

    return get_bloginfo('installation_url') . '/categories/' . implode('/', $category_slug_hierarchy);
}
/**
* ecatalog_get_latest_products will return last 5 added products
* Here is an inline example:
* <code>
* <?php
*     $latest_products = ecatalog_get_latest_products();
* ?>
* </code>
* @return array | array last 5 added products
*/
function ecatalog_get_latest_products() {
    $rows = ecatalog_get_products(array('posts_per_page' => 5));

    // var_dump($rows);
    return $rows;
}

/**
* ecatalog_get_related_products will return 3 latest related products based on category of the current product
* Here is an inline example:
* <code>
* <?php
*      $related_products = ecatalog_get_related_products();
* ?>
* </code>
* @return array | 3 products
*/

function ecatalog_get_related_products() {
    global $ecatalog_current_product;
    $rows = array();
    $product_ids = ecatalog_get_related_product_id($ecatalog_current_product['id']);

    for ($i = 0; $i < count($product_ids); $i++) {
        $rows[] = ecatalog_get_product($product_ids[$i]);
    }

    return $rows;
}

/**
* ecatalog_get_related_product_id will return 3 latest related products id based on the current product id
* Here is an inline example:
* <code>
* <?php
*     $product_ids = ecatalog_get_related_product_id($ecatalog_current_product['id']);
* ?>
* </code>
* @return array | product ids
*/

function ecatalog_get_related_product_id($product_id) {
    global $db;

    $product_ids = array();
    $table = 'products_categories_relationship';
    $qry = $db->query("SELECT * FROM " . $table . " WHERE `product_id` = '$product_id'");

    if ($qry) {
        while ($category = $db->fetch($qry, 'array')) {
            $category_id = $category['category_id'];

            $qry_pcr = $db->query("SELECT * FROM " . $table . " WHERE `category_id` = '$category_id' ");

            if ($qry_pcr)
                while ($row = $db->fetch($qry_pcr, 'array'))
                    $product_ids[] = $row['product_id'];
        }
    }

    return $product_ids;
}
/**
* ecatalog_footer will print system option website_footer_copyright_text
* how to use it:  ecatalog_footer();
* @return array | product ids
*/
function ecatalog_footer(){
    echo get_system_option(array('option_name' => 'website_footer_copyright_text'));
}
/**
* ecatalog_get_product_tabs will return the product tabs for product description
* Here is an inline example:
* <code>
* <hmtl>
*      <span><?php ecatalog_footer(); ?></span>
* </html>
* </code>
* @return array | product tabs
*/
function ecatalog_get_product_tabs(){
    global $db;
    global $ecatalog_current_product;

    $id = $ecatalog_current_product['id'];
    $rows = array();

    $qry = $db->query("SELECT * FROM `product_tabs` WHERE `product_id` = '$id' ORDER BY `sort_order`");

    if($qry)
        while($row = $db->fetch($qry,'array'))
              $rows[] = $row;

    return $rows;

}
/**
* ecatalog_cart_add_product will add the product into the cart using sesssion
* Here is an inline example:
* <code>
* <?php
*     ecatalog_cart_add_product($product,$quantity);
* ?>
* </code>
* @return void
*/
function ecatalog_cart_add_product($product, $quantity){
$_SESSION['ecatalog_product_enquiry'] = isset($_SESSION['ecatalog_product_enquiry']) === FALSE ? array() : $_SESSION['ecatalog_product_enquiry'];
    
    $_SESSION['ecatalog_product_enquiry'][$product['id']]['product'] = $product;
    $_SESSION['ecatalog_product_enquiry'][$product['id']]['quantity'] = $quantity;
}
/**
* ecatalog_cart_delete_product will delete the product into the cart using sesssion
* Here is an inline example:
* <code>
* <?php
*     ecatalog_cart_delete_product($id);
* ?>
* </code>
* @return void
*/
function ecatalog_cart_delete_product($id){
     unset($_SESSION['ecatalog_product_enquiry'][$id]);
}
/**
* ecatalog_cart_get_products will return the product into the cart using sesssion
* Here is an inline example:
* <code>
* <?php
*     foreach ($_SESSION['ecatalog_product_enquiry'] as $key => $product_obj) {}
* ?>
* </code>
* @return array | products in cart
*/
function ecatalog_cart_get_products(){
    
    if(isset($_SESSION['ecatalog_product_enquiry'])===false)
        return array();

    return $_SESSION['ecatalog_product_enquiry'];
}
/**
* ecatalog_cart_get_products will return the product into the cart using sesssion
* Here is an inline example:
* <code>
* <?php
*     ecatalog_cart_clear_products();
* ?>
* </code>
* @return array | products in cart
*/
function ecatalog_cart_clear_products(){
unset($_SESSION['ecatalog_product_enquiry']);
}
/**
* get_product_order_display will return the product order query
* Here is an inline example:
* <code>
* <?php
*     $order = get_product_order_display($order);
*     $qry = $db->query("SELECT * FROM `products` WHERE match(`product_name`) against ('$keyword') AND `product_status` = 'active' ".$order);
* ?>
* </code>
* @return string | query order
*/
function get_product_order_display($order){
 switch ($order) {
        case 'price_asc':
            $order = "ORDER BY `price` ASC";
            break;
        case 'price_desc':
            $order = "ORDER BY `price` DESC";
            break;
        case 'featured_desc':
            $order = "ORDER BY `featured_product` ASC";
            break;
        case 'featured_asc':
            $order = "ORDER BY `featured_product` DESC";
            break;
        case 'product_title_asc':
            $order = "ORDER BY `product_name` ASC";
            break;
        case 'product_title_desc':
            $order = "ORDER BY `product_name` DESC";
            break;
        default:
            $order = '';

    } 
    return $order;     
}
/**
* get_product_order_display will return the product order query
* Here is an inline example:
* <code>
* <?php
*     $search_results = ecatalog_get_search_products($input,$order);
* ?>
* </code>
* @return string | query order
*/
function ecatalog_get_search_products($keyword,$order){
    global $db;
    $rows = array();
    $order = get_product_order_display($order);
   
    $qry = $db->query("SELECT * FROM `products` WHERE match(`product_name`) against ('$keyword') AND `product_status` = 'active' ".$order);

    if($qry)
        while($row = $db->fetch($qry, 'array'))
            $rows[] = $row;

    return $rows;

}
/**
* ecatalog_get_default_view will return the default view
* Here is an inline example:
* <code>
* <?php
*      $default_view = ecatalog_get_default_view();
* ?>
* </code>
* @return string | default view
*/
function ecatalog_get_default_view(){
    global $db;
    $qry = $db->query("SELECT * FROM `system_options` WHERE `option_name` = 'category_page_display_view' ");

    $row = $db->fetch($qry, 'array');

    if($row['option_value'] == 'LIST_ONLY')
        return 'hide_others';
    else if($row['option_value'] == 'LIST')
        return '-list';

    return '-grid';


}
/**
* ecatalog_get_product_display_order will return the display order
* ecatalog_get_default_view will return the default view
* Here is an inline example:
* <code>
* <?php
*      $order = ecatalog_get_product_display_order('');
* ?>
* </code>
* @return string | display order
*/
function ecatalog_get_product_display_order($order){
    global $db;
    $order = $order;
    if($order == ' '){
        $order = get_system_option(array('option_name' => 'category_page_display_order'));
    }
    switch($order){
        case 'PRICE_HIGH_TO_LOW':
            $order = 'price_desc';
            break;
        case 'PRICE_LOW_TO_HIGH':
            $order = 'price_asc';
            break;
        case 'FEATURED_LISTING_TOP':
            $order = 'featured_desc';
            break;
        case 'FEATURED_LISTING_BOTTOM':
            $order = 'featured_asc';
            break;
        case 'PRODUCT_TITLE_A_Z':
            $order = 'product_title_asc';
            break;
        default:
            $order = 'product_title_desc';
    }
    return $order;
}
/**
* ecatalog_convert_to_option will return coverted display order
* Here is an inline example:
* <code>
* <html>
*     <a href="#" ><?php echo ecatalog_convert_to_option(SESSION::get('order_type')); ?></a>
* </html>
* </code>
* @return string | coverted display order
*/
function ecatalog_convert_to_option($order){
    switch($order){
        case 'price_desc':
            $order = 'Price (High - Low)';
            break;
        case 'price_asc':
            $order = 'Price (Low - High)';
            break;
        case 'featured_desc':
            $order = 'Featured Listing (Top)';
            break;
        case 'featured_asc':
            $order = 'Featured Listing (Bottom)';
            break;
        case 'product_title_asc':
            $order = 'Product Title (A to Z)';
            break;
        default:
            $order = 'Product Title (Z to A)';
    }

    return $order;
}
/**
* ecatalog_highlight set session if new product is added to cart
* Here is an inline example:
* <code>
* <?php
*     ecatalog_highlight();
* ?>
* </code>
* @return void
*/
function ecatalog_highlight(){
    $_SESSION['update_cart'] = true;
}
/**
* ecatalog_unhighlight unset session 
* Here is an inline example:
* <code>
* <?php
*     ecatalog_unhighlight();
* ?>
* </code>
* @return void
*/
function ecatalog_unhighlight(){
    unset( $_SESSION['update_cart']);
}
/**
* ecatalog_add_contact_form_7 will add data based on submitted contact forms
* Here is an inline example:
* <code>
* <?php
*     if(ecatalog_add_contact_form_7($form_data)){}
* ?>
* </code>
* @return boolean
*/
function ecatalog_add_contact_form_7($form_data){
    global $db;
    $form_id =  $_SESSION['form_id'];
    
    $qry_current_form_data = $db->query("SELECT * FROM `contact_form_7_forms_collected_data` WHERE `form_id` = '$form_id'");
    if($db->numRows($qry_current_form_data) > 0){
        $row = $db->fetch($qry_current_form_data,'array');
        $json_data = json_decode($row['form_data'], true);
        $form_data = stripslashes($form_data);
        $json_decode = json_decode(trim($form_data),true);
        $json_data['rows'][] = $json_decode;
        $json_new_data = json_encode($json_data);
        
        return $db->query("UPDATE `contact_form_7_forms_collected_data` SET `form_data`= '$json_new_data' WHERE `id` = {$row['id']}");
    }else{

        $json_new_data = array();
        $json_new_data['rows'] = array();
        $form_data = stripslashes($form_data);
        $json_decode = json_decode(trim($form_data),true);
        $json_new_data['rows'][] = $json_decode;
        $json_encode = json_encode($json_new_data);
        $json_new_data = $json_encode;

        return $db->query("INSERT INTO `contact_form_7_forms_collected_data`(`form_id`,`form_data`) VALUES ('$form_id','$json_new_data')");
   }
}
