<?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'];
    $column_ids = json_decode($_POST['columns_ids'], true);
    $custom_organization = $_POST['custom_organization'];
    ?>
    <tbody>
        <?php
        if ($custom_organization == "true") {
            // get the IDs and work them back to columns fro table to view
            $columns = [];
            foreach ($column_ids as $column_id) {
                $column_default_link_res = $db->query("default_links", "SELECT * FROM default_links WHERE record_id = $column_id");
                if ($column_default_link_res->num_rows > 0) {
                    $column_default_link = $column_default_link_res->fetch_assoc();
                    $columns[] = $column_default_link['parent_table_column'];
                    $as_columns[] = $column_default_link['custom_header'];
                    $function[] = $column_default_link['function'];
                    $display_method[] = $column_default_link['display_method'];
                    $onclick[] = $column_default_link['onclick'];
                    $onclick_file[] = $column_default_link['onclick_file'];
                    $icon[] = $column_default_link['icon'];
                    $send_column[] = $column_default_link['send_column'];
                    $custom_text[] = $column_default_link['custom_text'];
                    $prefix[] = $column_default_link['prefix_on_value'];
                    $postfix[] = $column_default_link['postfix_on_value'];
                    $number_formater[] = $column_default_link['number_format'];
                    $number_format_decimal[] = $column_default_link['number_format_decimal'];
                    $link_table[] = $column_default_link['child_table_name'];
                    $linK_table_column_return[] = $column_default_link['pull_column_name'];

                }
            }
            //QUERY TO GET THE DATA
            $sql_select = [];
            $i = 0;
            foreach ($columns as $column) {
                $sql_select[] = $column . " AS " . str_replace([',', "'", ".", " ", "-", "/"], '', $as_columns[$i]);
                $i++;
            }
            $sql_select_string = count($sql_select) > 0 ? implode(",", $sql_select) : "*";
            $table_data_res = $db->query($table_name, "SELECT " . $sql_select_string . " FROM " . $table_name . " WHERE " . $where_data . " " . $order_by . " " . $limit);

            if ($table_data_res->num_rows > 0) {
                while ($row = $table_data_res->fetch_assoc()) {
                    echo "<tr>";
                    $column_index = 0;
                    foreach ($row as $column => $value) {
                        // if there is costom static text like EDIT, PDF
                        if ($custom_text[$column_index] != null || $custom_text[$column_index] != '') {
                            $text_to_show = $custom_text[$column_index];
                        } else {
                            // calculate, reach other tables for data and get values
                            if ($link_table[$column_index] != '') {
                                if ($function[$column_index] == 'SUM') {
                                    $link_table_res = $db->query($link_table[$column_index], "SELECT SUM(" . $send_column[$column_index] . ") as `value` FROM " . $link_table[$column_index] . " WHERE " . $linK_table_column_return[$column_index] . " = '" . $value . "'");
                                    if ($link_table_res->num_rows > 0) {
                                        $link_table_row = $link_table_res->fetch_assoc();
                                        $text_to_show = $link_table_row['value'];
                                    }

                                } else if ($function[$column_index] == 'COUNT') {
                                    $link_table_res = $db->query($link_table[$column_index], "SELECT COUNT(" . $linK_table_column_return[$column_index] . ") as `value` FROM " . $link_table[$column_index] . " WHERE " . $linK_table_column_return[$column_index] . " = '" . $value . "'");

                                    if ($link_table_res->num_rows > 0) {
                                        $link_table_row = $link_table_res->fetch_assoc();
                                        $text_to_show = $link_table_row['value'];
                                    }

                                } else if ($function[$column_index] == 'AVG') {
                                    $link_table_res = $db->query($link_table[$column_index], "SELECT AVG(" . $send_column[$column_index] . ") as `value` FROM " . $link_table[$column_index] . " WHERE " . $linK_table_column_return[$column_index] . " = '" . $value . "' ORDER BY record_id DESC LIMIT 1");
                                    if ($link_table_res->num_rows > 0) {
                                        $link_table_row = $link_table_res->fetch_assoc();
                                        $text_to_show = $link_table_row['value'];
                                    }
                                } else if ($function[$column_index] == 'MIN') {
                                    $link_table_res = $db->query($link_table[$column_index], "SELECT MIN(" . $send_column[$column_index] . ") as `value` FROM " . $link_table[$column_index] . " WHERE " . $linK_table_column_return[$column_index] . " = '" . $value . "' ORDER BY record_id DESC LIMIT 1");
                                    if ($link_table_res->num_rows > 0) {
                                        $link_table_row = $link_table_res->fetch_assoc();
                                        $text_to_show = $link_table_row['value'];
                                    }

                                } else if ($function[$column_index] == 'MAX') {
                                    $link_table_res = $db->query($link_table[$column_index], "SELECT MAX(" . $send_column[$column_index] . ") as `value` FROM " . $link_table[$column_index] . " WHERE " . $linK_table_column_return[$column_index] . " = '" . $value . "' ORDER BY record_id DESC LIMIT 1");
                                    if ($link_table_res->num_rows > 0) {
                                        $link_table_row = $link_table_res->fetch_assoc();
                                        $text_to_show = $link_table_row['value'];
                                    }

                                } else {
                                    $link_table_res = $db->query($link_table[$column_index], "SELECT " . $linK_table_column_return[$column_index] . " FROM " . $link_table[$column_index] . " WHERE record_id = '" . $value . "'  ORDER BY record_id DESC LIMIT 1");
                                    if ($link_table_res->num_rows > 0) {
                                        $link_table_row = $link_table_res->fetch_assoc();
                                        $text_to_show = $link_table_row[$linK_table_column_return[$column_index]];
                                    }
                                }
                            } else {
                                $text_to_show = $value;
                            }
                        }
                        // check if its a number and give it a number format
                        if ($number_formater[$column_index] == 1) {
                            $text_to_show = number_format((Float) $text_to_show, $number_format_decimal[$column_index], '.', ',');
                        }
                        // add a defined prefix to the value
                        if ($prefix[$column_index] != null || $prefix[$column_index] != '') {
                            $text_to_show = $prefix[$column_index] . $text_to_show;
                        }
                        // add a defined postfix to the value
                        if ($postfix[$column_index] != null || $postfix[$column_index] != '') {
                            $text_to_show = $text_to_show . $postfix[$column_index];
                        }
                        // check if there is a redirect set up
                        if ($onclick[$column_index] == 'REDIRECT') {
                            $onclick_function = "onclick=\"window.location.href = '" . $onclick_file[$column_index] . "?record_id=" . $row[str_replace([',', "'", ".", " ", "-", "/"], '', $as_columns[$column_index])] . "'\"";
                        } else if ($onclick[$column_index] == 'POPUP') {
                            $onclick_function = "onclick=\"open_iframe('" . $onclick_file[$column_index] . "?record_id=" . $row[str_replace([',', "'", ".", " ", "-", "/"], '', $as_columns[$column_index])] . "')\"";
                        } else {
                            $onclick_function = "";
                        }
                        if ($display_method[$column_index] == 'BUTTON') {
                            $text_to_show = "<button class=\"button_small\" $onclick_function>" . $text_to_show . "</button>";
                        } else if ($display_method[$column_index] == 'ICON') {
                            $text_to_show = $text_to_show . " <i style='color:black' class=\"" . $icon[$column_index] . "\" $onclick_function></i>";

                        } else if ($display_method[$column_index] == 'PROGRESS BAR') {
                            $text_to_show = '<div style="height: 20px; width: 100%; background-color: #e9ecef; border-radius: 0.5em; border:0.5px solid #f36e216c; position: relative;" ' . $onclick_function . '> <div style="width: ' . $text_to_show . '%; height: 20px; background-color: #17469ea6; z-index: 10; border-radius: 0.4em;"></div></div>';
                        }
                        echo "<td $onclick_function>" . $text_to_show . "</td>";
                        $column_index++;
                    }
                    echo "</tr>";
                }
            }
        } else {
            $table_data_res = $db->query($table_name, "SELECT * FROM " . $table_name . " WHERE 1 ORDER BY record_id DESC " . $limit);
            if ($table_data_res->num_rows > 0) {
                while ($row = $table_data_res->fetch_assoc()) {
                    echo "<tr>";
                    foreach ($row as $column => $value) {
                        echo "<td>" . $value . "</td>";
                    }
                    echo "</tr>";
                }
            }
        }

        ?>
    </tbody>
    <?php
}

