<?php

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

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

  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) reached";
           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);
            }
        }
  }


}
?>
