<?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;


  $sql1 = "SELECT n_files from users where username = '$username'";
  $sql2 = "UPDATE users SET n_files = n_files+1 WHERE username = '$username'";
  $result = mysqli_query($mysqli, $sql1)->fetch_all()[0];
  if (file_exists($path)) {
    $myfile = fopen($path, "w");
    fwrite($myfile, $data);
    fclose($myfile);

    $msg = "file successfully saved";
    clearstatcache();
    echo json_encode($msg);
    exit;
  }
  if ($result[0] >= 3) {
    $msg = "maximum limit(3) reached";
    echo json_encode($msg);
  } else {
    if (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);
    }
  }


}
?>
