<?php
defined($security_key) or exit;
//------------------------------------------
// History
//------------------------------------------
//Connect to DB
$pdo = dbConnect($dbname);

//CONTENT FROM API (POST)
$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
if (isset($post_content['delete'])){$command = 'delete';} //change command to delete
$date = date('Y-m-d H:i:s');


function checkSerial($serialinput){
    $serialnumberhelper = strip_tags(trim($serialinput));
    $whereclause = 'WHERE serialnumber = "'.$serialnumberhelper.'"';
    return $whereclause;
}

//CHECK IF SN AND PAYLOAD IS SEND => FROM EXTERNAL APPS 
if (isset($post_content['sn']) && isset($post_content['payload'])){

    if (!empty($post_content['sn']) && !empty($post_content['payload'])) {
        // +++++++++++++++++++++++++++++++++++++++++++++++++++++++
        // 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['payload']);
        $serial = $post_content['sn'];
        $sn_service = $post_content['payload']['external_device_sn'] ?? '';
    
        //GET PRODUCT ROWID FOR EQUIPMENT CREATE
        if (isset($post_content['payload']['logdetails']['PN']) && (!empty($post_content['payload']['logdetails']['PN']) || $post_content['payload']['logdetails']['PN'] != '')){
            $pn2 = preg_replace("/[^0-9]/","",$post_content['payload']['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 = 1;
            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 = 1;
            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['payload']['serviceReport']['visualinspection_id']) && $post_content['payload']['serviceReport']['visualinspection_id'] != 0) {
                    $updateObject_visual = 1;
                    $visualinspectionID = $post_content['payload']['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['payload']['serviceReport'])) {
                    $sendServiceReport = 1;
                    $testObject = array(
                        "final" => $post_content['payload']['serviceReport']['questionItems'],
                        "maintenance_test" => $post_content['payload']['serviceReport']['maintenance_id'],
                        "visualinspection" => $post_content['payload']['serviceReport']['visualinspection_id'],
                        "serialnumber" => $post_content['sn'],
                        "external_device_sn" => $post_content['payload']['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
        // +++++++++++++++++++++++++++++++++++++++++++++++++++++++

        //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['payload']);
                    $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
            $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['payload']['serviceReport'])) {
                $maintenanceID = $post_content['payload']['serviceReport']['maintenance_id'];
                $visualID = $post_content['payload']['serviceReport']['visualinspection_id'];
            }else {
                $maintenanceID = $post_content['payload']['maintenance_test'];
                $visualID = $post_content['payload']['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['payload']['logdetails']['PN'])){
            //GET PN from object
            $getPN = $post_content['payload']['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 = ?';
            $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
    }
}
else {
    //STANDARD HISTORY API

    //CREATE EMPTY STRINGS
    $clause = '';
    $clause_insert ='';
    $input_insert = '';

    $post_content['updatedby'] = $username;

    //ADD STANDARD PARAMETERS TO ARRAY BASED ON INSERT OR UPDATE
    if ($command == 'update' && !isset($post_content['delete'])){


    }
    elseif ($command == 'insert' && !isset($post_content['delete'])){

        //GET EQUIPMENTID IF SN IS USED
        if (array_key_exists('sn', $post_content)){
            $sql = 'SELECT rowID FROM equipment WHERE serialnumber = ?';
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$post_content['sn']]);
            $messages = $stmt->fetch();
            $messages = $messages[0];
            $post_content['equipmentid'] = $messages;
        }
        $post_content['created'] = $date;
        $post_content['createdby'] = $username;
    }
    else {
        //do nothing
    }

    //CREAT NEW ARRAY AND MAP TO CLAUSE
    if(isset($post_content) && $post_content!=''){   
        foreach ($post_content as $key => $var){
            if ($key == 'submit' || $key == 'rowID' || $key == 'sn'){
                //do nothing
            }
            else {
                $criterias[$key] = $var;
                $clause .= ' , '.$key.' = ?';
                $clause_insert .= ' , '.$key.'';
                $input_insert .= ', ?'; // ? for each insert item
                $execute_input[]= $var; // Build array for input
            }
        }
    }

    //CLEAN UP INPUT
    $clause = substr($clause, 2); //Clean clause - remove first comma
    $clause_insert = substr($clause_insert, 2); //Clean clause - remove first comma
    $input_insert = substr($input_insert, 1); //Clean clause - remove first comma

    //QUERY AND VERIFY ALLOWED
    if ($command == 'update' && !isset($post_content['delete']) && isAllowed('history',$profile,$permission,'U') === 1){
        $sql = 'UPDATE equipment_history SET '.$clause.' WHERE rowID = ?';
        $execute_input[] = $id;
        $stmt = $pdo->prepare($sql);
        $stmt->execute($execute_input);
    } 
    elseif ($command == 'insert' && !isset($post_content['delete']) && isAllowed('history',$profile,$permission,'C') === 1){
        $sql = 'INSERT INTO equipment_history ('.$clause_insert.') VALUES ('.$input_insert.')';
        $stmt = $pdo->prepare($sql);
        $stmt->execute($execute_input);
    }
    elseif ($command == 'delete' && isAllowed('history',$profile,$permission,'D') === 1){
        $stmt = $pdo->prepare('DELETE FROM equipment_history WHERE rowID = ?');
        $stmt->execute([ $id ]); 

        //Add deletion to changelog
        changelog($dbname,'history',$id,'Delete','Delete',$username);
    } else
    {
        //do nothing
    }
}
?>