<?php
include "DBModel.php";
$currentFolder = null;

define("WEBSITE_BASE_PATH", "http://localhost/filemgt/dashboard/");


function get_random_name($num = 6)
{
    $characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
    $string = '';
    $max = strlen($characters) - 1;
    for ($i = 0; $i < $num; $i++) {
        $string .= $characters[mt_rand(0, $max)];
    }
    return $string;
}

function reload_to_page($page)
{
    header("Location: $page");
    exit();
}

function reload_current_directory()
{
    reload_to_page(get_current_url());
}

function get_current_url()
{
    if (in_folder()) {
        return create_url("index.php", ['id' => get_folder_id()]);
    } else {
        return create_url('index.php');
    }
}

function create_url($path, $arguments = [])
{
    $url = WEBSITE_BASE_PATH;
    if ($path != "/") {
        $url .= $path;
    }
    if (count($arguments) > 0) {
        $url .= "?";
        foreach ($arguments as $key => $value) {
            $url .= $key . "=" . $value;
        }
    }
    return $url;
}



function save_to_file_manager($filename, $realfilename, $type, $size, $folder)
{
    $model = new DBModel("file_manager");
    $model->insertRecord([
        'file_name' => $filename,
        'real_name' => $realfilename,
        'file_size' => $size,
        'file_type' => $type,
        'folder' => $folder
    ]);
}

function save_a_folder($name, $parent)
{
    $model = new DBModel("file_manager_folder");
    $model->insertRecord([
        'name' => $name,
        'parent' => $parent
    ]);
}


function get_all_files()
{
    $model = new DBModel("file_manager");
    if (in_folder()) {
        return $model->getAllBySQL("SELECT * from file_manager Where folder=?", [get_folder_id()]);
    } else {
        return $model->getAllBySQL("SELECT * from file_manager Where folder=0 OR folder IS NULL");
    }
}

function get_all_parent_folders()
{
    $model = new DBModel("file_manager");
    if (in_folder()) {
        return $model->getAllBySQL("SELECT * from file_manager_folder WHERE parent=?", [get_folder_id()]);
    } else {
        return $model->getAllBySQL("SELECT * from file_manager_folder WHERE parent IS NULL");
    }
}

function create_file_link($name)
{
    return WEBSITE_BASE_PATH . "uploads/" . $name;
}

function in_folder()
{
    if (get_folder_id()) {
        return true;
    }
    return false;
}

function get_folder_id()
{
    if (isset($_GET['id']) && !empty($_GET['id'])) {
        return $_GET['id'];
    }
    return null;
}

function getCurrentFolder($id)
{
    global $currentFolder;
    if (isset($currentFolder["id"]) && $currentFolder["id"] == $id) {
        return $currentFolder;
    } else {
        $model = new DBModel("file_manager_folder");
        $currentFolder = $model->getOneRecordByPk($id);
        return $currentFolder;
    }
}

function get_current_folder_name()
{
    if (in_folder()) {
        return "(" . getCurrentFolder(get_folder_id())["name"] . ")";
    }
}

function parent_up_url()
{
    $folder = getCurrentFolder(get_folder_id());
    if ($folder["parent"]) {
        return create_url("index.php", ['id' => $folder["parent"]]);
    } else {
        return create_url("index.php");
    }
}

function get_icon($type, $name = "")
{
    if (strpos($type, 'excel') !== false) {
        return "<img src='./images/ic_excel.png' style='width: 20px'/>";
    } else if (strpos($type, 'audio') !== false) {
        return "<img src='./images/ic_music.png' style='width: 20px'/>";
    } else if (strpos($type, 'pdf') !== false) {
        return "<img src='./images/ic_pdf.png' style='width: 20px'/>";
    } else if (strpos($type, 'openxmlformats') !== false) {
        if (strpos($name, 'doc') !== false) {
            return "<img src='./images/ic_word.png' style='width: 20px'/>";
        } else if (strpos($name, 'ppt') !== false) {
            return "<img src='./images/ic_power_point.png' style='width: 20px'/>";
        } else if (strpos($name, 'xlsx') !== false) {
            return "<img src='./images/ic_excel.png' style='width: 20px'/>";
        } else {
            return "<img src='./images/ic_file.png' style='width: 20px'/>";
        }
    } else if (strpos($type, 'image') !== false) {
        return "<img src='./images/ic_picture.png' style='width: 20px'/>";
    } else if (strpos($type, 'video') !== false) {
        return "<img src='./images/ic_video.png' style='width: 20px'/>";
    } else {
        return "<img src='./images/ic_file.png' style='width: 20px'/>";
    }
}


