<?php

@session_start();

/// table ajax for page
if (isset($_POST['table_ajax'])) {
    include "db.class.php";
    $db = new db();

    $table_name = $_POST['table_name'];
    $custom_organization = $_POST['custom_organization'];
    $file_path = $_POST['file_path'];
    $where_data = $_POST['where_data'];
    $limit = $_POST['limit'];
    $order_by = "ORDER BY " . $_POST['order_by'];
    $pull_from = json_decode($_POST['pull_from'], true);
    $linked_tables = json_decode($_POST['linked_tables'], true);
    $functions = json_decode($_POST['functions'], true);
    $columns = json_decode($_POST['columns'], true);
    $display_method = json_decode($_POST['display_method'], true);
    $onclick = json_decode($_POST['onclick'], true);
    $onclick_file = json_decode($_POST['onclick_file'], true);
    $icon = json_decode($_POST['icon'], true);
    $send_column = json_decode($_POST['send_column'], true);
    $custom_text = json_decode($_POST['custom_text'], true);
    $exclude_columns_array = json_decode($_POST['exclude_columns_array'], true);
    // echo var_dump($_POST);
    ?>
    <tbody>
        <tr>
            <?php
            if ($custom_organization) {
                if (in_array("record_id", $columns)) {
                    $id_is_in_list = true;
                    $column = implode(",", $columns);
                } else {
                    $id_is_in_list = false;
                    $column = implode(",", $columns);
                    $column .= ",record_id";
                }
                $table_res = $db->query($table_name, "SELECT $column FROM " . $table_name . " WHERE " . $where_data . " " . $order_by . " " . $limit . "");
                while ($table_data = $table_res->fetch_assoc()) {
                    $index_for_columns = 0;
                    foreach ($columns as $column_name) {
                        if ($custom_text[$index_for_columns] == null) {

                            if ($linked_tables[$index_for_columns] != null) {
                                if ($functions[$index_for_columns] == "COUNT") {

                                    // COUNT FUNCTION CALCULATION
                                    $value_res = $db->query($linked_tables[$index_for_columns], "SELECT " . $functions[$index_for_columns] . "(*) AS CNT FROM " . $linked_tables[$index_for_columns] . " WHERE " . $pull_from[$index_for_columns] . " = " . $table_data['record_id']);
                                    // echo "SELECT " . $functions[$index_for_columns] . "(*) AS CNT FROM " . $linked_tables[$index_for_columns] . " WHERE " . $pull_from[$index_for_columns] . " = " . $table_data['record_id'] . "<br>";
                                    if ($value_res->num_rows > 0) {
                                        $value = $value_res->fetch_assoc();
                                        $returned_value = $value['CNT'];
                                    } else {
                                        $returned_value = "LINK TO TABLE FAILED : SELECT " . $pull_from[$index_for_columns] . " FROM " . $linked_tables[$index_for_columns] . " WHERE record_id = " . $table_data[$column_name];
                                    }
                                } else if ($functions[$index_for_columns] == "SUM") {

                                    // COUNT FUNCTION CALCULATION
                                    $value_res = $db->query($linked_tables[$index_for_columns], "SELECT " . $functions[$index_for_columns] . "($pull_from[$index_for_columns]) AS SM FROM " . $linked_tables[$index_for_columns] . " WHERE " . $pull_from[$index_for_columns] . " = " . $table_data['record_id']);
                                    // echo "SELECT " . $functions[$index_for_columns] . "($pull_from[$index_for_columns]) AS SM FROM " . $linked_tables[$index_for_columns] . " WHERE " . $pull_from[$index_for_columns] . " = " . $table_data['record_id'];
                                    if ($value_res->num_rows > 0) {
                                        $value = $value_res->fetch_assoc();
                                        $returned_value = $value['SM'];
                                    } else {
                                        $returned_value = "LINK TO TABLE FAILED : SELECT " . $pull_from[$index_for_columns] . " FROM " . $linked_tables[$index_for_columns] . " WHERE record_id = " . $table_data[$column_name];
                                    }
                                } else {
                                    // BASIC QUERY 
                                    $value_res = $db->query($linked_tables[$index_for_columns], "SELECT " . $pull_from[$index_for_columns] . " FROM " . $linked_tables[$index_for_columns] . " WHERE record_id = " . $table_data[$column_name]);
                                    if ($value_res->num_rows > 0) {
                                        $value = $value_res->fetch_assoc();
                                        $returned_value = $value[$pull_from[$index_for_columns]];
                                    } else {
                                        $returned_value = "LINK TO TABLE FAILED : SELECT " . $pull_from[$index_for_columns] . " FROM " . $linked_tables[$index_for_columns] . " WHERE record_id = " . $table_data[$column_name];
                                    }

                                }
                            } else {
                                $returned_value = $table_data[$column_name];
                            }
                        } else {
                            $returned_value = $custom_text[$index_for_columns];
                        }

                        // function to do on click
                        if ($onclick[$index_for_columns] == "REDIRECT") {
                            $onclick_html = "onclick='window.location.href = \"" . $onclick_file[$index_for_columns] . "?record_id=" . $table_data[$send_column[$index_for_columns]] . "\"'";
                        } else if ($onclick[$index_for_columns] == "POPUP") {
                            $onclick_html = "onclick='open_iframe(\"" . $onclick_file[$index_for_columns] . "?record_id=" . $table_data[$send_column[$index_for_columns]] . "\")'";
                        } else {
                            $onclick_html = "";
                        }
                        // build display method of data
                        if ($display_method[$index_for_columns] == "BUTTON") {
                            echo "<td><button $onclick_html>$returned_value</button></td>";
                        } else if ($display_method[$index_for_columns] == "ICON") {
                            $icon_class = $icon[$index_for_columns]; // comes from POST
                            echo "<td $onclick_html>";
                            echo $returned_value;
                            if ($icon_class != "") {
                                echo " <i class='$icon_class' style='font-size: 1em;color: #000;'></i>";
                            }
                            echo "</td>";
                        } else if ($display_method[$index_for_columns] == "PROGRESS BAR") {
                            ?>
                                    <td>
                                        <div
                                            style="height: 20px; width: 110px; background-color: #e9ecef; border-radius: 0.5em; border:0.5px solid #f36e216c; position: relative;">
                                            <div
                                                style="width: <?php echo $returned_value; ?>%; height: 20px; background-color: #17469ea6; z-index: 10; border-radius: 0.4em;">
                                            </div>
                                        </div>
                                    </td>
                            <?php
                        } else {

                            echo "<td>$returned_value</td>";
                        }

                        $index_for_columns++;
                    }

                    ?>
                    <?php if ($file_path != null) { ?>
                        <td>
                            <button
                                onclick="window.location.href ='<?php echo $file_path; ?>?record_id=<?php echo $table_data['record_id']; ?>'">EDIT</button>
                        </td>
                    <?php } ?>
                </tr>
                <?php

                }


            } else {
                ?>
            <tr>
                <?php
                $index_for_columns = 0;
                $table_res = $db->query($table_name, "SELECT * FROM $table_name WHERE " . $where_data . " " . $order_by . " " . $limit . "");
                while ($table_data = $table_res->fetch_assoc()) {
                    $table_columns_res = $db->query($table_name, "SHOW COLUMNS FROM $table_name");
                    while ($columns = $table_columns_res->fetch_assoc()) {
                        if (in_array($columns['Field'], $exclude_columns_array))
                            continue;

                        $all_link_columns_under_table = $db->query("default_links", "SELECT * FROM default_links WHERE parent_table_name = '" . $table_name . "' AND parent_table_column = '" . $columns['Field'] . "'");
                        if ($all_link_columns_under_table->num_rows > 0) {
                            $linked_tables_data = $all_link_columns_under_table->fetch_assoc();
                            if ($linked_tables_data['custom_text'] == "") {
                                if ($linked_tables_data['child_table_name'] != "") {
                                    $get_linked_value = $db->query($linked_tables_data['child_table_name'], "SELECT " . $linked_tables_data['pull_column_name'] . " FROM " . $linked_tables_data['child_table_name'] . " WHERE record_id = " . $table_data[$columns['Field']]);
                                    if ($get_linked_value->num_rows > 0) {
                                        $linked_value = $get_linked_value->fetch_assoc();
                                        $returned_value = $linked_value[$linked_tables_data['pull_column_name']];
                                    } else {
                                        $returned_value = "LINK TO TABLE FAILED : SELECT " . $linked_tables_data['child_table_column'] . " FROM " . $linked_tables_data['child_table_name'] . " WHERE record_id = " . $table_data[$columns['Field']];
                                    }
                                } else {
                                    $returned_value = $table_data[$columns['Field']];
                                }
                            } else {
                                $returned_value = $linked_tables_data['custom_text'];
                            }
                            // function to do on click
                            if ($linked_tables_data["onclick"] == "REDIRECT") {
                                $onclick_html = "onclick='window.location.href = \"" . $linked_tables_data["onclick_file"] . "?record_id=" . $table_data[$linked_tables_data["send_column"]] . "\"'";
                            } else if ($linked_tables_data["onclick"] == "POPUP") {
                                $onclick_html = "onclick='open_iframe(\"" . $linked_tables_data["onclick_file"] . "?record_id=" . $table_data[$linked_tables_data["send_column"]] . "\")'";
                            } else {
                                $onclick_html = "";
                            }
                            // build display method of data
                            if ($linked_tables_data["display_method"] == "BUTTON") {
                                echo "<td><button $onclick_html>$returned_value</button></td>";
                            } else if ($linked_tables_data["display_method"] == "ICON") {
                                $icon_class = $linked_tables_data["icon"]; // comes from POST
                                echo "<td $onclick_html>";
                                echo $returned_value;
                                if ($icon_class != "") {
                                    echo "<i class='$icon_class' style='font-size: 1em;color: #000;'></i></i>";
                                }
                                echo "</td>";
                            } else if ($linked_tables_data["display_method"] == "PROGRESS BAR") {
                                ?>
                                        <td>
                                            <div
                                                style="height: 20px; width: 110px; background-color: #e9ecef; border-radius: 0.5em; border:0.5px solid #f36e216c; position: relative;">
                                                <div
                                                    style="width: <?php echo $returned_value; ?>%; height: 20px; background-color: #17469ea6; z-index: 10; border-radius: 0.4em;">
                                                </div>
                                            </div>
                                        </td>
                                <?php
                            } else {

                                echo "<td>$returned_value</td>";
                            }

                        } else {
                            echo '<td>' . @$table_data[$columns['Field']] . '</td>';
                        }


                        $index_for_columns++;
                    }
                    ?>
                    <?php if ($file_path != null) { ?>
                        <td>
                            <button
                                onclick="window.location.href ='<?php echo $file_path; ?>?record_id=<?php echo $table_data['record_id']; ?>'">EDIT</button>
                        </td>
                    <?php } ?>
                </tr>
                <?php

                }
            }
            ?>

    </tbody>
    <?php
}


