<?php

include_once("database.php")
$postData = file_get_contents("php://input");

if(isset($postData) && !empty($postData)) {
    $request = json_decode($postData);
    $username = trim($request->File.id);
    $data = trim($request->File.text);
    $filename = trim($request->File.filename);
    $lang = trim($request->File.language);
    $path = trim($request->File.path).'/'.$filename;

    if(file_exists($path)) {
        $msg = "file already exists";
        clearstatcache();
        echo json_encode($msg);
    }
    else {
        $sql1 = "SELECT n_files from userdata where username = $username";
        $sql2 = "UPDATE userdata SET n_files = n_files+1 WHERE username = $username ";
        $result = mysqli_query($mysqli,$sql1);
        if($result == 10){
            $msg = "maximum limit(10) exceeded";
            echo json_encode($msg);
        }
        else{
            if($result = mysqli_query($mysqli, $sql2)) {
                $myfile = fopen($path,"w");
                fwrite($myfile,$data);
                fclose($myfile);

                $msg = "file successfully uploaded";
                clearstatcache();
                echo json_encode($msg);
            }
            else{
                http_response_code(404);
            }
        }
        
    }
    
}
?>