if (isset($_POST['user_custom'])) {

    $db = new db();
    var_dump($_POST);
    // Delete old data
    $db->query("user_table_views", "DELETE FROM user_table_views WHERE user_id = '" . $_SESSION['user_id'] . "' AND table_name = '" . $_POST['table_name'] . "'");
    // insert the table order for the user under user table_data
    $column_ids = json_decode($_POST['columns'], true);
    foreach ($column_ids as $column_id) {
        $db->query("user_table_views", "INSERT INTO user_table_views (user_id, table_name, default_link_id) VALUES ('" . $_SESSION['user_id'] . "', '" . $_POST['table_name'] . "', '" . $column_id . "')");
    }
}


class table
{
    public $table_name;
    public $file_path = null;
    public $custom_organization;
    public $columns = [];
    public $searchable_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;height: 50px;">
                <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 all_column_names_from_table_as_select($start_column, $start_id)
    {
        $db = new db();
        $columns = "<option value='" . $start_id . "'>" . $start_column . "</option>";
        $columns .= "<option value='-1' style='background-color: red;'>REMOVE</option>";
        $default_links_res = $db->query("default_links", "SELECT * FROM default_links WHERE parent_table_name = '" . $this->table_name . "' AND custom_header != '$start_column'");
        if ($default_links_res->num_rows > 0) {
            while ($default_link = $default_links_res->fetch_assoc()) {
                $columns .= "<option value='" . $default_link['record_id'] . "'>" . $default_link['custom_header'] . "</option>";
            }
        }
        return $columns;
    }

