<?php
ob_start();
require_once('rengine-API.php');

$method = $_SERVER['REQUEST_METHOD'];
//Receive the RAW post data.
$content = trim(file_get_contents("php://input"));
//Attempt to decode the incoming RAW post data from JSON.
$decoded = json_decode($content, JSON_PRETTY_PRINT);

$myfile = fopen("tmp/debug.txt", "w");
fwrite($myfile, "\nDATE & TIME :\t".date("Y-m-d H:i:s e")."\n" );
fwrite($myfile, "METHOD :\t".$method."\n" );
fwrite($myfile, "ACTION :\t".$_POST['action']."\n" );
fwrite($myfile, "BASE NAME :\t". $_FILES['file']['name']. "\nTMP NAME :\t".$_FILES['file']['tmp_name']. "\nFILE SIZE :\t".$_FILES['file']['size']."\n\n" );


if(isset($_FILES['file'])){
    if(isset($_POST['action'])){
        switch($_POST['action']){

            case 'app_mgmt_import':
                move_uploaded_file($_FILES['file']['tmp_name'], "tmp/".$_FILES['file']['name']);
                $result = valvapp_restore("tmp",$_FILES['file']['name']);
                $return["result"] = $result;
                echo json_encode($return);
                fwrite($myfile, "RESPONSE :\t".json_encode($return)."\n\n" );
                fclose($myfile);
                if($result == "OK"){
                    reboot();
                }
                break;

            case 'advanced_update':
                move_uploaded_file($_FILES['file']['tmp_name'], "tmp/".$_FILES['file']['name']);
                $result = update_engine("tmp/".$_FILES['file']['name']);
                $return["result"] = $result;
                echo json_encode($return);
                fwrite($myfile, "RESPONSE :\t".json_encode($return)."\n\n" );
                break;

            default:
                http_response_code(404);
                break;
        }
    }
    else{
        http_response_code(405);
    }
}else {
    http_response_code(400);
}




        // case 'app_mgmt_import':
        //     if(isset($_FILES['file'])){
        //         fwrite($myfile,"\nFile presents!\n" );
        //     }else {
        //         fwrite($myfile,"\nFile not presents!\n" );
        //     }
        //     fwrite($myfile,"\nFile :\n".isset($_FILES['file'])."\n" );
        //     fwrite($myfile,"\nFile name :\n".$decoded['name']."\n" );
        //     fwrite($myfile,"\nBase name : ". $decoded['file']['name']. "\nFile size : ".$decoded['file']['size']."\n\n" );
        //     break;

fclose($myfile);
?>
