<?php
//defined($security_key) or exit;
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'));
//------------------------------------------
// Application related calls
//------------------------------------------
$action = $request[2];

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

function checkSerial($serialinput){

//Check Serialnumber used
if (preg_match('/^[^-]*-[^-]*$/', $serialinput)){
    $check=explode('-', $serialinput);
    $productrowid = strip_tags(trim($check[0]));
    $rowID= strip_tags(trim($check[1]));
    $whereclause = 'WHERE rowID = "'.$rowID.'"';
    }
    else
    {
    $serialnumberhelper = strip_tags(trim($serialinput));
    $whereclause = 'WHERE serialnumber = "'.$serialnumberhelper.'"';
    }

    return $whereclause;
}

//////// - ACTIONS - API - //////////////////
switch ($action){

case 'validateSerial':

    if (isset($_GET['sn']) && $_GET['sn'] != ''){
    //Get Productcode
    $idcheck = "-";
    $whereclause = checkSerial($_GET['sn']);

    $sql = "SELECT count(rowID) as rowID from equipment $whereclause";
    $stmt = $pdo->prepare($sql);
    $stmt->execute();
    //Get results
    $messages = $stmt->fetch();

    if ($messages[0] == 1) {
        echo json_encode(array('SN'=> TRUE));
    }
    else {
        echo json_encode(array('SN'=> FALSE));
    }
    }  
    elseif (isset($_GET['esm']) && $_GET['esm'] != '') {
        //FILTER ESM Number
        $filter1 = 'ESM":"'.$_GET['esm'].'","SN":';
        
        //BUILD SQL
        $whereclause = "WHERE description like '%$filter1%'";
        $sql = "SELECT rowID FROM equipment_history $whereclause";
        $stmt = $pdo->prepare($sql);
        $stmt->execute();
        //Get results
        $messages = $stmt->fetch();
        if ($messages[0] > 0) {
            echo json_encode(array('ESM'=> TRUE));
        }
        else {
            echo json_encode(array('ESM'=> FALSE));
        }
    }
    else {
            http_response_code(400);
    }

break;

case 'getProducts':

    $sql = "SELECT * FROM products";
    $stmt = $pdo->prepare($sql);
    $stmt->execute();
    //Get results
    $messages = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode($messages);
        
break;

case 'getEquipmentHistory':

// +++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Return all when nothing specified +++++++++++++++++++++
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++
$whereclause = '';
$sn_found = 0;

    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    // Check SN 			 +++++++++++++++++++++++++++++++++
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    if (isset($_GET['sn']) && $_GET['sn'] != '')	{
        //Get Productcode
        $sn = strip_tags(trim($_GET['sn']));
        $sn_found = 1; //indicates SN is found

        $whereclause = 'WHERE h.description like "%historycreated%SN%:%'.$sn.'%" and h.type !="SRIncluded"';
        }

        // +++++++++++++++++++++++++++++++++++++++++++++++++++++++
        // Check Filter 		  		++++++++++++++++++++++++++
        // +++++++++++++++++++++++++++++++++++++++++++++++++++++++

        //Type Filter
        if (isset($_GET['type']) && $_GET['type'] != ''){

        switch ($_GET['type']) {
            case 'latest':
                if ($sn_found == 1){
                    $whereclause .= ' AND h.rowID in (Select MAX(h.rowID) AS row_ID FROM equipment_history h GROUP BY h.equipmentid)';
                    }
                    else
                    {
                        $whereclause = "WHERE h.rowID in (Select MAX(h.rowID) AS row_ID FROM equipment_history h WHERE h.description like '%historycreated%' GROUP BY h.equipmentid)";
                    }
            break;

            default:
                $filtertype = strip_tags(trim($_GET['type']));
                $whereclause .= ' AND type="'.$filtertype.'"';
            break;
            }
        }

        if ($whereclause == ''){
            $whereclause = "WHERE h.description like '%historycreated%'";
        }

        //Start DATE Filter
        if ((isset($_GET['start']) && $_GET['start'] != '') && (isset($_GET['end']) && $_GET['end'] != '')){
            $start_range = strip_tags(trim($_GET['start']));
            $end_range = strip_tags(trim($_GET['end']));
        }
        else {
            $end_range = date("Y-m-d", strtotime("+ 1 days")); //default data range
            $start_range = date("Y-m-d", strtotime("-270 days")); //default data range
        }

        $whereclause .=  " AND h.created BETWEEN '$start_range' and '$end_range'";
        //END DATE Filter

// +++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Execute query & return+++++++++++++++++++++++++++++++++
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++
$pdo = dbConnect($dbname);

$sql = "SELECT h.rowID, h.description FROM equipment_history h $whereclause";
$stmt = $pdo->prepare($sql);
$stmt->execute();
//Get results
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
$number = count($messages);
$i = 1;

echo '[';
foreach ($messages as $message){
    $add_object = json_decode($message['description']);
    $add_object->historyID = $message['rowID'];
    
    if ($i < $number){
        echo json_encode($add_object);
        echo ','; 
    } else {
        echo json_encode($add_object);
    }
    $i++;
}
echo ']';
    
break;

case 'serviceInit':
    include './settings/systemservicetool_init.php';  
    echo json_encode($init);							
break;

case 'getQuestions':

    //build allowed_response
    if (isset($_GET['type']) && $_GET['type'] != ''){
    
    include './settings/systemservicetool.php';

    //build questions
    switch ($_GET['type']) {
        case 'visual':
        $arrayQuestions = $arrayQuestions_visual;
            break;

        case 'final':
        $arrayQuestions = $arrayQuestions_finalize;
            break;

        case 'cartest':
            include './settings/systemcartest.php';
            $arrayQuestions = $arrayQuestions_cartest;
                break;
        }
    //Return JSON
    echo json_encode($arrayQuestions);
}
else {
        http_response_code(400);
}
break;

case 'firmwareUpdate':

    if (isset($_GET['sn']) && $_GET['sn'] != '' && isset($_GET['hw_version']) && $_GET['hw_version'] != '' && isset($_GET['sw_version']) && $_GET['sw_version'] != '')	{
        
        include './settings/settings_redirector.php';

        //Clean input data
        $hw_device_send = strip_tags(trim($_GET['hw_version']));
        $sw_device_send = strip_tags(trim($_GET['sw_version']));
     
        //Check exceptions
        if (in_array($_GET['sn'],$serialnumber_exceptions)){
            //Serialnumber found in exceptions include exception file
            include './settings/systemfirmware_exceptions.php';
        } 
        else
        {
            //Serialnumber not found in exceptions include standard firmware
            include './settings/systemfirmware.php';
        }
        //Include Firmware
        if (isset(${'Firmwarename' . $hw_device_send}) && isset(${'Firmware' . $hw_device_send})){
            $firmwarename = ${'Firmwarename' . $hw_device_send};
            $firmware = ${'Firmware' . $hw_device_send};
            echo json_encode(array("hw_version"=> $hw_device_send, "HEX_FW"=> $firmwarename, "Firmware" => $firmware));
        }
        else 
        {
            http_response_code(404);
        }
}
else {
        http_response_code(400);
}

break;

case 'validateSoftware':

    if (isset($_GET['version']) && $_GET['version'] != '')	{

        //Clean input data
        $version = strip_tags(trim($_GET['version']));
        
        //Include Firmware
        include './settings/systemfirmware.php';

        if ($service_tool_version == $version){

            //Version equal No Update = 0
            echo json_encode(array("update"=> 0));
        }
        else {
            //Version not equal Update = 1
            echo json_encode(array("update"=> 1));
        }
        
    }
    else {
            http_response_code(400);
    }
break;

case 'getSoftware':
    include './settings/systemservicetool.php';
    echo json_encode(array("url"=> $software_url));
break;

case 'getfirmwareCommunication':
    if (isset($_GET['hw_version']) && $_GET['hw_version'] != ''){
        
        $target = $_GET['target'] ?? '0';
        $hw_device_send = strip_tags(trim($_GET['hw_version']));

        $filter1 = 'soldto":"';
        $filter2 = '","shipto';
        $filter3 = 'shipto":"';
        $filter4 = '","location';

        $whereclause = "WHERE e.hw_version='$hw_device_send' AND c.type_1='1' AND c.status='1'";

        //get target
        switch ($target) {
            case '0': // Both
                $onclause ="SUBSTRING_INDEX(SUBSTRING_INDEX(e.accounthierarchy, '$filter1', -1),'$filter2',1) = c.partnerID or SUBSTRING_INDEX(SUBSTRING_INDEX(e.accounthierarchy, '$filter3', -1),'$filter4',1) = c.partnerID";
                break;
            
            case '1': // SoldTO only
                $onclause ="SUBSTRING_INDEX(SUBSTRING_INDEX(e.accounthierarchy, '$filter1', -1),'$filter2',1) = c.partnerID";
                break;
            
            case '2': // ShipTO only
                $onclause =" SUBSTRING_INDEX(SUBSTRING_INDEX(e.accounthierarchy, '$filter3', -1),'$filter4',1) = c.partnerID";
                break;
        }

        $pdo = dbConnect($dbname);
        $sql = "SELECT e.sw_version, c.email from equipment e join communication c on $onclause $whereclause group by c.email";
        $stmt = $pdo->prepare($sql);
        $stmt->execute();
        //Get results
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

        if ($result) {
            echo json_encode(array("firmware_scope"=> count($result)));
        } 
        else {
            echo json_encode(array("firmware_scope"=> '0'));
        }
        
    }
    else {
            http_response_code(400);
    }

    break;

case 'getCartest':

    //FILTER FOR GROUPBY FILTERS on CAR
    $filter1 = '"CarBrand": "';
    $filter2 = '"CarType": "';
    $filter3 = '"CarVIN": "';

    //CONNECT TO DB
    $pdo = dbConnect($dbname);
    $sql = "SELECT * FROM equipment_history where type='cartest' group by SUBSTRING_INDEX(SUBSTRING_INDEX(description, '$filter1', -1),'$filter2',1), SUBSTRING_INDEX(SUBSTRING_INDEX(description, '$filter2', -1),'$filter3',1) ORDER BY description ASC";
    $stmt = $pdo->prepare($sql);
    $stmt->execute();
    //Get results
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode($result,JSON_UNESCAPED_UNICODE);
break;

} 
// end switch