    function __destruct()
    {
        $db = new db();
        $loading = new loading();
        $exclude_columns_array = ['record_id', 'password'];
        ?>
        <script>
            var order_by = "record_id DESC";
        </script>

        <table id="table">
            <thead>
                <tr id="header_row" class="table_header"> <?php
                // check if user has their own configuration
                $user_table_views_res = $db->query("user_table_views", "SELECT * FROM user_table_views WHERE user_id = '" . $_SESSION['user_id'] . "' AND table_name = '" . $this->table_name . "' ORDER BY record_id ASC");
                if ($user_table_views_res->num_rows > 0) {
                    $this->custom_organization = true;
                    while ($user_table_views = $user_table_views_res->fetch_assoc()) {
                        $this->columns[] = $user_table_views['default_link_id'];
                        $default_links_res = $db->query("default_links", "SELECT * FROM default_links WHERE record_id = '" . $user_table_views['default_link_id'] . "'");
                        $default_link = $default_links_res->fetch_assoc();
                        if ($default_link['searchable'] == 1) {
                            $this->searchable_columns[] = $default_link['parent_table_column'];
                        }
                        ?>
                            <td style="min-width: 300px;">
                                <div class="row center_auto">
                                    <input id="column_<?php echo $default_link['record_id']; ?>"
                                        value="<?php echo $default_link['parent_table_column']; ?>" hidden>
                                    <select onchange="change_column(this)" style="width:80%;float:left;">
                                        <?php echo $this->all_column_names_from_table_as_select($default_link['custom_header'], $default_link['record_id']); ?>
                                    </select>
                                    <?php if ($default_link['parent_table_column'] != 'record_id') { ?>
                                        <i style='color:black;margin-left:10px;' class="fa-solid fa-up-long"
                                            onclick="order_by_column(this,'column_<?php echo $default_link['record_id']; ?>', 'ASC')"></i>
                                        <i style='color:black;margin-left:10px;' class="fa-solid fa-down-long"
                                            onclick="order_by_column(this,'column_<?php echo $default_link['record_id']; ?>', 'DESC')"></i>
                                    <?php } ?>
                                </div>
                            </td>
                            <?php
                    }
                    ?>
                        <td>
                            <i style='color:green; font-size: 2em;margin-top: -7px;' class="fa-sharp fa-solid fa-plus"
                                onclick="add_column()"></i>
                        </td>
                        <?php
                } else {
                    // get all default links made to this table
                    $default_links_res = $db->query("default_links", "SELECT * FROM default_links WHERE parent_table_name = '" . $this->table_name . "'");
                    if ($default_links_res->num_rows > 0) {
                        $this->custom_organization = true;

                        while ($default_link = $default_links_res->fetch_assoc()) {
                            $this->columns[] = $default_link['record_id'];
                            if ($default_link['searchable'] == 1) {
                                $this->searchable_columns[] = $default_link['parent_table_column'];
                            }
                            ?>
                                <td style="min-width: 300px;">
                                    <div class="row center_auto">
                                        <input id="column_<?php echo $default_link['record_id']; ?>"
                                            value="<?php echo $default_link['parent_table_column']; ?>" hidden>
                                        <select onchange="change_column(this)" style="width:80%;float:left;">
                                            <?php echo $this->all_column_names_from_table_as_select($default_link['custom_header'], $default_link['record_id']); ?>
                                        </select>
                                        <?php if ($default_link['parent_table_column'] != 'record_id') { ?>
                                            <i style='color:black;margin-left:10px;' class="fa-solid fa-up-long"
                                                onclick="order_by_column(this,'column_<?php echo $default_link['record_id']; ?>', 'ASC')"></i>
                                            <i style='color:black;margin-left:10px;' class="fa-solid fa-down-long"
                                                onclick="order_by_column(this,'column_<?php echo $default_link['record_id']; ?>', 'DESC')"></i>
                                        <?php } ?>
                                    </div>
                                </td> 
                                <?php
                        }
                        ?>
                            <td>
                                <i style='color:green; font-size: 2em;margin-top: -7px;' class="fa-sharp fa-solid fa-plus"
                                    onclick="add_column()"></i>
                            </td>
                            <?php
                    } else {

                        $this->custom_organization = false;
                        ?>

                            <?php
                            // get all default links made to this table
                            $table_columns_res = $db->query($this->table_name, "SHOW COLUMNS FROM " . $this->table_name);
                            if ($table_columns_res->num_rows > 0) {
                                while ($table_column = $table_columns_res->fetch_assoc()) {
                                    $this->columns[] = $table_column['Field'];
                                }
                            }
                    }
                }
                ?>
                </tr>
            </thead>
            <script>
                function order_by_column(icon_select, select, order) {

                    if (icon_select.style.color == "black") {

                        icon_select.style.color = "green";
                        order_by = document.getElementById(select).value + " " + order;
                        search_ajax(1);

                        var all_icons = document.getElementById("header_row").querySelectorAll("i");
                        all_icons.forEach(icon => {
                            if (icon != icon_select) {
                                icon.style.display = "none";
                            }
                        });

                    } else if (icon_select.style.color == "green") {

                        icon_select.style.color = "black";
                        order_by = "record_id DESC";
                        search_ajax(1);

                        var all_icons = document.getElementById("header_row").querySelectorAll("i");
                        all_icons.forEach(icon => {
                            icon.style.display = "block";

                        });
                    }
                }

                function add_column() {
                    var last_column = document.getElementById("header_row").lastElementChild;
                    var new_column = document.createElement("td");
                    new_column.innerHTML = "<select onchange=\"change_column(this,1)\"><?php echo $this->all_column_names_from_table_as_select('SELECT', -1); ?></select>";
                    document.getElementById("header_row").insertBefore(new_column, last_column);
                    new_column.querySelector("select").focus();
                    new_column.querySelector("select").scrollIntoView({
                        block: "center",
                        inline: "center",
                        behavior: "smooth"
                    });
                }
                function change_column(selected_select, new_added_select) {

                    if (new_added_select == 1) {
                        var duplicate = false;
                        var selects = document.getElementById("header_row").getElementsByTagName("select");
                        for (var i = 0; i < selects.length; i++) {
                            if (selects[i] != selected_select && selects[i].value == selected_select.value) {
                                duplicate = true;
                                break;
                            }
                        }
                        if (duplicate) {
                            alert("Duplicate column. Please select a different one.");
                            selected_select.value = -1;
                            return;
                        }
                    }
                    if (!duplicate) {
                        var selects = document.getElementById("header_row").getElementsByTagName("select");
                        for (var i = 0; i < selects.length; i++) {
                            if (selects[i] != selected_select && selects[i].value == selected_select.value) {
                                selects[i].value = -1;
                            }
                        }
                        var selects = document.getElementById("header_row").getElementsByTagName("select");
                        var values = [];
                        for (var i = 0; i < selects.length; i++) {
                            if (selects[i].value == -1) {
                                continue;
                            }
                            values.push(selects[i].value);
                        }
                        var xhr = new XMLHttpRequest();
                        xhr.onreadystatechange = function () {
                            if (xhr.readyState === 4 && xhr.status === 200) {
                                window.location.reload();
                            }
                        };
                        xhr.open("POST", "#", true);
                        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                        xhr.send("table_name=<?php echo $this->table_name; ?>&columns=" + JSON.stringify(values) + "&user_custom");
                    }
                }
            </script>


            <div class="table_search_container " id="search_bar_container" style="display: none;">
                <?php
                $column_indexing = 0;
                foreach ($this->searchable_columns as $column) {
                    if (in_array($column, $exclude_columns_array))
                        continue;
                    if (strpos(strtolower($column), "date") !== false) {
                        echo "<div class='column center_auto'>";
                        echo "<label>" . strtoupper(str_replace("_", " ", str_replace("id", "", $column))) . "</label>";
                        echo "<div class='row width_50 column_gap_1 center_auto'>";
                        echo "<input type='Datetime-local' name='" . $column . "_from ' id='" . $column . "_from '> - ";
                        echo "<input type='Datetime-local' name='" . $column . "_to ' id='" . $column . "_to '>";
                        echo "</div>";
                        echo "</div>";
                    } else {
                        echo "<div class='column center_auto'>";
                        echo "<label>" . strtoupper(str_replace("_", " ", str_replace("id", "", $column))) . "</label>";
                        echo "<input type='text' class='width_25'  name='$column' id='$column'>";
                        echo "</div>";
                    }
                    $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 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_ids", '<?php echo json_encode($this->columns) ?>');
                params.append("custom_organization", '<?php echo json_encode($this->custom_organization) ?>');
                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
    }

}