if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
    $folder = isset($_POST['folder']) ? $_POST['folder'] : null;

    $uploadDir = "./uploads/";

    // file upload section
    if (isset($_FILES["file"]) && $_FILES["file"]["error"] == 0) {
        $filename = $_FILES["file"]["name"];
        $filetype = $_FILES["file"]["type"];
        $filesize = $_FILES["file"]["size"];
        $random_name = get_random_name() . "." . pathinfo($filename, PATHINFO_EXTENSION);
        if (file_exists($uploadDir . $random_name)) {
            echo $filename . " is already exists.";
        } else {
            move_uploaded_file($_FILES["file"]["tmp_name"], $uploadDir . $random_name);
            //save_to_gallery($random_name, $filename);
            save_to_file_manager($random_name, $filename, $filetype, $filesize, get_folder_id());
            reload_current_directory();
        }
    } else {
        if ($folder) {
            save_a_folder($folder, get_folder_id());
            reload_current_directory();
        }
    }

}


// renaming the file

if ($_SERVER["REQUEST_METHOD"] == "GET" && isset($_GET['file'])) {

    if (is_numeric($_GET['file']) && isset($_GET['name'])) {
        $model = new DBModel("file_manager");
        $record = $model->getOneRecordByPk($_GET['file']);
        $original = $record["real_name"];
        $orig_extension = pathinfo($original, PATHINFO_EXTENSION);
        $model->updateRecordByPk($_GET['file'], [
            'real_name' => $_GET["name"] . "." . $orig_extension
        ]);
        reload_current_directory();
    }
}

// renaming the folder

if ($_SERVER["REQUEST_METHOD"] == "GET" && isset($_GET['folder'])) {
    if (is_numeric($_GET['folder']) && isset($_GET['name'])) {
        $model = new DBModel("file_manager_folder");
        $record = $model->getOneRecordByPk($_GET['folder']);
        $original = $record["name"];
        $model->updateRecordByPk($_GET['folder'], [
            'name' => $_GET["name"]
        ]);
        reload_current_directory();
    }
}

if ($_SERVER["REQUEST_METHOD"] == "GET" && isset($_GET['action']) && $_GET['action'] == 'delete') {

    $id = isset($_GET['item']) ? $_GET['item'] : null;
    if (isset($_GET['type']) && $_GET['type'] == 'file') {
        $model = new DBModel("file_manager");
        $model->deleteRecordByPk($id);
    } else if (isset($_GET['type']) && $_GET['type'] == 'folder') {
        $model = new DBModel("file_manager_folder");
        $model->deleteRecordByPk($id);
    }
    reload_current_directory();
}


?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>File Manager</title>
    <!-- <link rel="stylesheet" type="text/css" href="./assets/jquery.contextMenu.css">
    <link rel="stylesheet" type="text/css" href="./assets/jquery-confirm.min.css"> -->
    <link rel="stylesheet" href="../style.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/2.3.4/css/dataTables.dataTables.css">

    <!-- <script src="https://code.jquery.com/jquery-3.7.1.js"></script>
    <script src="https://cdn.datatables.net/2.3.4/js/dataTables.js"></script> -->
    <!-- <link rel="stylesheet" href="path/to/font-awesome/css/font-awesome.min.css"> -->

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-contextmenu/2.9.2/jquery.contextMenu.min.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-contextmenu/2.9.2/jquery.ui.position.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-contextmenu/2.9.2/jquery.contextMenu.min.js"></script>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.4/jquery-confirm.min.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.4/jquery-confirm.min.js"></script>


</head>
<style>
    table {
        width: 100%;
    }
</style>

