<?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('',$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] == 'rowid') {
            //build up search
            $clause .= ' AND ps.rowID = :'.$v[0]; 
        }
        elseif ($v[0] == 'search') {
            //build up search
            $clause .= ' AND p.productcode like :'.$v[0]; 
        }
        elseif ($v[0] == 'sn') {
            //build up search
            $clause .= ' AND e.serialnumber = :'.$v[0]; 
        }
        elseif ($v[0] == 'hw_version') {
            //build up search
            $clause .= ' AND ps.hw_version = :'.$v[0]; 
        }
        elseif ($v[0] == 'status') {
            //build up search
            $clause .= ' AND ps.status = :'.$v[0]; 
        }
        else {//create clause
            $clause .= ' AND '.$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_software '.$whereclause.'';
} 
elseif (isset($criterias['list']) && $criterias['list'] =='') {
//SQL for Paging 
$sql = 'SELECT p.productcode, ps.* FROM products p JOIN products_software ps ON p.rowID = ps.productrowid '.$whereclause.'';
}
elseif (isset($criterias['sn']) && $criterias['sn'] !='') {
    //SQL for PRODUCT SOFTWARE DOWNLOAD API 
    $sql = 'SELECT p.productcode, ps.* FROM products p JOIN equipment e ON e.productrowid = p.rowID JOIN products_software ps ON p.rowID = ps.productrowid '.$whereclause.'';
}
else {
//SQL for Paging 
$sql = 'SELECT p.productcode, ps.* FROM products p JOIN products_software ps ON p.rowID = ps.productrowid '.$whereclause.'';
}

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

//Bind to query
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);
            }
            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);
}

// IF PRODUCTCODE AND VERSION IS SEND ASSUME SOFTWARE REQUEST
if (!isset($criterias['productrowid']) && isset($criterias['sn']) && $criterias['sn'] != '' ){

    //default output
    $output = array(
        "productcode" => "",
        "version"=> "",
        "hw_version"=> "",
        "mandatory"=> "",
        "latest"=> "",
        "software"=> "",
        "source" => "",
        "source_type" => ""
    );

    //check if current version is send and update the equipment record
    if(isset($criterias['version']) && $criterias['version'] !=''){
        $sql = 'UPDATE equipment SET sw_version = ?, updatedby = ? WHERE serialnumber = ? ';
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$criterias['version'],$username,$criterias['sn']]);
    }

    //check if current version is send and update the equipment record
    if(isset($criterias['hw_version']) && $criterias['hw_version'] !=''){
        $sql = 'UPDATE equipment SET hw_version = ?, updatedby = ? WHERE serialnumber = ? ';
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$criterias['hw_version'],$username,$criterias['sn']]);
    }
    
    //GET PRODUCTCODE, SW_VERSION_UPGRADE, HW_VERSION from equipment SN
    $sql = 'SELECT p.productcode, e.sw_version_upgrade, e.hw_version FROM equipment e JOIN products p ON e.productrowid = p.rowID WHERE e.serialnumber = ?';
    $stmt = $pdo->prepare($sql);
    //Excute Query
    $stmt->execute([$criterias['sn']]);
    //Get results
    $productcodes = $stmt->fetchAll(PDO::FETCH_ASSOC);
    //assign serialnumber to productcode
    $criterias['productcode'] = $productcodes[0]['productcode']?? '';
    $sw_upgrade_version = $productcodes[0]['sw_version_upgrade'] ?? '';
    $hw_eq_version = $productcodes[0]['hw_version'] ?? '';
    
    //GET LATEST BASED ON PRODUCTCODE 
    if ($sw_upgrade_version > 0){
        //sw_version_upgrade set => change query
        $sql = 'SELECT * FROM products_software ps JOIN products p ON ps.productrowid = p.rowID WHERE ps.rowID = ? AND ps.status = "1"';
        $stmt = $pdo->prepare($sql);
        //Excute Query
        $stmt->execute([$sw_upgrade_version]);    
    } 
    else { 
        //GET THE LATEST
        if (!empty($hw_eq_version) || $hw_eq_version != ''){
            $sql = 'SELECT * FROM products_software ps JOIN products p ON ps.productrowid = p.rowID WHERE p.productcode = ? AND ps.hw_version = ? AND ps.status = "1" AND ps.latest = "1"';
            $stmt = $pdo->prepare($sql);
            //Excute Query
            $stmt->execute([$criterias['productcode'],$hw_eq_version]);
        } else {
            $sql = 'SELECT * FROM products_software ps JOIN products p ON ps.productrowid = p.rowID WHERE p.productcode = ? AND ps.status = "1" AND ps.latest = "1"';
            $stmt = $pdo->prepare($sql);
            //Excute Query
            $stmt->execute([$criterias['productcode']]);
        }
    }

    //Get results
    $messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
 
    foreach ($messages as $message){

        //CHECK IF FIRMWARE FILE IS AVAILABLE
        $software_file = dirname(__FILE__,4)."/firmware/".$message['software'];
        $file = glob($software_file, GLOB_BRACE);
        
        if (!empty($file)){   
            //GET FILE EXTENTION
            $ext = strtolower(pathinfo($file[0], PATHINFO_EXTENSION));
            if ($ext == 'hex'){
                //GET SOURCE CODE
                $file_contents = file_get_contents($software_file);
                //REMOVE RETURN \R
                $file_contents = str_replace("\r", '',$file_contents);
                $source_type = 'HEX';
                } 
                else {
                //PROVIDE URL TO FILE
                $file_contents = 'https://'.$_SERVER['SERVER_NAME'].'/firmware'.'/'.$message['software'];
                $source_type = 'url';
            }
        }

        // Default input product values
        $output = array(
            "productcode" => $message['productcode'],
            "version"=> $message['version'], 
            "hw_version"=> $message['hw_version'] ?? '',
            "mandatory"=> $message['mandatory'], 
            "latest"=> $message['latest'], 
            "software"=> $message['software'], 
            "source" => $file_contents ?? '',
            "source_type" => $source_type ?? ''
        );
        
    }
      
    $messages = $output;
}

//Encrypt results
$messages = generate_payload($messages);

//Send results
echo $messages;

?>