<?php

/**
 * File handling functions
 * 
 * @category    Filesystem
 * @package     ATProcessor
 * @author      Sam Meredith <sam@aandtinstruments.com>
 * @version     0.1
 */

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

/**
 * Turn all errors into exceptions so they can be caught in the try catch block
 */ 
set_error_handler(function($errno, $errstr, $errfile, $errline, $errcontext) {
    // error was suppressed with the @-operator
    if (0 === error_reporting()) {
        return false;
    }

    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
});

/**
 * Handle Ajax requests
 */ 
try {

    if ( isset($_POST["action"]) ) {
        $action = htmlspecialchars($_POST["action"]);

        switch ($action) {

            case "deleteFile":
                $path = htmlentities($_POST["path"]);

                echo deleteFile($path);
                break;

            case "fileList":
                $path = htmlentities($_POST["path"]);
                $pattern = htmlentities($_POST["pattern"]);

                echo getFileList($path, $pattern);
                break;

            case "getFile":
                $file = htmlentities($_POST["file"]);
                $path = htmlentities($_POST["path"]);

                echo getFile($path, $file);
                break;

            case "getLocalFile":
                $path = htmlentities($_POST["path"]);
                
                echo getLocalFile($path);
                break;

            case "savebfd":
                $name = htmlentities($_POST["name"]);
                $config = $_POST["config"];

                echo saveBFDConfig($name, $config);
                break;

            default:
                throw new Exception('Invalid Request', 2000);
                break;
        }
    }

} catch (Exception $e) {

    echo json_encode(
        array(
            'status' => false,
            'error' => $e->getMessage(),
            'error_code' => $e->getCode()
        )
    );

    exit;
}

restore_error_handler();

/**
 * Delete the file at the given path
 * @param string $path
 */
function deleteFile($path) {
    if (unlink($path)) {
        return json_encode(
            array(
                'status' => true,
                'response' => true
            )
        );
    } else {
        throw new Exception('Delete Failed.', 2002);
    }
}

/** 
 * Get list of files at a given path matching a given pattern
 * @param string $path The path to search for files
 * @param string $pattern A regex pattern to match
 * @return json an encoded json return structure
 */
function getFileList($path, $pattern) {
    $fileArray = scandir($path);

    if ($fileArray) {
        $fileArray = array_filter($fileArray, function($file) use ($pattern) {
            return preg_match($pattern, $file);
        });

        return json_encode(
            array(
                'status' => true,
                'response' => $fileArray
            )
        );
    } else {
        throw new Exception('File not found.', 2001);
    }
}

/** 
 * Returns the file at a given path
 * @param string $path The path to search for files
 */
function getFile($path, $filename) {
    if (file_exists($path)) {

        header($_SERVER["SERVER_PROTOCOL"] . " 200 OK");
        header("Cache-Control: public"); // Needed for IE
        header("Content-Type: " . mime_content_type($path));
        header("Content-Transfer-Encoding: Binary");
        header("Content-Length:" . filesize($path));
        header("Content-Disposition: attachment; filename=" . $filename);
        readfile($path);

    } else {
        throw new Exception('File not found.', 2001);
    }
}

/** 
 * Returns the contents of a file under the root directory
 * @param string $path The path to search for files
 */
function getLocalFile($path) {
    return file_get_contents($path);
}

/** 
 * Save a BFD configuration to file
 * @param string $name The name for the saved configuration
 * @param string $config The configuration to save
 */
function saveBFDConfig($name, $config) {
    $configPath = "logs/database/";

    $fullName = $configPath . $name . date('_d_m_Y') . ".bfdbackup";
    file_put_contents($fullName, $config);

    return json_encode(
        array(
            'status' => true,
            'response' => true
        )
    );
}

?>