<body>
    <h1>My Files and Folders</h1>
    <p>Add a file</p>
    <form method="post" enctype="multipart/form-data" style="display: flex;">
        <label for="file" class="form-label">Upload File</label>
        <div class="form-group">
            <input class="form-input" type="file" name="file" />&nbsp;&nbsp;
        </div>
        <label for="folder" class="form-label">Create Folder</label>
        <div class="form-group">
            <input class="form-input" type="text" name="folder">&nbsp;&nbsp;
        </div>
        <button class="btn blue" type="submit" name="submit">Submit</button>
    </form>

    <br><br>
    <h2><a href="<?Php echo create_url("index.php"); ?>">Files and Folders</a> <?php echo get_current_folder_name(); ?>
    </h2>

    <table id="example" class="display">
        <form method="post" action="search.php">
            Search For Student: <input type="text" name="search" id="search" />
        </form>
        <thead>
            <tr>
                <td>Name</td>
                <td>Date</td>
                <td>Type</td>
                <td>Size</td>
            </tr>
        </thead>
        <tbody>
            <?php if (in_folder()): ?>
                <tr>
                    <td colspan="4"><img src='./images/ic_folder.png' style='width: 20px' /> &nbsp;
                        <a href="<?php echo parent_up_url(); ?>">...</a>
                    </td>
                </tr>
            <?php endif; ?>
            <?php foreach (get_all_parent_folders() as $folderObject): ?>
                <tr>
                    <td><img src='./images/ic_folder.png' style='width: 20px' /> &nbsp;
                        <a id="<?php echo $folderObject["id"]; ?>" data-id="<?php echo $folderObject["id"]; ?>" data-type="folder"
                            data-filename="<?php echo $folderObject["name"]; ?>" class="item"
                            href="<?php echo create_url('index.php', ['id' => $folderObject["id"]]); ?>">
                            <?php echo $folderObject["name"]; ?></a>
                    </td>
                    <td><?php echo $folderObject["createdOn"]; ?></td>
                    <td>File Folder</td>
                    <td></td>
                </tr>
            <?php endforeach; ?>
            <?php foreach (get_all_files() as $fObject): ?>
                <tr>
                    <td><?php echo get_icon($fObject["file_type"], $fObject["real_name"]); ?> &nbsp;
                        <a data-id="<?php echo $fObject["id"]; ?>" data-type="file"
                            data-filename="<?php echo $fObject["real_name"]; ?>" class="item" target="_blank"
                            href="<?php echo create_file_link($fObject["file_name"]); ?>">
                            <?php echo $fObject["real_name"]; ?></a>
                    </td>
                    <td><?php echo $fObject["createdOn"]; ?></td>
                    <td><?php echo $fObject["file_type"]; ?></td>
                    <td><?php echo $fObject["file_size"]; ?></td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    


<script>
    var CURRENT_BASE_PATH = "<?php echo get_current_url(); ?>";
    var IS_DIRECTORY = "<?php echo in_folder() ? 'true' : 'false'; ?>";

    $(document).ready(function () {
        attachRightClickMenu();

        function attachRightClickMenu() {
            $.contextMenu({
                selector: '.item',
                callback: function (key, options) {
                    const $this = $(this);
                    const id = $this.data('id');
                    const type = $this.data('type');
                    const name = $this.data('filename');

                    if (key === "rename") {
                        handleRename(id, type, name);
                    } else if (key === "delete") {
                        handleDelete(id, type, name);
                    }
                },
                items: {
                    rename: { name: "Rename", icon: "edit" },
                    delete: { name: "Delete", icon: "delete" }
                }
            });
        }

        function handleRename(id, type, name) {
            let formAction = CURRENT_BASE_PATH + (IS_DIRECTORY === 'true' ? '&' : '?') + type + '=' + id;

            $.confirm({
                useBootstrap: false,
                title: 'Rename ' + name,
                content: '' +
                    '<form action="' + formAction + '" class="formName">' +
                    '<div class="form-group">' +
                    '<label>Rename ' + type + ' to</label>' +
                    '<input type="text" placeholder="New name" class="name form-control" required />' +
                    '</div>' +
                    '</form>',
                buttons: {
                    formSubmit: {
                        text: 'Submit',
                        btnClass: 'btn-blue',
                        action: function () {
                            const newName = this.$content.find('.name').val();
                            if (!newName.trim()) {
                                $.alert('Please enter a valid name');
                                return false;
                            }
                            // Redirect with new name
                            window.location.href = formAction + "&name=" + encodeURIComponent(newName);
                        }
                    },
                    cancel: function () { /* do nothing */ }
                }
            });
        }

        function handleDelete(id, type, name) {
            $.confirm({
                title: 'Confirm Delete',
                content: 'Are you sure you want to delete "' + name + '"?',
                buttons: {
                    confirm: function () {
                        const deleteURL = CURRENT_BASE_PATH +
                            (IS_DIRECTORY === 'true' ? '&' : '?') +
                            'type=' + type + '&item=' + id + '&action=delete';

                        window.location.href = deleteURL;
                    },
                    cancel: function () { /* do nothing */ }
                }
            });
        }
    });
</script>

    </body>

</html>