<?php

include "autoload.php";

$html = new html("HOME");

function get_all_column_names()
{
    $db = new db();
    $result = $db->query($_GET['table_name'], "SHOW COLUMNS FROM " . $_GET['table_name']);
    $options = "";
    $options .= "<option value=''>NONE</option>";
    while ($columns = $result->fetch_assoc()) {
        $options .= "<option value='" . $columns['Field'] . "'>" . $columns['Field'] . "</option>";
    }
    return $options;
}

function get_tables()
{
    $db = new db();
    $result = $db->query("", "SHOW TABLES");
    $options = "";
    $options .= "<option value=''>NONE</option>";
    while ($columns = $result->fetch_array()) {
        $table_name = $columns[0];
        if ($table_name == $_GET['table_name'] || $table_name == 'user_table_views')
            continue;
        $options .= "<option value='" . $table_name . "'>" . strtoupper(str_replace("_", " ", $table_name)) . "</option>";
    }
    return $options;
}

?>

<script>
    function get_all_column_names_from_ajax(table_name, index, $value_to_be = '') {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById('pull_column_' + index).innerHTML = this.responseText;

                if ($value_to_be != '') {
                    document.getElementById('pull_column_' + index).value = $value_to_be;
                }
            }
        };
        xmlhttp.open("GET", "get_column_names.php?table_name=" + table_name, true);
        xmlhttp.send();
    }
