<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

?>
<?php

        header('Content-Type: application/json');

        $json_input = file_get_contents('php://input');
        $data = json_decode($json_input);
        if (json_last_error() !== JSON_ERROR_NONE) {
           echo json_encode(["error" => "Invalid JSON"]);
           exit;
        }


        $serviceName = $data->serviceName; // Accedi al valore di "serviceName"
        $iid = $data->IDD;
        $token = $data->Token;
	$Graph = $data->jSonData;
	$fileName = $data->fileName ?? null;

        $toRet = array();




	switch($serviceName) {
		case "STORE_JSON":
                {
 	if (!isset($fileName))
	{
	   echo json_encode(["error" => "fileName is mandatory!"]);
           exit;
	}

      
			$toRet['output']="STORED";
                        $toRet['result']=0;
			$toRet['reason']=$serviceName." executed.";
			$dirPath  = "/var/www/html/VIZITFS_TOCONV/".$iid;
			 if (!is_dir($dirPath)) {
				 if (!mkdir($dirPath, 0755, true)) {
			 		$toRet['result'] = -1;
            				$toRet['output'] = "STORE_JSON failed: cannot create directory.";
            				echo json_encode($toRet);
            				exit;
				 }
			 }
			$outpath = "/var/www/html/VIZITFS_TOCONV/".$iid."/".$fileName.".json";

			$jsonString = is_string($data->jSonData) ? $data->jSonData: json_encode($data->jSonData);

			file_put_contents($outpath,$jsonString);	
			if (file_exists($outpath)) {
			
			}
			else {
				$toRet['result']=-1;
				$toRet['output']="STORE_JSON failed.";	
			}               
			break;
		}

		case "GET_FILE":
                {

			$fts="";
			if ($data->folderName=="VIZITFS") {
				$fts="/var/www/html/VIZITFS/".$iid;
				$ext = ".json";
			}
			$freq = $fts."/".$data->fileName;
			if (file_exists($freq)) {
				$toRet['result']=1;
				$toRet['output']=file_get_contents($freq);
			}
			else {
				$toRet['result']=-1;
				$toRet['output']='FILE_DOES_NOT_EXISTS';
			}
                        $toRet['reason']=$serviceName." executed.";
                        break;
                }
                case "GET_FILES":
		{
			$idd = $data->IDD;
			$arr = array();
			$fts="";
			$ext="";
			if ($data->folderName=="VIZITFS") {
				$fts="/var/www/html/VIZITFS/".$iid."/";
				$ext=".json";
			}
			if ($handle = opendir($fts)) {
  				while (false !== ($entry = readdir($handle))) {
					if (strpos($entry,$ext)>-1) {
						$entryf = array();
						$entryf["filename"]=$entry;
						$fileTime = filemtime($fts.$entry);
						$entryf["timestamp"]=$fileTime;
						$entryf["timestamp_date"]=date("Ymd", $fileTime);
						$entryf["timestamp_time"]=date("His",$fileTime);
           				array_push($arr,$entryf);
        			}
    			}
    				closedir($handle);
			}

			$toRet['output'] = $arr;
                        $toRet['result']=0;
                        $toRet['reason']=$serviceName." executed.";
                        break;
                }

		case "RENAME_FILE":
                {
			if (!isset($data->newFileName)) {
				$toRet['output'] = 'newFileName param is mandatory';
                     	  	$toRet['result']=-1;
                        	$toRet['reason']=$serviceName." executed.";
                        	break;
			}

			$fts="";
			if ($data->folderName=="VIZITFS") {
				$fts="/var/www/html/VIZITFS/".$iid;
				$ext=".json";
			}
			
			$freq = $fts . "/" . $data->fileName . $ext;
			$newname = $fts . "/" . $data->newFileName . $ext;

			// Se $freq esiste, $newname è un path valido e $newname non esiste già
			if (file_exists($freq) && !file_exists($newname)) {
			   
			      if (rename($freq, $newname)) {
			     	$toRet['result'] = 0;
			      	$toRet['output'] = 'RENAME_FILE_EXECUTED';
			      }
			      else {
				     $toRet['result']=-1;
				     $toRet['output']='RENAME_FILE_FAILED';
				}
			}

			else {
				$toRet['result']=-1;
				$toRet['output']='FILE_DOES_NOT_EXISTS';
			}
                        $toRet['reason']=$serviceName." executed.";
                        break;
                }
		case "DELETE_FILE":
                {
			$fts="";
			if ($data->folderName=="VIZITFS") {
				$fts="/var/www/html/VIZITFS/".$iid;
				$ext=".json";
			}
			
			$freq = $fts . "/" . $data->fileName . $ext;

			if (file_exists($freq)) {
			   
			      if (unlink($freq)) {
			     	$toRet['result'] = 0;
			      	$toRet['output'] = 'DELETE_FILE_EXECUTED';
			      }
			      else {
				     $toRet['result']=-1;
				     $toRet['output']='DELETE_FILE_FAILED';
				}
			}

			else {
				$toRet['result']=-1;
				$toRet['output']='FILE_DOES_NOT_EXISTS';
			}
                        $toRet['reason']=$serviceName." executed.";
                        break;
                }
		default: {
                        $toRet['result']=-1;
                        $toRet['reason']=$serviceName." not found";
                }
        }

        echo json_encode($toRet);
?>