class table
{

    public $table_name;
    public $file_path = null;
    public $custom_organization;
    public $columns = [];
    public $linked_tables = [];
    public $pull_from = [];
    public $functions = [];
    public $display_method = [];
    public $onclick = [];
    public $onclick_file = [];
    public $icon = [];
    public $send_column = [];
    public $custom_text = [];


    function __construct($table_name)
    {

        $this->table_name = $table_name;
        $db = new db();
        ?>


        <div class="width_100 column background_1 center_auto" id="table_banner">
            <script src="https://cdn.jsdelivr.net/npm/xlsx/dist/xlsx.full.min.js"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.8.1/jspdf.plugin.autotable.min.js"></script>
            <div class="width_100 row center_auto " style="border-bottom: 2px solid #000;">
                <h2 class="width_80 row center_auto"><?php echo ' ' . str_replace("_", " ", strtoupper($table_name)); ?></h2>
                <i class="fa fa-search width_10 font_size_2_0 row center_auto" onclick="search_bar()"></i>
                <i class="fa fa-gear width_10 font_size_2_0 row center_auto"
                    onclick="open_iframe('/classes/custom_table.php?table_name=<?php echo $table_name; ?>')"></i>
                <i class="fa fa-download width_10 font_size_2_0 row center_auto" onclick="exportToExcel()"></i>
                <i class="fa fa-file width_10 font_size_2_0 row center_auto" onclick="exportToPDF()"></i>
                <!-- <i class="fa fa-upload width_10 font_size_2_0 row center_auto" onclick="#"></i> -->
            </div>
            <script>
                function exportToExcel() {
                    // Get table element
                    let table = document.getElementById("table");

                    // Columns to exclude
                    let excludeColumns = ["ACTIONS"]; // Add more column headers if needed

                    // Clone table to manipulate without affecting original
                    let cloneTable = table.cloneNode(true);

                    // Get all headers
                    let headers = cloneTable.querySelectorAll("th");

                    // Determine index of columns to remove
                    let removeIndexes = [];
                    headers.forEach((th, index) => {
                        if (excludeColumns.includes(th.innerText.trim())) {
                            removeIndexes.push(index);
                        }
                    });

                    // Remove cells under excluded columns
                    let rows = cloneTable.querySelectorAll("tr");
                    rows.forEach(row => {
                        removeIndexes.slice().reverse().forEach(idx => {
                            if (row.children[idx]) row.removeChild(row.children[idx]);
                        });
                    });

                    // Convert modified table to worksheet
                    let wb = XLSX.utils.table_to_book(cloneTable, { sheet: "<?php echo str_replace(" ", "_", strtoupper($table_name)); ?>" });

                    // Export to Excel
                    XLSX.writeFile(wb, "<?php echo str_replace(" ", "_", strtoupper($table_name)); ?>.xlsx");
                }
                async function exportToPDF() {
                    const { jsPDF } = window.jspdf;
                    const doc = new jsPDF("landscape", "mm", "a4"); // landscape mode

                    // --- Columns to exclude ---
                    const excludeColumns = ["ACTIONS"]; // 👈 edit this array

                    // --- Add Logo ---
                    let img = new Image();
                    img.src = "/assets/logo.png"; // 👈 replace with your logo path
                    await img.decode();
                    doc.addImage(img, "PNG", 250, 10, 40, 20); // position for landscape

                    // --- Add Heading ---
                    doc.setFontSize(18);
                    doc.text(
                        <?php echo "'" . str_replace("_", " ", strtoupper($table_name)) . "'"; ?>,
                        14,
                        20
                    );

                    doc.setFontSize(12);
                    doc.text("Generated: " + new Date().toLocaleDateString(), 14, 30);

                    // --- Parse Table Data (remove excluded columns) ---
                    let table = document.querySelector("#table");

                    // ✅ Only take the first header row
                    let headerRow = table.querySelector("thead tr");
                    let headers = Array.from(headerRow.querySelectorAll("th"))
                        .map(th => th.innerText.trim())
                        .filter(h => !excludeColumns.includes(h));

                    let body = Array.from(table.querySelectorAll("tbody tr")).map(tr => {
                        let cells = Array.from(tr.querySelectorAll("td"));
                        return cells
                            .map((td, i) => {
                                let header = headerRow.querySelectorAll("th")[i].innerText.trim();
                                if (!excludeColumns.includes(header)) {
                                    return td.innerText.trim();
                                }
                                return null;
                            })
                            .filter(cell => cell !== null);
                    });


                    // --- Add Table ---
                    doc.autoTable({
                        head: [headers],
                        body: body,
                        startY: 40,
                        theme: "grid",
                        styles: {
                            fontSize: 10,
                            cellPadding: 3,
                            halign: "center",
                            valign: "middle"
                        },
                        headStyles: {
                            fillColor: [41, 128, 185],
                            textColor: [255, 255, 255],
                            fontStyle: "bold"
                        },
                        bodyStyles: {
                            fillColor: [245, 245, 245]
                        },
                        alternateRowStyles: {
                            fillColor: [220, 230, 241]
                        }
                    });

                    // --- Add Page Numbers ---
                    let pageCount = doc.internal.getNumberOfPages();
                    for (let i = 1; i <= pageCount; i++) {
                        doc.setPage(i);
                        doc.setFontSize(10);
                        doc.text(
                            `Page ${i} of ${pageCount}`,
                            doc.internal.pageSize.getWidth() - 40,
                            doc.internal.pageSize.getHeight() - 10
                        );
                    }

                    // --- Save PDF ---
                    doc.save("table_report.pdf");
                }

            </script>
        </div>
        <?php
    }

