<?php
    // CONFIGURATION
    // Absolute path to the directory containing all image directories as well as the staging directory
    // All other paths (in the user interface) are relative to $rootDir
    // All paths require trailing slashes!
    $rootDir = __DIR__ . '/../images/';
    // The URI at which the rootDir will be served
    // Use /images/ for testing
    // When the app is not served at the root https://example.com/ but at a sublocation like https://example.com/imgsort2/,
    // you might need to set it to just `images` without the /
    $rootPath = '/images/';
    // Path of the directory containing all the files to be sorted, relative to $rootDir
    $stagingDirName = '.sort/';


    // Not configuration anymore!
    $stagingPath = $rootPath . $stagingDirName . '/';
    $stagingDir = $rootDir . $stagingDirName . '/';
   
    /**
     * @brief Return a list of all files in the staging directory
     */
    function getFileList() {
        global $stagingDir;
        $images = array_values(array_filter(scandir($stagingDir), function($file) use ($stagingDir) {
            return is_file($stagingDir . $file); //&& preg_match('/\.(jpg|jpeg|png|gif)$/i', $file);
        }));
        return json_encode($images);
    }

    /**
     * @brief Return a list of all files in $dir and its sub directories
     * @param $displayDir The returned file paths will be appended to $displayDir instead of $dir
     * $dir and $displayDir must have trailing slashes!
     */
    function getFileListRecursive($dir, $displayDir=null) {
        $filesAndDirs = scandir($dir);
        $files = [];
        foreach ($filesAndDirs as $file) {
            if ($file == "." || $file == "..") { continue; }
            if (is_dir($dir . $file)) {
                $sub_files = getFileListRecursive($dir . $file . '/', $displayDir . $file . '/');
                $files = array_merge($files, $sub_files);
            } else {
                if (is_null($displayDir)) {
                    $files[] = $dir . $file;
                } else {
                    $files[] = $displayDir . $file;
                }
            }
        }
        return $files;
    }


    function saveMove($file, $dest) {
        $fullDir = dirname($dest);

        if (!is_file($file)) {
            error_log("File not found: ".$file);
            return [false, "File not found"];
        }
        if (is_file($dest)) {
            error_log("File already exists: ".$dest);
            return [false, "File already exists"];
        }

        // create non existing directories
        if (!is_dir($fullDir)) {
            // rw for use+group, recursive
            if (!mkdir($fullDir, 0770, true)) {
                return [false, "Failed to create directory"];
            }
        }
        if (!rename($file, $dest)) {
            return [false, "Failed to move file"];
        }
        return [true, ""];
    }
    /**
     * Move a file from staging to the destination directory
     * @param file relative to stagingDir
     * @param dest new filename relative to rootDir
     */
    function moveFile($file, $dest) {
        global $stagingDir, $rootDir;
        $fullFile = $stagingDir . $file;
        $fullDest = $rootDir . $dest;
        return saveMove($fullFile, $fullDest);
    }

    /**
     * Like movefile, except reversed
     */
    function undoFile($file, $dest) {
        global $stagingDir, $rootDir;
        $fullFile = $stagingDir . $file;
        $fullDest = $rootDir . $dest;
        return saveMove($fullDest, $fullFile);
    }


    // Parse the request
    $action = $_GET["action"];
    $result_ok = true;
    switch ($action) {
      case "getFileList":
        /* $result = getFileList(); */
        $result = json_encode(getFileListRecursive($stagingDir, ''));
        break;
      case "getStagingPath":
        $result = $stagingPath;
        break;
      case "moveFile":
        $file = $_GET["file"];
        $dest = $_GET["dest"];
        list($result_ok, $result) = moveFile($file, $dest);
        break;
      case "undoFile":
        $file = $_GET["file"];
        $dest = $_GET["dest"];
        list($result_ok, $result) = undoFile($file, $dest);
        break;
      default:
        $result = "Invalid action";
        $result_ok = false;
    }
    if ($result_ok) {
      http_response_code(200);
    } else {
      http_response_code(500);
    }
    echo $result;
?>
