<?php
defined($security_key) or exit;

//------------------------------------------
// Products_configurations
//------------------------------------------

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

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

//NEW ARRAY
$criterias = [];   
$whereclause = '';
$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] == 'version_status'){
            $clause .= ' AND pv.status = :'.$v[0];
        }
        else {//create clause
            $clause .= ' AND pc.'.$v[0].' = :'.$v[0];
        }
    }
    if ($whereclause == '' && $clause !=''){
        $whereclause = 'WHERE '.substr($clause, 4);
    } else {
        $whereclause .= $clause;
    }
} 

//ENSURE PRODUCTROWID IS SEND
if (isset($criterias['productrowid']) && $criterias['productrowid'] != ''){

    //CHECK IF ALLOWED TO CRUD VERSIONS
    list($whereclause_alt,$condition_alt) = getWhereclause('',$permission,$partner,'get');

    $sql = "SELECT * FROM products WHERE rowID = ? '.$whereclause_alt.'";
    $stmt = $pdo->prepare($sql);

    $stmt->execute([$criterias['productrowid']]);
    $product_data = $stmt->fetch();
    $product_owner = ($product_data['rowID'])? 1 : 0;
   
    //IF PRODUCT IS OWNED THEN CRUD is ALLOWED
    if ($product_owner === 1 ){

        //Define Query
        if(isset($criterias['totals']) && $criterias['totals'] ==''){
        //Request for total rows
            $sql = 'SELECT count(*) as count FROM products_configurations pc '.$whereclause.'';
        } 
        elseif (isset($criterias['list']) && $criterias['list'] =='') {
            //SQL for Paging 
            $sql = 'SELECT * FROM products_configurations pc '.$whereclause.'';
        }
        else {
            //SQL for Paging include name from different tables
            $sql = 'SELECT pc.*, pv.config,pag.group_mandatory, pag.group_type,
                CASE WHEN p.rowID IS NOT NULL THEN p.productname 
                    WHEN pag.group_id IS NOT NULL THEN pag.group_name
                    END AS assignment_name,
                CASE WHEN p.rowID IS NOT NULL THEN "product" 
                WHEN pag.group_id IS NOT NULL THEN "group"
                    END AS type
                FROM products_configurations pc
                LEFT JOIN products p ON p.rowID = pc.assignment
                LEFT JOIN products_attributes_groups pag  ON pag.group_id = pc.assignment
                LEFT JOIN products_versions pv  ON pv.rowID = pc.version '.$whereclause;
        }

        $stmt = $pdo->prepare($sql);
     
        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']) && $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;
    }
}
?>