<?php
defined($security_key) or exit;

//------------------------------------------
// Equipments
//------------------------------------------

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

//Get user_rights from users.php
$partner = json_decode($partnerhierarchy);  


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

//default whereclause
$whereclause = '';

switch ($permission) {    
    case '4': 
        $whereclause = '';
        break;
    case '3':
        $whereclause = '';
        break;
    case '2':
        $condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search;
        $whereclause = 'WHERE e.accounthierarchy like :condition ';
        break;
    default:
        $condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search.'___shipto___'.substr($partner->shipto, 0, strpos($partner->shipto, "-")).'%___location___'.substr($partner->location, 0, strpos($partner->location, "-")).'%';
        $whereclause = 'WHERE e.accounthierarchy like :condition ';
        break;
} 
//------------------------------------------
//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] =='history' || $v[0] =='success_msg' || $v[0] =='download' || $v[0] =='sort'){
        //do nothing
        } 
        elseif ($v[0] == 'equipmentid') {
        //build up search
        $clause .= ' AND e.rowID = :'.$v[0]; 
        }
        elseif ($v[0] == 'servicedate') {
        //build up service coverage
        $clause .= ' AND e.service_date <= :'.$v[0]; 
        }
        elseif ($v[0] == 'warrantydate') {
        //build up warranty coverage
        $clause .= ' AND e.warranty_date >= :'.$v[0]; 
        }
        elseif ($v[0] == 'historyid') {
        //build up history ID
        $clause .= ' AND h.rowID = :'.$v[0]; 
        }
        elseif ($v[0] == 'type') {
            //build up history ID
            $clause .= ' AND h.type = :'.$v[0]; 
        }
        elseif ($v[0] == 'h_equipmentid') {
            //build up search
            $clause .= ' AND h.equipmentid = :'.$v[0]; 
        }
        elseif ($v[0] == 'status') {
        //Update status based on status
        $clause .= ' AND e.'.$v[0].' = :'.$v[0];
        $status = $v[1];
        }
        elseif ($v[0] == 'search') {
        //build up search
        $clause .= ' AND (serialnumber like :'.$v[0].' OR e.rowID like :'.$v[0].')'; 
        }
        elseif ($v[0] == 'partnerid') {
        //build up accounthierarchy
        $clause .= ' AND e.accounthierarchy like :'.$v[0]; 
        }
        elseif ($v[0] == 'firmware') {
            //Include systemfirwmare
            include './settings/systemfirmware.php';
            //build up search
            $clause .= ' AND e.status != 5 AND e.sw_version not like "'.substr($FirmwarenameR06, 0, -4).'%"';
        }
        else {//create clause
        $clause .= ' AND '.$v[0].' = :'.$v[0];
        }
    }
    if ($whereclause == '' && $clause !=''){
        $whereclause = 'WHERE '.substr($clause, 4);
    } else {
        $whereclause .= $clause;
    }
} 
if (isset($criterias['download']) && $criterias['download'] ==''){
//Request for download
$sql = 'SELECT e.rowID as equipmentID, e.productrowid, e.serialnumber, e.status, e.created, e.hw_version, e.sw_version, e.accounthierarchy, e.service_date, e.warranty_date, p.productcode, p.productname from equipment e LEFT JOIN products p ON e.productrowid = p.rowID '.$whereclause.'  ORDER BY equipmentID';
}
elseif (isset($criterias['totals']) && $criterias['totals'] =='' && !isset($criterias['type'])){
//Request for total rows
    $sql = 'SELECT count(*) as count from equipment e LEFT JOIN products p ON e.productrowid = p.rowID '.$whereclause.'';
} 
elseif (isset($criterias['totals']) && $criterias['totals'] =='' && isset($criterias['type'])){
    //Request for total rows for history reports
        $sql ='SELECT count(*) as count from history h LEFT JOIN equipment e ON h.equipmentid = e.rowID '.$whereclause.'';
} 
elseif (isset($criterias['history']) && $criterias['history'] ==''){
    //request history
    $sql ='SELECT h.rowID as historyID, e.rowID as equipmentID, h.equipmentid as h_equipmentid, e.serialnumber, h.type, h.description, h.created, h.createdby from history h LEFT JOIN equipment e ON h.equipmentid = e.rowID '.$whereclause.'';
} 
else {
   // GET SORT INDICATOR
   $sort_indicator = $criterias['sort'] ?? ''; 

    /*
    1 Serialnumber ASC
    2 Serialnumber DESC
    3 Status ASC
    4 Status DESC
    5 Warranty ASC
    6 Warranty DESC
    7 Service ASC
    8 Service DESC
    */
   
   switch ($sort_indicator){
    case 1:
        $sort = ' e.serialnumber ASC ';
        break;
    case 2:
        $sort = ' e.serialnumber DESC ';
        break;
    case 3:
        $sort = ' e.status ASC ';
        break;
    case 4:
        $sort = ' e.status DESC ';
        break;
    case 5:
        $sort = ' e.warranty_date ASC ';
        break;
    case 6:
        $sort = ' e.warranty_date DESC ';
        break;
    case 7:
        $sort = ' e.service_date ASC ';
        break;
    case 8:
        $sort = ' e.service_date DESC ';
        break;
    default:
        $sort = ' equipmentID ';
        break;
   }
  
    //SQL for Paging 
    $sql = 'SELECT e.rowID as equipmentID, e.productrowid, e.serialnumber, e.status, e.created, e.createdby, e.hw_version, e.sw_version, e.accounthierarchy, e.service_date, e.warranty_date, e.order_ref, p.productcode, p.productname from equipment e LEFT JOIN products p ON e.productrowid = p.rowID '.$whereclause.' ORDER BY '.$sort.' LIMIT :page,:num_products';
}

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

//------------------------------------------
//Bind to query
//------------------------------------------
if (str_contains($whereclause, ':status')){
    $stmt->bindValue('status', $status, PDO::PARAM_INT);
}
if (str_contains($whereclause, ':condition')){
    $stmt->bindValue('condition', $condition, 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);
            }
            elseif ($key == 'partnerid'){
                $search_value = '%"_"'.$value.'-%';
                $stmt->bindValue($key, $search_value, PDO::PARAM_STR);
            }
            elseif ($key == 'p'){
                //Do nothing (bug)
            }
            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['history']) && $criterias['history'] =='') || (isset($criterias['download']) && $criterias['download'] =='')){
     //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_equipment, PDO::PARAM_INT);
    $stmt->bindValue('num_products', $page_rows_equipment, PDO::PARAM_INT);
    //Excute Query
    $stmt->execute();
    //Get results
    $messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
//------------------------------------------
//Encrypt results
//------------------------------------------
$messages = generate_payload($messages);
//------------------------------------------
//Send results
//------------------------------------------
echo $messages; 

?>