<?php
//defined($security_key) or exit;
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'));

//------------------------------------------
// Application related calls
//------------------------------------------
$action = $request[2];
$post_content = json_decode($input,true);

//SET PARAMETERS FOR QUERY
$id = $post_content['rowID'] ?? ''; //check for rowID
$command = ($id == '')? 'insert' : 'update';  //IF rowID = empty then INSERT
$date = date('Y-m-d H:i:s');

// 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;
}

if ($action == 'createHistory'){

if (!empty($post_content['sn']) && !empty($post_content['testdetails'])) {

    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    // Action defaults (0=No 1=Yes)          +++++++++++++++++
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++  
    $equipmentUpdate = 0; //equipment update
    $servicetoolHistoryUpdate = 0; // service tool history update
    $equipmentCreate = 0; //Create equipment when serialnumber not Found
    $equipmentProductUpdate = 0; //update equipment with productcode
    $equipmentUpdate_status = 0; //update equipment with status
    $equipmentServiceDate = 0; //update equipment with service date
    $historyUpdate_type = 0; //update type of history
    $updateObject_visual = 0; //update visual inspection object
    $sendServiceReport = 0; //send service report via email
    $transfercartest = 0; //Update cartest table with incoming data
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    //SET DEFAULT PARAMETERS
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    $user = $username;
    $account = $partnerhierarchy; //string
    $current_date = date("Y-m-d");
    $input_type = $post_content['type'];
    $testdetails = json_encode($post_content['testdetails']);
    $serial = $post_content['sn'];
    //$productrowid = (isset($post_content['testdetails']['logdetails']['PN']) && (!empty($post_content['testdetails']['logdetails']['PN']) || $post_content['testdetails']['logdetails']['PN'] != ''))? $post_content['testdetails']['logdetails']['PN'] : 0; //default product for equipment create
    $sn_service = $post_content['testdetails']['external_device_sn'] ?? '';

    //GET PRODUCT ROWID FOR EQUIPMENT CREATE
    if (isset($post_content['testdetails']['logdetails']['PN']) && (!empty($post_content['testdetails']['logdetails']['PN']) || $post_content['testdetails']['logdetails']['PN'] != '')){
        $pn2 = preg_replace("/[^0-9]/","",$post_content['testdetails']['logdetails']['PN']);
        $productrowid = ltrim($pn2, "0");
    } else {
        $productrowid = 0; //default product for equipment create
    }
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    // Define action based on historytype
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    switch ($input_type){
        case 1: //Bootloader
            $historytype = ${'HistoryType_'.$input_type};
            $equipmentCreate = 1;
            $equipmentUpdate = 1;
            $equipmentServiceDate = 1;
        break;

        case 2: //Firmware
            $historytype = ${'HistoryType_'.$input_type};
            $equipmentCreate = 1;
            $equipmentUpdate = 1;
            $servicetoolHistoryUpdate = 0;
        break;

        case 3: //Serialnumber
            $historytype = ${'HistoryType_'.$input_type};
            $equipmentProductUpdate = 1;
            $equipmentUpdate_status = 1;
            $equipmentServiceDate = 1;
        break;

        case 4://Visual
            $historytype = ${'HistoryType_'.$input_type};
        break;

        case 5://Maintenance_Test
            $historytype = ${'HistoryType_'.$input_type};
            $equipmentUpdate = 0;
            $servicetoolHistoryUpdate = 0;
        break;

        case 6://Assembly_Test
            $historytype = ${'HistoryType_'.$input_type};
            $equipmentUpdate = 0;
            $equipmentUpdate_status = 1;
        break;

        case 7://ProductNumber
            $historytype = ${'HistoryType_'.$input_type};
            $equipmentProductUpdate = 1;
            $equipmentUpdate_status = 1;
        break;

        case 8://Visual
            $historytype = ${'HistoryType_'.$input_type};

            //Check for existing visualinspectionID
            if (isset($post_content['testdetails']['serviceReport']['visualinspection_id']) && $post_content['testdetails']['serviceReport']['visualinspection_id'] != 0) {
                $updateObject_visual = 1;
                $visualinspectionID = $post_content['testdetails']['serviceReport']['visualinspection_id'];
            }

        break;

        case 9://ServiceReport
            $historytype = ${'HistoryType_'.$input_type};
            $historyUpdate_type = 1;
            $servicetoolHistoryUpdate = 1;
            $equipmentServiceDate = 1;
            
            //Check if servicereport comes from ServiceTool else inhouse
            if (isset($post_content['testdetails']['serviceReport'])) {
                $sendServiceReport = 1;
                $testObject = array(
                    "final" => $post_content['testdetails']['serviceReport']['questionItems'],
                    "maintenance_test" => $post_content['testdetails']['serviceReport']['maintenance_id'],
                    "visualinspection" => $post_content['testdetails']['serviceReport']['visualinspection_id'],
                    "serialnumber" => $post_content['sn'],
                    "external_device_sn" => $post_content['testdetails']['external_device_sn']
                );
                $testdetails = json_encode($testObject);
            }
   
            break;
        case 11: //car_test
            $historytype = 'CarTest';
            $equipmentCreate = 1;
            $transfercartest = 1;
        break;

        case 'firmware': //update from Portal
            $historytype = $HistoryType_2;
            $equipmentUpdate = 1;
            $servicetoolHistoryUpdate = 1;
            $sn_service = $post_content['sn_service'];
        break;

        default:
            $historytype = 'Other';
        break;
    } 
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    //Connect to DB
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++

    $pdo = dbConnect($dbname);
    //Get whereclause based on serialnumber
    $whereclause = checkSerial($serial); 

    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    //CHECK if EQUIPMENT EXISTS
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    $sql = "SELECT count(rowID) as total, rowID FROM equipment $whereclause";
    $stmt = $pdo->prepare($sql);
    $stmt->execute();
    $total = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $total_equipment = $total[0]['total'];
    $rowID = $total[0]['rowID'] ?? '';
  
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    // Create equipment when not exist	 +++++++++++++++++++++++++
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    if ($equipmentCreate == 1 && $total_equipment == 0){
        $sql = 'INSERT INTO equipment (productrowid,created,createdby,status,accounthierarchy,serialnumber,service_date,warranty_date) VALUES (?,?,?,?,?,?,?,?)';
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$productrowid,$date,$user,$status0,$account,$serial,$current_date,$current_date]);
        $rowID = $pdo->lastInsertId();
    }
  
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    // Insert or UPDATE equipment_history item  ++++++++++++++++++++++++
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    if ($updateObject_visual == 1){
        $sql = "UPDATE equipment_history SET description = '$testdetails', updatedby = ? WHERE rowID = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$user,$visualinspectionID]);
        $last_id = $visualinspectionID;
    }
    else {
    // Insert Equipment
        $sql = "INSERT INTO equipment_history (equipmentid,type,description,createdby,updatedby) VALUES (?,?,?,?,?)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$rowID,$historytype,$testdetails,$user,$user]);
        $last_id = $pdo->lastInsertId();
    }
            
    // Return ID            
    echo json_encode(array('historyID'=> $last_id));
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    // Specials below                 ++++++++++++++++++++++++
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    //
    //
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    //Update HW and SW on equipment ++++++++++++++++++++++++++
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    if ($equipmentUpdate == 1){
        //get HW + SW from PortalAPI
        if ($post_content['type'] == 'firmware'){
                    $test = json_decode($post_content['testdetails']);
                    $hw_version = 	$test->HW;
                    $sw_version = 	$test->HEX_FW;
            }
            else {
            //GET HW + SW from object
                $hw_version = 	$post_content['testdetails']['logdetails']['HW'] ?? '';
                $fw_version = 	$post_content['testdetails']['logdetails']['FW'] ?? '';
                $sw_version = 	$post_content['testdetails']['logdetails']['HEX_FW'] ?? '';

                //GET COMMITCODE
                $commitCode = compareCommitCodes($sw_version,$fw_version);

                //IF COMMITCODE IS EMPTY THEN RETURN HEX_FW
                $sw_version = ($commitCode != '' || !empty($commitCode)) ? $commitCode : $sw_version;
            }

        //check SW_VERSION for filetype HEX_FW can contain extension
        $version_file_type = strtolower(substr($sw_version, -4)); // filetype
    
        if ($version_file_type[0] == '.'){
            $sw_version = substr($sw_version, 0, -4);
        }
        
        //Update Equipment record
        $sql = "UPDATE equipment SET hw_version = ?, sw_version = ? $whereclause";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$hw_version,$sw_version]);
    }
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    //Update equipment status       ++++++++++++++++++++++++++
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    if ($equipmentUpdate_status == 1){

        if ($historytype == $HistoryType_6){$update_status = $status1;}
        if ($historytype == $HistoryType_3 && $sn_service != 'Portal'){$update_status = $status0;}
        if ($historytype == $HistoryType_7 && $sn_service == 'Portal'){$update_status = $status2;}

        //Update Equipment record
        $sql = "UPDATE equipment SET status = ? $whereclause";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$update_status]);

        //UPDATE CHANGELOG
        changelog($dbname,'equipment',$rowID,'status',$update_status,$user);
    }
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    //UPDATE equipment_history type           ++++++++++++++++++++++++++
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    if ($historyUpdate_type == 1){
        //Check if servicereport comes from ServiceTool else inhouse
        if (isset($post_content['testdetails']['serviceReport'])) {
            $maintenanceID = $post_content['testdetails']['serviceReport']['maintenance_id'];
            $visualID = $post_content['testdetails']['serviceReport']['visualinspection_id'];
        }else {
            $maintenanceID = $post_content['testdetails']['maintenance_test'];
            $visualID = $post_content['testdetails']['visualinspection'];
        }
        
        //UPDATE equipment_history record
        $sql = "UPDATE equipment_history SET type = ?, updatedby = ? where rowID= ? or rowID= ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$type15,$user,$visualID,$maintenanceID]);
    }
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    //Update productcode on equipment ++++++++++++++++++++++++++
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    if ($equipmentProductUpdate == 1 && isset($post_content['testdetails']['logdetails']['PN'])){
        //GET PN from object
        $getPN = $post_content['testdetails']['logdetails']['PN'];
        $pn2 = preg_replace("/[^0-9]/","",$getPN);
        $PN = ltrim($pn2, "0");

        //Update Equipment record
        $sql = "UPDATE equipment SET productrowid = ? $whereclause";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$PN]);
    }
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    //Update equipment service date ++++++++++++++++++++++++++
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    if ($equipmentServiceDate == 1){
        //Update Equipment record
        $sql = "UPDATE equipment SET service_date = ? $whereclause";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$current_date]);
    }
   
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    // UPDATE equipment_history of service tool ++++++++++++++++++++++++++
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    if ($servicetoolHistoryUpdate == 1 && !empty($sn_service)){
    
        // +++++++++++++++++++++++++++++++++++++++++++++++++++++++
        //CHECK if EQUIPMENT EXISTS
        // +++++++++++++++++++++++++++++++++++++++++++++++++++++++
        $whereclause = checkSerial($sn_service);
        $sql = "SELECT count(rowID) as total, rowID FROM equipment $whereclause";
        $stmt = $pdo->prepare($sql);
        $stmt->execute();
        $total = $stmt->fetchAll(PDO::FETCH_ASSOC);
        $total_servicetool = $total[0]['total'];
        $rowID_servicetool = $total[0]['rowID'];
        
        if($total_servicetool != 0){ 
        // Insert historyitem
        $sql = "INSERT INTO equipment_history (equipmentid,type,description,createdby,updatedby) VALUES (?,?,?,?,?)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$rowID_servicetool,$historytype,$testdetails,$user,$user]);
        //Update status to InUse
        $sql = "UPDATE equipment SET status = ? $whereclause";
        $stmt = $pdo->prepare($sql);
        $stmt->execute(['4']);
        }
    }
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    // sendServiceReport	         ++++++++++++++++++++++++++
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    if ($sendServiceReport == 1){
        //GET STORED SERVICE REPORT
        $sql = 'SELECT h.rowID as historyID, h.type, h.description, h.created, h.createdby FROM equipment_history h WHERE rowID = ?';
        $pdo = dbConnect($dbname);
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$last_id]);
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        foreach ($results as $result){
            $result = json_decode(json_encode($result));
            $servicereport = serviceReport($result, 'email', $language);
            generatedPDF($servicereport,$last_id,$useremail);
        }
    }  
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    // transfer to cartest table	++++++++++++++++++++++++++
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    if ($transfercartest == 1){
        convertCartest();
    }
}
else
{
    http_response_code(400); //Payload not valid
}

}

?>