<?php
require_once('config.php');

//Bearer Auth
if(@$_SERVER['HTTP_AUTHORIZATION'] != 'Bearer '.$arrConfig['auth']['bearer']){
    response(403, 'invalid Bearer Token');
}

if(!empty($_POST['folder'])){
    foreach($arrConfig['directories'] as $key=>$config){
        if($_POST['folder']==$key){
            $uploaddir = $config['path'];
            $uploadfile = $uploaddir . basename( $_FILES['file']['name']);
            break;
        }
    }

    if(move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)){
        response(200, "The file has been uploaded successfully");
    }

    else{
        response(500, "There was an error uploading the file");
    }

} else {
    response(422, 'parameter folder is missing');
}

function response($code, $message){
    echo json_encode(['message'=>$message]);
    header("HTTP/1.1 ".$code.' '.getCodeStatus($code));
    die();
}

function getCodeStatus($code){
    $arrCode = [
        200 => 'OK',
        403 => 'Forbidden',
        422 => 'Unprocessable Entity',
        500 => 'Server Error',
    ];
    return $arrCode[$code];
}
?>