<?php
defined($security_key) or exit;

//------------------------------------------
// Products
//------------------------------------------

//Connect to DB
$pdo = dbConnect($dbname);

//SoldTo is empty
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}

//default whereclause
$whereclause = '';

list($whereclause,$condition) = getWhereclause('products',$permission,$partner,'get');

//NEW ARRAY
$criterias = [];   
$clause = '';

//Check for $_GET variables and build up clause
if(isset($get_content) && $get_content!=''){    
    //GET VARIABLES FROM URL
    $requests = explode("&", $get_content);     
    //Check for keys and values
    foreach ($requests as $y){
        $v = explode("=", $y);
        //INCLUDE VARIABLES IN ARRAY
        $criterias[$v[0]] = $v[1]; 
    
        if ($v[0] == 'page' || $v[0] =='p' || $v[0] =='totals' || $v[0] =='list' || $v[0] =='history'|| $v[0] =='success_msg'){
        //do nothing
        } 
        elseif ($v[0] == 'search') {
        //build up search
        $clause .= ' AND p.productcode like :'.$v[0]; 
        }
        elseif ($v[0] == 'product_id') {
            //build up product_id = rowID
            //check if multiple product_ids are provided
            if (str_contains($v[1], ',')){
                $inputs = explode(",",$v[1]);
                $new_querystring = ''; //empty querystring
                $x=0;
                foreach($inputs as $input){
                    //create key
                    $new_key = $v[0].'_'.$x;
                    //inject new key/value to array
                    $criterias[$new_key] = $input;
                    $new_querystring .= ':'.$new_key.','; 
                    $x++;
                }
                //remove obsolete last character from new_querystring
                $new_querystring = substr($new_querystring,0, -1);
                //add new_querystring to clause
                $clause .= ' AND p.rowID IN ('.$new_querystring.')'; 
                //remove original key/value from array
                unset($criterias[$v[0]]);
            } 
            else {
                $clause .= ' AND (p.rowID IN (:'.$v[0].') or p.url_slug =:'.$v[0].')'; 
            }
        }
        else {//create clause
        $clause .= ' AND p.'.$v[0].' = :'.$v[0];
        }
    }
    if ($whereclause == '' && $clause !=''){
        $whereclause = 'WHERE '.substr($clause, 4);
    } else {
        $whereclause .= $clause;
    }
} 
//Define Query
if(isset($criterias['totals']) && $criterias['totals'] ==''){
//Request for total rows
    $sql = 'SELECT count(*) as count FROM products p '.$whereclause.'';
} 
elseif (isset($criterias['list']) && $criterias['list'] =='') {
    //SQL for Paging 
    $sql = 'SELECT * FROM products p '.$whereclause.'';
} 
elseif (isset($criterias['list']) && $criterias['list'] =='price'){

    //SET SPECIFIC WHERECLAUSE
    if ($whereclause == ''){
        $whereclause_1 = 'WHERE p.salesflag = 1';
        $whereclause_2 = 'WHERE pat.item_status = 1';
    } else {
        $whereclause_1 = $whereclause .' AND p.salesflag = 1 AND p.status = 1 ';

        list($whereclause_alt,$condition_alt) = getWhereclause('products_attributes_items',$permission,$partner,'get');
        $whereclause_2 = $whereclause_alt .' AND pat.item_status = 1';
    }

    //GET ALL PRODUCTS AND PRODUCT ATTRIBUTES FOR PRICING
    $sql = '(SELECT p.rowID as product_id, p.productname as product_name FROM products p '.$whereclause_1.' ) UNION (SELECT pat.attribute_id as product_id, pat.item_name as product_name FROM products_attributes_items pat '.$whereclause_2.' )';
}
elseif (isset($criterias['list']) && $criterias['list'] =='config'){
    
    //SET SPECIFIC WHERECLAUSE
    if ($whereclause == ''){
        $whereclause_1 = 'WHERE p.salesflag = 1 AND p.status = 1 AND p.configurable = 0 ';
        $whereclause_2 = 'WHERE pag.group_status = 1';
    } else {
        $whereclause_1 = $whereclause .' AND p.salesflag = 1 AND p.status = 1 AND p.configurable = 0 ';

        list($whereclause_alt2,$condition_alt2) = getWhereclause('products_attributes_groups',$permission,$partner,'get');

        $whereclause_2 = $whereclause_alt2 .' AND pag.group_status = 1';
    }
    
    //GET ALL PRODUCTS AND PRODUCT ATTRIBUTES FOR PRICING
    $sql = '(SELECT p.rowID as product_id, p.productname as product_name FROM products p '.$whereclause_1.' ) UNION (SELECT pag.group_id as product_id, CONCAT(pag.group_name, " (", pag.group_name_internal,")") as product_name FROM products_attributes_groups pag '.$whereclause_2.' )';
}
else {
    //SQL for Paging 
    $sql = 'SELECT p.*, m.full_path FROM products p LEFT JOIN media m ON p.product_media = m.rowID '.$whereclause.' LIMIT :page,:num_products';
}

$stmt = $pdo->prepare($sql);

//Bind to query
if (str_contains($whereclause, ':condition')){
    $stmt->bindValue('condition', $condition, PDO::PARAM_STR);
}
if (str_contains($whereclause_alt, ':condition')){
    $stmt->bindValue('condition', $condition_alt, PDO::PARAM_STR);
}
if (str_contains($whereclause_alt2, ':condition')){
    $stmt->bindValue('condition', $condition_alt2, PDO::PARAM_STR);
}

if (!empty($criterias)){
    foreach ($criterias as $key => $value){
        $key_condition = ':'.$key;
        if (str_contains($whereclause, $key_condition)){
            if ($key == 'search'){
                $search_value = '%'.$value.'%';
                $stmt->bindValue($key, $search_value, PDO::PARAM_STR);
            }
            else {
                $stmt->bindValue($key, $value, PDO::PARAM_STR);
            }
        }
    }
}

//Add paging details
if(isset($criterias['totals']) && $criterias['totals']==''){
    $stmt->execute();
    $messages = $stmt->fetch();
    $messages = $messages[0];
}
elseif(isset($criterias['list'])){
    //Excute Query
    $stmt->execute();
    //Get results
    $messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
else {
    $current_page = isset($criterias['p']) && is_numeric($criterias['p']) ? (int)$criterias['p'] : 1;
    $stmt->bindValue('page', ($current_page - 1) * $page_rows_products, PDO::PARAM_INT);
    $stmt->bindValue('num_products', $page_rows_products, PDO::PARAM_INT);

    //Excute Query
    $stmt->execute();
    //Get results
    $messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

//------------------------------------------
//JSON_ENCODE
//------------------------------------------
$messages = json_encode($messages, JSON_UNESCAPED_UNICODE);

//Send results
echo $messages;

?>