</script>
<form action="save_columns.php" method="post">
    <input type="text" hidden value="<?php echo $_GET['table_name']; ?>" name="table_name">
    <div class="app_body_container column width_100 background_1">
        <div class="width_100 row center_auto">
            <h1><?php echo strtoupper(str_replace("_", " ", (string) $_GET['table_name'])); ?></h1>
        </div>
        <h2>PLEASE SELECT THE ORDER OF TABLE YOU WISH TO VIEW</h2>
        <?php
        $column_count = $db->query($_GET['table_name'], "SHOW COLUMNS FROM " . $_GET['table_name'])->num_rows;
        $index = 0;
        ?>
        <hr>
        <div class="row width_90 column_gap_3 center_auto">
            <label class="width_10">ORDER</label>
            <label class="width_10">COLUMN</label>
            <label class="width_10">TO</label>
            <label class="width_10">FUNC.</label>
            <label class="width_10">RETURN</label>
            <label class="width_10">VIEW</label>
            <label class="width_10">ICON</label>
            <label class="width_10">ONCLICK</label>
            <label class="width_10">OPEN</label>
            <label class="width_10">SEND</label>
            <label class="width_10">HEADER</label>
            <label class="width_10">NAME</label>
        </div>
        <?php
        while ($index < $column_count) {

            ?>
            <div class="row width_90 column_gap_3 center_auto">
                <?php
                echo "<label class='width_20' for='column_$index'>$index</label>";
                echo "<select class='width_20' name='column_$index' id='column_$index'>";
                echo get_all_column_names();
                echo "</select>";
                ?>

                <select name="match_to_table_<?php echo $index; ?>" class='width_20'
                    id="match_to_table_<?php echo $index; ?>"
                    onchange="get_all_column_names_from_ajax(this.value, '<?php echo $index; ?>')">
                    <?php echo get_tables(); ?>
                </select>

                <select name="function_<?php echo $index; ?>" id="function_<?php echo $index; ?>" class='width_20'>
                    <option value=''>NONE</option>
                    <option value='SUM'>SUM</option>
                    <option value='COUNT'>COUNT</option>
                    <option value='AVG'>AVG</option>
                    <option value='MAX'>MAX</option>
                    <option value='MIN'>MIN</option>
                </select>

                <select name="pull_column_<?php echo $index; ?>" class='width_20' id="pull_column_<?php echo $index; ?>">
                </select>

                <select name="display_method_<?php echo $index; ?>" id="display_method_<?php echo $index; ?>"
                    class='width_20'>
                    <option>TEXT</option>
                    <option>ICON</option>
                    <option>BUTTON</option>
                    <option>PROGRESS BAR</option>
                </select>

                <select name="icon_<?php echo $index; ?>" id="icon_<?php echo $index; ?>" class='width_20'>
                    <option value="">NONE</option>
                    <option value="fa fa-home">Home</option>
                    <option value="fa fa-user">User</option>
                    <option value="fa fa-envelope">Envelope</option>
                    <option value="fa fa-cog">Settings</option>
                    <option value="fa fa-star">Star</option>
                    <option value="fa fa-heart">Heart</option>
                    <option value="fa fa-search">Search</option>
                    <option value="fa fa-shopping-cart">Cart</option>
                    <option value="fa fa-bell">Notifications</option>
                    <option value="fa fa-lock">Lock</option>
                    <option value="fa fa-paperclip">Paperclip</option>
                    <option value="fa fa-file">File</option>
                    <option value="fa fa-file-lines">Document</option>
                    <option value="fa fa-file-word">Word File</option>
                    <option value="fa fa-file-excel">Excel File</option>
                    <option value="fa fa-file-pdf">PDF File</option>
                    <option value="fa fa-folder">Folder</option>
                    <option value="fa fa-folder-open">Open Folder</option>
                    <option value="fa fa-envelope">Envelope</option>
                    <option value="fa fa-envelope-open">Open Envelope</option>
                    <option value="fa fa-pen">Pen</option>
                    <option value="fa fa-pencil">Pencil</option>
                    <option value="fa fa-pen-to-square">Edit</option>
                    <option value="fa fa-print">Printer</option>
                    <option value="fa fa-sticky-note">Sticky Note</option>
                    <option value="fa fa-briefcase">Briefcase</option>
                    <option value="fa fa-calendar">Calendar</option>
                    <option value="fa fa-calendar-check">Checked Calendar</option>
                    <option value="fa fa-clipboard">Clipboard</option>
                    <option value="fa fa-clipboard-list">Clipboard List</option>
                    <option value="fa fa-folder-plus">Add Folder</option>
                    <option value="fa fa-folder-minus">Remove Folder</option>
                    <option value="fa fa-paper-plane">Send</option>
                </select>

                <select name="onclick_<?php echo $index; ?>" id="onclick_<?php echo $index; ?>" class='width_20'>
                    <option>NONE</option>
                    <option>POPUP</option>
                    <option>REDIRECT</option>
                </select>

                <?php
                $rootPath = $_SERVER["DOCUMENT_ROOT"];

                // Define folders to exclude here
                $excludedFolders = [
                    'styles',
                    '.ico',
                    'classes',
                    '.class',
                    'assets',
                    'user_types',
                    'admin_home',
                    'favicon',
                    'excluded_files',
                    'signatures',
                    'attachments',
                    'cgi-bin',
                    'default_links' // Add any other folder you want to exclude
                ];

                ?>

                <select name="onclick_file_<?php echo $index; ?>" id="onclick_file_<?php echo $index; ?>" class="width_20">
                    <option value="">NONE</option>
                    <?php
                    $directoryIterator = new RecursiveIteratorIterator(
                        new RecursiveDirectoryIterator($rootPath, RecursiveDirectoryIterator::SKIP_DOTS),
                        RecursiveIteratorIterator::SELF_FIRST
                    );

                    foreach ($directoryIterator as $file) {
                        // Check if the current file or folder is in the excluded list
                        $pathSegments = explode(DIRECTORY_SEPARATOR, $file->getPathname());
                        $isExcluded = false;
                        foreach ($pathSegments as $segment) {
                            if (in_array($segment, $excludedFolders) || strpos($segment, '.') === 0) {
                                $isExcluded = true;
                                break;
                            }
                        }
                        if ($isExcluded) {
                            continue;
                        }

                        $relativePath = str_replace($rootPath, '', $file->getPathname());
                        $label = strtoupper(str_replace(['_', '-'], ' ', basename($file->getFilename(), '.php')));

                        if ($file->isDir()) {
                            echo "<optgroup label='" . htmlspecialchars(trim($relativePath, DIRECTORY_SEPARATOR)) . "'>";
                        } elseif ($file->isFile()) {
                            echo "<option value='" . htmlspecialchars($relativePath) . "'>" . htmlspecialchars($label) . "</option>";
                        }
                    }
                    ?>
                </select>
                <?php
                echo "<select class='width_20' name='send_column_$index' id='send_column_$index'>";
                echo get_all_column_names();
                echo "</select>";
                ?>

                <input type="text" name="custom_header_<?php echo $index; ?>" id="custom_header_<?php echo $index; ?>"
                    class='width_20' placeholder="Custom Header">

                <input type="text" name="custom_text_<?php echo $index; ?>" id="custom_text_<?php echo $index; ?>"
                    class='width_20' placeholder="Custom Text">

            </div>

            <?php
            $index++;

        }

        ?>

        <?php
        // get all selected columns and display them
        $check_columns_saved = $db->query("user_table_views", "SELECT * FROM user_table_views WHERE table_name = '" . $_GET['table_name'] . "' AND user_id = '" . $_SESSION['user_id'] . "' ORDER BY record_id ASC");
        if ($check_columns_saved->num_rows > 0) {
            $i = 0;
            while ($columns = $check_columns_saved->fetch_assoc()) {
                ?>
                <script>document.getElementById('column_<?php echo $i; ?>').value = '<?php echo $columns['column_name']; ?>';</script>
                <script>document.getElementById('function_<?php echo $i; ?>').value = '<?php echo $columns['function']; ?>';</script>
                <script>document.getElementById('display_method_<?php echo $i; ?>').value = '<?php echo $columns['display_method']; ?>';</script>
                <script>document.getElementById('icon_<?php echo $i; ?>').value = '<?php echo $columns['icon']; ?>';</script>
                <script>document.getElementById('onclick_<?php echo $i; ?>').value = '<?php echo $columns['onclick']; ?>';</script>
                <script>document.getElementById('onclick_file_<?php echo $i; ?>').value = '<?php echo $columns['onclick_file']; ?>';</script>
                <script>document.getElementById('send_column_<?php echo $i; ?>').value = '<?php echo $columns['send_column']; ?>';</script>
                <script>document.getElementById('custom_header_<?php echo $i; ?>').value = '<?php echo $columns['custom_header']; ?>';</script>
                <script>document.getElementById('custom_text_<?php echo $i; ?>').value = '<?php echo $columns['custom_text']; ?>';</script>
                <?php
                if ($columns['match_to_table'] != '') {
                    ?>
                    <script>document.getElementById('match_to_table_<?php echo $i; ?>').value = '<?php echo $columns['match_to_table']; ?>';</script>
                    <script>get_all_column_names_from_ajax(document.getElementById('match_to_table_<?php echo $i; ?>').value, <?php echo $i; ?>, '<?php echo $columns['pull_column']; ?>');</script>
                    <?php
                }
                ?>

                <?php
                $i++;
            }
        }
        ?>
        <input type="text" hidden value="<?php echo $column_count; ?>" name="column_index_count">

        <button class="button" type="submit">SAVE</button>
        <br><br>
    </div>
</form>