<?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
list($whereclause,$condition) = getWhereclause('equipment',$permission,$partner,'get');

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

//------------------------------------------
// MAINTENANCE QUERIES
//------------------------------------------

//Update sw_version_latest
$sw_version_latest_update = 0;
//------------------------------------------
//------------------------------------------
//------------------------------------------

//------------------------------------------
//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] =='products' || $v[0] =='list' || $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') {
            
             //PARTNER INFORMATION
            $api_url = '/v2/partners/partnerID='.$v[1] ;
            $partner_return = ioApi($api_url,'',$clientsecret);
            $partner_return  = json_decode($partner_return ,true);
            $partner_return = $partner_return[0];
            
            if ($partner_return){
                //PARTNER FOUND
                
                switch ($partner_return['partnertype']) {
                    case 'SalesID':
                        $clause .= ' AND e.accounthierarchy like "%_salesid_:_'.$v[1].'-%"';                
                        break;
                    case 'SoldTo':
                        $clause .= ' AND e.accounthierarchy like "%_soldto_:_'.$v[1].'-%"'; 
                        break;
                    case 'ShipTo':
                        $clause .= ' AND e.accounthierarchy like "%_shipto_:_'.$v[1].'-%"'; 
                        break;
                    case 'Location':
                        $clause .= ' AND e.accounthierarchy like "%_location_:_'.$v[1].'-%"'; 
                        break;
                }

            } else {
                //Partner not found        
                //Partner not found return empty
                $clause .= ' AND e.accounthierarchy =""'; 
            }
            //remove original key/value from array      
            unset($criterias[$v[0]]); 
        }
        elseif ($v[0] == 'serialnumber') {
            //build up serialnumber
            //check if multiple serialnumbers 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 e.serialnumber IN ('.$new_querystring.')'; 
                //remove original key/value from array
                unset($criterias[$v[0]]);
            } 
            else {
                $clause .= ' AND e.serialnumber IN (:'.$v[0].')'; 
            }
        }
        elseif ($v[0] == 'firmware') {
                //Assets with firmaware upgrade = 0 (1=latest version, 2=No software)
                $clause .= ' AND e.status != 5 AND e.sw_version_latest = 0';     
                
                //UPDATE VERSION STATUS
                $sw_version_latest_update = 1;
        }
        else {//create clause
        $clause .= ' AND '.$v[0].' = :'.$v[0];
        }
    }
    if ($whereclause == '' && $clause !=''){
        $whereclause = 'WHERE '.substr($clause, 4);
    } else {
        $whereclause .= $clause;
    }
} 

if ($sw_version_latest_update == 1){
    //------------------------------------------
    //UPDATE SW_STATUS 
    //------------------------------------------
    //UPDATE ASSETS-> SW_LATEST_VERSION WITH NO PRODUCT_SOFTWARE TO 2
    $sql = 'UPDATE equipment e LEFT JOIN products_software ps ON e.productrowid = ps.productrowid SET e.sw_version_latest = 2 WHERE ps.rowID IS NULL';
    $stmt = $pdo->prepare($sql);
    $stmt->execute();

    //UPDATE ASSETS-> SW_LATEST_VERSION WITH PRODUCT_SOFTWARE FROM 2 TO 0
    $sql = 'UPDATE equipment e LEFT JOIN products_software ps ON e.productrowid = ps.productrowid SET e.sw_version_latest = 0 WHERE ps.rowID IS NOT NULL AND sw_version_latest = 2';
    $stmt = $pdo->prepare($sql);
    $stmt->execute();

    //UPDATE LATEST TO NO IN CASE HW_VERSION ARE EQUAL AND SW_VERSIONS NOT AND NOT LATEST
    $sql = 'UPDATE equipment e JOIN products_software ps ON e.productrowid = ps.productrowid SET e.sw_version_latest = 0 WHERE ps.latest = 1 AND lower(e.sw_version) <> lower(ps.version) AND lower(e.hw_version) = lower(ps.hw_version) AND e.sw_version_latest = 1';
    $stmt = $pdo->prepare($sql);
    $stmt->execute();

    //UPDATE LATEST TO YES IN CASE HW_VERSION ARE EQUAL AND SW_VERSIONS ARE EQUAL
    $sql = 'UPDATE equipment e JOIN products_software ps ON e.productrowid = ps.productrowid SET e.sw_version_latest = 1 WHERE ps.latest = 1 AND lower(e.sw_version) = lower(ps.version) AND lower(e.hw_version) = lower(ps.hw_version) AND e.sw_version_latest = 0';
    $stmt = $pdo->prepare($sql);
    $stmt->execute();
    //------------------------------------------
    //------------------------------------------
}

if (isset($criterias['download']) && $criterias['download'] ==''){
//Request for download
$sql = 'SELECT e.rowID as equipmentID, e.*, 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['list']) && $criterias['list'] =='') {
    //SQL for Paging 
    $sql = 'SELECT e.rowID, e.serialnumber FROM equipment e '.$whereclause.'';
}
elseif (isset($criterias['products']) && $criterias['products'] ==''){
    //Request for all products in equipment view
    $sql = 'SELECT distinct(p.productcode), p.productname from equipment e LEFT JOIN products p ON e.productrowid = p.rowID '.$whereclause.'  ORDER BY p.productcode';
} 
elseif (isset($criterias['totals']) && $criterias['totals'] =='' && isset($criterias['type'])){
    //Request for total rows for history reports
        $sql ='SELECT count(*) as count FROM equipment_history h LEFT JOIN equipment e ON h.equipmentid = e.rowID '.$whereclause.'';
} 
elseif (isset($criterias['history']) && $criterias['history'] != ''){

    //History INDICATOR
    /*
    0 Show All
    1 Created DESC, LIMIT 5
    */

    switch ($criterias['history']) {
        case 1:
            $sort = ' ORDER BY h.created DESC LIMIT 0,'.$page_rows_equipment_servicereporst;
            break;
        
        default:
            $current_page = isset($criterias['p']) && is_numeric($criterias['p']) ? (int)$criterias['p'] : 1;
            $start_page = ($current_page - 1) * $page_rows_history;
            $sort = ' ORDER BY h.created DESC LIMIT '.$start_page.','.$page_rows_history;
            break;
    }
    //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 equipment_history h LEFT JOIN equipment e ON h.equipmentid = e.rowID '.$whereclause.$sort; 
} 
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
    9 Latest ASC
    10 Latest 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;
    case 9:
        $sort = ' e.created DESC ';
        break;
    case 10:
        $sort = ' e.created ASC ';
        break;
    default:
        $sort = ' equipmentID ';
        break;
   }
  
    //SQL for Paging 
    $sql = 'SELECT e.rowID as equipmentID, e.*, p.productcode, p.productname, p.product_media 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);
            }
        }
    }
}

//------------------------------------------
// Debuglog
//------------------------------------------
if (debug){
    $message = $date.';'.$sql.';'.$username;
    debuglog($message);
}
//------------------------------------------
//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['list']) && $criterias['list']=='') || (isset($criterias['products']) && $criterias['products'] =='') || (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);
}
//------------------------------------------
//JSON_EnCODE
//------------------------------------------
$messages = json_encode($messages, JSON_UNESCAPED_UNICODE);
//------------------------------------------
//Send results
//------------------------------------------
echo $messages; 

?>