    function add_action_button($file_path)
    {
        $this->file_path = $file_path;
    }


    function __destruct()
    {
        $db = new db();
        $loading = new loading();
        $exclude_columns_array = ['record_id', 'password'];
        ?>
        

        <table id="table">
            <?php
            $table_view_res = $db->query("user_table_views", "SELECT * from user_table_views WHERE table_name = '" . $this->table_name . "' AND user_id = {$_SESSION['user_id']}");
            if ($table_view_res->num_rows > 0) {
                $this->custom_organization = true;
                echo "<thead><tr>";
                $this->columns = [];
                while ($table_view = $table_view_res->fetch_assoc()) {
                    $this->columns[] = $table_view['column_name'];
                    $this->pull_from[] = $table_view['pull_column'];
                    $this->linked_tables[] = $table_view['match_to_table'];
                    $this->functions[] = $table_view['function'];
                    $this->display_method[] = $table_view['display_method'];
                    $this->onclick[] = $table_view['onclick'];
                    $this->onclick_file[] = $table_view['onclick_file'];
                    $this->icon[] = $table_view['icon'];
                    $this->send_column[] = $table_view['send_column'];
                    $this->custom_text[] = $table_view['custom_text'];



                    if ($table_view['custom_header'] != "") {
                        echo '<th>' . $table_view['custom_header'] . '</th>';
                    } else {
                        if ($table_view['function'] == 'COUNT') {
                            ?>
                            <th><?php echo strtoupper('total ' . strtoupper(str_replace("_", " ", str_replace("id", "", $table_view['match_to_table'])))); ?>
                            </th>
                            <?php
                        } else if ($table_view['function'] == 'SUM') {
                            ?>
                                <th><?php echo strtoupper('total ' . str_replace("_", " ", str_replace("id", "", $table_view['column_name']))); ?>
                                </th>
                            <?php
                        } else if ($table_view['function'] == 'AVG') {
                            ?>
                                    <th><?php echo strtoupper('AVG ' . str_replace("_", " ", str_replace("id", "", $table_view['column_name']))); ?>
                                    </th>
                            <?php
                        } else if ($table_view['function'] == 'MAX') {
                            ?>
                                        <th><?php echo strtoupper('MAX ' . str_replace("_", " ", str_replace("id", "", $table_view['column_name']))); ?>
                                        </th>
                            <?php
                        } else if ($table_view['function'] == 'MIN') {
                            ?>
                                            <th><?php echo strtoupper('MIN ' . str_replace("_", " ", str_replace("id", "", $table_view['column_name']))); ?>
                                            </th>
                            <?php
                        } else {
                            echo '<th>' . strtoupper(str_replace("_", " ", $table_view['column_name'])) . '</th>';
                        }
                    }
                }
                if ($this->file_path != null) {
                    echo "<th>ACTIONS</th>";
                }
                echo "</tr></thead>";

            } else {
                $this->custom_organization = false;
                ?>
                <thead>
                    <tr>
                        <?php
                        $table_columns_res = $db->query($this->table_name, "SHOW COLUMNS FROM " . $this->table_name . "");
                        while ($row = $table_columns_res->fetch_assoc()) {
                            $this->columns[] = $row['Field'];
                            if (in_array($row['Field'], $exclude_columns_array))
                                continue;

                            echo '<th>' . strtoupper(str_replace("_", " ", $row['Field'])) . '</th>';
                        }

                        if ($this->file_path != null) {
                            echo "<th>ACTIONS</th>";
                        }
                        ?>

                    </tr>
                </thead>
            <?php } ?>

            <div class="table_search_container " id="search_bar_container" style="display: none;">
                <?php
                $column_indexing = 0;
                foreach ($this->columns as $column) {
                    if (in_array($column, $exclude_columns_array))
                        continue;
                    if (strpos(strtolower($column), "date") !== false) {
                        echo "<div class='row width_50 column_gap_1 center_auto'>";
                        echo "<h3>" . strtoupper(str_replace("_", " ", str_replace("id", "", $column))) . "</h3>";
                        echo "<div class='column center_auto'>";
                        echo "<label>FROM</label>";
                        echo "<input type='Datetime-local' name='" . $column . "_from ' id='" . $column . "_from '>";
                        echo "</div><div class='column center_auto'>";
                        echo "<label>TO</label>";
                        echo "<input type='Datetime-local' name='" . $column . "_to ' id='" . $column . "_to '>";
                        echo "</div></div>";
                    } else {
                        echo "<input type='text' class='width_25' placeholder='" . strtoupper(str_replace("_", " ", str_replace("id", "", $column))) . "' name='$column' id='$column'>";
                    }
                    $column_indexing++;
                }

                ?>
                <div class='column center_auto'>
                    <label>ROWS</label>
                    <select id="data_rows" name="data_fows">

                        <?php
                        for ($row = 1; $row <= 10; $row++) {
                            echo "<option value='" . $row * 100 . "'>" . $row * 100 . "</option>";
                        }
                        ?>
                        <option>ALL</option>
                    </select>
                </div>
                <button id="search_bar_button" onclick="search_ajax(1)">Search</button>
            </div>
        </table>


        <!-- loading animation -->
        <?php $loading->loading_dots(); ?>

        <!-- Iframe POPUP -->
        <div class="iframe_background" style="display: none;">
            <?php $loading->loading_dots(); ?>
        </div>
        <iframe class="popup_iframe" src="" style="display: none;"> <!-- loading animation -->

        </iframe>
        <i class="fa fa-times-circle iframe_close" style="display: none;" onclick="close_iframe()"></i>



        <script>

            // Get the elements
            const child = document.getElementById("search_bar_container");
            const newParent = document.getElementById("table_banner");

            // Move child into newParent
            newParent.appendChild(child);
            search_ajax(0);
            function search_ajax(search_clicked) {
                var order_by = "record_id DESC";
                var limit = " LIMIT 100";
                var where_data = "1";

                if (search_clicked != 0) {

                    document.querySelector("#table tbody").remove();
                    document.querySelector("#loading_div").style.display = "block";
                    const container = document.getElementById("search_bar_container");
                    // Get all inputs and selects inside this div
                    const fields = container.querySelectorAll("input, select");
                    total_fields = fields.length;
                    total_empty_fields = 1;
                    let query = [];
                    fields.forEach(field => {
                        console.log(field.name, field.value);
                        if (field.value != "") {
                            if (field.name == "data_fows") {
                                if (field.value == "ALL") {
                                    var limit = "";
                                } else {
                                    var limit = " LIMIT " + field.value;
                                }
                            } else if (field.name.includes("_from") || field.name.includes("_to")) {
                                if (field.name.includes("_from")) {
                                    query.push(field.name.replace("_from", "") + " >= '" + field.value.replace("T", " ") + "'");
                                } else {
                                    query.push(field.name.replace("_to", "") + " <= '" + field.value.replace("T", " ") + "'");
                                }
                            } else {
                                query.push(field.name + " LIKE '%" + field.value + "%'");
                            }
                        } else {
                            total_empty_fields++;
                        }
                    });

                    if (total_empty_fields == total_fields) {
                        console.log("empty");
                        where_data = "1";
                        console.log(where_data);
                    } else {
                        where_data = query.join(" AND ");
                        console.log(where_data);
                    }

                };


                console.log("ajax");
                const xhr = new XMLHttpRequest();

                // Function to execute while the AJAX request is in progress
                xhr.onprogress = function (event) {
                    document.querySelector("#loading_div").style.display = "block";
                };

                // Function to execute when the AJAX request is complete
                xhr.onload = function () {
                    document.querySelector("#loading_div").style.display = "none";

                    console.log(xhr.responseText);

                    if (xhr.status >= 200 && xhr.status < 300) {
                        document.querySelector("#table").innerHTML += xhr.responseText;
                    } else {
                        console.error('AJAX request failed with status:', xhr.status);
                    }
                };

                // Function to handle errors during the AJAX request
                xhr.onerror = function () {
                    console.error('Network error occurred during AJAX request.');
                };

                xhr.open('POST', "/classes/table.class.php", true); // true makes the request asynchronous
                xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                var params = new URLSearchParams();
                params.append("table_ajax", "1");
                params.append("table_name", "<?php echo $this->table_name; ?>");
                params.append("custom_organization", "<?php echo $this->custom_organization; ?>");
                params.append("where_data", where_data);
                params.append("order_by", order_by);
                params.append("limit", limit);
                params.append("pull_from", '<?php echo json_encode($this->pull_from); ?>');
                params.append("linked_tables", '<?php echo json_encode($this->linked_tables); ?>');
                params.append("columns", '<?php echo json_encode($this->columns) ?>');
                params.append("functions", '<?php echo json_encode($this->functions) ?>');
                params.append("display_method", '<?php echo json_encode($this->display_method) ?>');
                params.append("onclick", '<?php echo json_encode($this->onclick) ?>');
                params.append("onclick_file", '<?php echo json_encode($this->onclick_file) ?>');
                params.append("icon", '<?php echo json_encode($this->icon) ?>');
                params.append("send_column", '<?php echo json_encode($this->send_column) ?>');
                params.append("custom_text", '<?php echo json_encode($this->custom_text) ?>');
                params.append("file_path", '<?php echo ($this->file_path) ?>');
                params.append("exclude_columns_array", '<?php echo json_encode($exclude_columns_array) ?>');
                xhr.send(params.toString());
            }

            function open_iframe(url) {
                document.querySelector(".popup_iframe").style.display = "block";
                document.querySelector(".iframe_close").style.display = "block";
                document.querySelector(".iframe_background").style.display = "flex";
                document.querySelector(".popup_iframe").src = url;
            }
            function close_iframe() {
                window.location.reload();
                document.querySelector(".popup_iframe").style.display = "none";
                document.querySelector(".iframe_close").style.display = "none";
                document.querySelector(".iframe_background").style.display = "none";
                document.querySelector(".popup_iframe").src = "";

            }

            function search_bar() {
                if (document.querySelector("#search_bar_container").style.display == "none") {
                    document.querySelector("#search_bar_container").style.display = "flex";
                } else {
                    document.querySelector("#search_bar_container").style.display = "none";
                }
            }
        </script>
        <?php
    }

}



