<?php
session_start();
require_once "PHPMailer.php";
require_once "SMTP.php";
require_once "Exception.php";
require_once "dashboard_class.php";


use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

class root_styles
{
    function __destruct()
    {
        ?>
        <style>
            body {
                margin: 0;
                background: linear-gradient(45deg, rgb(0, 195, 255), rgb(5, 41, 109), rgb(141, 224, 255), rgb(0, 0, 0));
                background-size: 400% 400%;
                animation: gradient 20s ease infinite;
                display: flex;
                flex-direction: row;
                flex-wrap: wrap;
                align-content: space-around;
                justify-content: center;
                overflow: hidden;
                /* Prevents overflow */
                position: relative;
            }

            /* Gradient Animation */
            @keyframes gradient {
                0% {
                    background-position: 0% 50%;
                }

                50% {
                    background-position: 100% 50%;
                }

                100% {
                    background-position: 0% 50%;
                }
            }

            /* Particle Base */
            .particle {
                position: absolute;
                opacity: 0.8;
                animation: floatParticles linear infinite;
                z-index: 1;

            }

            /* Circle Shape */
            .circle {
                width: 12px;
                height: 12px;
                border-radius: 50%;
                background-color: rgba(255, 255, 255, 0.6);
                animation-duration: 14s;
                z-index: 1;

            }

            /* Hexagon Shape */
            .hexagon {
                width: 10px;
                height: 10px;
                background-color: rgba(255, 255, 255, 0.6);
                clip-path: polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%);
                animation-duration: 16s;
                z-index: 1;

            }

            /* Diamond Shape */
            .diamond {
                width: 10px;
                height: 10px;
                background-color: rgba(255, 255, 255, 0.6);
                transform: rotate(45deg);
                animation-duration: 18s;
                z-index: 1;

            }

            /* Floating Animation */
            @keyframes floatParticles {
                0% {
                    transform: translateY(100vh) translateX(0) scale(1);
                    opacity: 0.5;
                }

                50% {
                    opacity: 1;
                }

                100% {
                    transform: translateY(-10vh) translateX(30px) scale(1.2);
                    opacity: 0;
                }
            }

            /* Popup container */
            .popup {
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0, 0, 0, 0.5);
                display: none;
                justify-content: center;
                align-items: center;
                z-index: 10;
                backdrop-filter: blur(10px);
            }

            /* Popup content */
            .popup-content {
                background: rgba(255, 255, 255);
                padding: 2vw;
                border-radius: 10px;
                width: 30vw;
                height: 38vw;
                /* width: 50vw; */
                text-align: center;
                -webkit-box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.75);
                -moz-box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.75);
                box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.75);
            }

            .inputs {
                border: none;
                border-bottom: 5px solid;
                background: transparent;
                outline: none;
                font-size: 2vw;
                color: black;
                margin: 0vw 0vw 2vw 0vw;
            }

            .login_inputs {
                border: none;
                border-bottom: 5px solid;
                background: transparent;
                outline: none;
                /* font-size: 4vw; */
                /* height: 11vw; */
                font-size: 3vw;
                height: 7vw;
                color: black;
                margin: 0vw 0vw 2vw 0vw;
            }

            .header {
                /* font-size: 11vw; */
                font-size: 5vw;
                color: black;
                margin: 2vw 0vw;

            }

            .submit_btn {
                font-size: 2vw;
                color: white;
                cursor: pointer;
                background: transparent;
                border: 3px solid;
                border-radius: 15px;
                outline: none;
                width: 80%;
                margin: 0vw auto;
            }

            .submit_btn:hover {
                scale: 1.1;
                transition: all 0.5s ease-in-out;
                box-shadow: 0px 15px 10px rgba(0, 0, 0, 1);
            }

            .submit_btn:not(:hover) {
                scale: 1;
                transition: all 0.5s ease-in-out;
            }

            .container {
                display: flex;
                flex: 1 1 auto;
                z-index: 2;
                height: 100%;

            }

            img {
                width: 50px;
                margin: 10px 0;
            }

            .sidebar {
                width: 20.8%;
                /* height: 97vh; */
                height: 100%;
                background: black;
                padding: 10px;
                float: left;
                position: absolute;
                top: 0;
                left: 0;
                overflow-y: scroll;
            }

            .sidebar a {
                text-decoration: none;
                color: white;
                font-size: 2vw;
                margin: 10px 0;
            }

            .sidebar::-webkit-scrollbar {
                width: 1em;
            }

            .sidebar::-webkit-scrollbar-track {
                /* box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3); */
                background-color: transparent;
            }

            .sidebar::-webkit-scrollbar-thumb {
                background-image: url(images/scroll_icon.png);
                background-size: 20px 100%;
                background-repeat: no-repeat;
            }

            iframe {
                width: 80vw;
                /* Adjust size as needed */
                height: 80vh;
                border: none;
                /* Removes default border */
                background: transparent;
            }

            .transparent-iframe {
                position: relative;
                z-index: 10;
                /* Ensures it stays above the background */
                /* backdrop-filter: blur(10px); */
                /* Adds a blur effect */
            }

            button {
                font-size: 0.95vw;
                margin: 1vw auto;
                cursor: pointer;
                border: 3px solid #01b9f5;
                background: white;
                width: 90%;
                height: 2vw;
                color: #145693;
                border-radius: 0.8vw;
                overflow: auto;
                z-index: 2;
                text-transform: uppercase;
            }

            button:hover {
                scale: 1.1;
                transition: all 0.5s ease-in-out;
                /* box-shadow: 0px 15px 10px rgba(0, 0, 0, 1); */
                background: #145693;
                color: white;
                border: 3px solid white;
            }

            button:not(:hover) {
                scale: 1;
                transition: all 0.5s ease-in-out;
            }

            .login_btn {
                /* font-size: 3.25vw; */
                font-size: 2.5vw;
                overflow: hidden;
                /* margin: 3vw auto; */
                margin: 2vw auto;
                cursor: pointer;
                border: 3px solid white;
                background: gray;
                width: 90%;
                color: white;
                padding: 3vw;
                border-radius: 0.8vw;
                z-index: 2;
            }

            .login_btn:hover {
                scale: 1;
                transition: all 0.5s ease-in-out;
            }

            .login_btn:not(:hover) {
                scale: 1;
                transition: all 0.5s ease-in-out;
            }

            .text {
                font-size: 2vw;
                color: white;
            }

            .text1 {
                font-size: 2vw;
                color: Black;
            }

            .logo {
                margin: 1vw;
                width: 100%;
                cursor: pointer;
            }

            .dropdown {
                display: none;
                flex-direction: column;
                background-color: darkgrey;
                /* background-color: #145693; */
                border: 3px solid white;
                border-top: none;
                width: 88%;
                position: relative;
                bottom: 26px;
                z-index: 1;
                padding: 1vw 0vw;
                border-bottom-left-radius: 10px;
                border-bottom-right-radius: 10px;
                animation: dropdown 0.8s ease-in-out;
            }

            @keyframes dropdown {
                from {
                    opacity: 0;
                    transform: translateY(-20px);
                }

                to {
                    opacity: 1;
                    transform: translateY(0);
                }
            }

            .sub_2 {
                text-align: center;
                border-bottom: 1px solid #145693;
                font-size: 1.5vw;
                color: white;
                margin-bottom: 0;
            }

            .mini_btn {
                margin: 1vw auto 0vw auto;
                cursor: pointer;
                border: 3px solid #80808000;
                background: white;
                width: 80%;
                color: black;
                border-radius: 15px;
                font-size: 0.75vw;
                box-shadow: -4px 4px 9px rgba(0, 0, 0, 1);
                text-transform: uppercase;
            }

            .mini_btn:hover {
                transition: all 0.5s ease-in-out;
                box-shadow: 0px 10px 10px rgba(0, 0, 0, 1);
                background: white;
                color: #145693;
            }

            .mini_btn:not(:hover) {
                transition: all 0.5s ease-in-out;
            }

            .frame {
                height: 99.5%;
                float: right;
                width: 77.5%;
                position: absolute;
                right: 0;
                top: 0;
                overflow: hidden;
                border: none;
            }

            @media only screen and (max-width: 767px) and (min-width:501) {
                .dropdown {
                    width: 86%;
                }

                button {
                    width: 93%;
                }

                .popup-content {
                    width: 45vw;
                    height: 50vw;
                }
            }

            @media only screen and (max-width: 500px) {

                .sidebar {
                    width: 18.5%;
                    height: 98.6%;
                }

                button {
                    font-size: 2vw;
                    margin: 2vw auto;
                    padding: 1vw;
                }

                .mini_btn {
                    font-size: 2vw;
                    margin: 2vw auto 0vw auto;
                    padding: 1vw;
                    width: 90%;
                }

                .sub_2 {
                    font-size: 2vw;
                }

                .inputs {
                    font-size: 1.5vw;
                    margin: 1vw 0vw 1.5vw 0vw;
                }

                .login_inputs {
                    font-size: 1.5vw;
                    margin: 1vw 0vw 1.5vw 0vw;
                }

                .header {
                    font-size: 2.5vw;
                    margin: 2vw 0vw;
                }

                .submit_btn {
                    font-size: 2vw;
                    margin: 1vw auto;
                }

                .login_btn {
                    font-size: 2vw;
                    margin: 1vw auto;
                }

                .text {
                    font-size: 2.5vw;
                }

                .text1 {
                    font-size: 2.5vw;
                }

                .logo {
                    margin: 10px 0;
                    width: 25vw;
                    cursor: pointer;
                }
            }
        </style>

        <script>
            document.addEventListener("DOMContentLoaded", function () {
                const particleCount = 25; // Adjust number of particles
                const shapes = ["particle", "circle", "hexagon", "diamond"];
                const body = document.body;

                for (let i = 0; i < particleCount; i++) {
                    let particle = document.createElement("div");
                    let shape = shapes[Math.floor(Math.random() * shapes.length)];
                    particle.classList.add("particle", shape);
                    // Randomize position, animation duration, and speed
                    particle.style.left = Math.random() * 100 + "vw";
                    particle.style.animationDuration = Math.random() * 10 + 10 + "s"; // Between 10-20s
                    particle.style.animationDelay = Math.random() * 10 + "s"; // Staggered animation start
                    particle.style.width = Math.random() * 5 + 2 + "vw";
                    particle.style.height = particle.style.width;
                    particle.style.opacity = 0;

                    // Randomize animation speed
                    particle.style.animationTimingFunction = `cubic-bezier(${Math.random() * 0.1 + 0.05}, ${Math.random() * 0.9 + 0.05}, ${Math.random() * 0.1 + 0.05}, ${Math.random() * 0.9 + 0.05})`;

                    body.appendChild(particle);
                }
            });

        </script>

        <?php
    }
}

class login_system
{

    /**
     * This is the destructor of the class login_system.
     * It will display a login form as a popup to the user if the user is not logged in.
     * It will also submit the login form if the user is logged in.
     * It will also check the login status of the user every second and log the user out if the user is not logged in.
     */
    public function __destruct()
    {
        ?>
        <div id="loginPopup" class="popup">
            <div class="popup-content">
                <h2 class="header">Login</h2>
                <form id="loginForm" style="display: flex; flex-direction: column;">
                    <input type="text" id="username" name="username" placeholder="Username" class="login_inputs" required>
                    <input type="password" id="password" name="password" placeholder="Password" class="login_inputs" required>

                    <button type="button" id="submit_btn" class="login_btn" onclick="submitLogin()">Submit</button>
                </form>
            </div>
        </div>



        <script>
            first_load();

            function first_load() {
                check_login_status();
                setInterval(check_login_status, 1000);
            }

            function logout() {
                window.location.href = 'logout.php';
            }

            function check_login_status() {
                var xhr = new XMLHttpRequest();
                xhr.open("POST", "login.php", true);
                xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                xhr.onreadystatechange = function () {
                    console.log(xhr.responseText); // Handle response from server
                    if (xhr.responseText == "0") {
                        showPopup();
                    }
                };
                xhr.send("login_check");
            }

            function submitLogin() {
                var username = document.getElementById('username').value;
                var password = document.getElementById('password').value;

                var xhr = new XMLHttpRequest();
                xhr.open("POST", "login.php", true);
                xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        // alert(xhr.responseText); // Handle response from server
                        if (xhr.responseText == 1) {
                            document.getElementById('loginPopup').style.display = 'none';
                            document.getElementById('username').value = "";
                            document.getElementById('password').value = "";
                            window.location.href = 'index.php';
                        } else {
                            alert("LOGIN FAILED PLEASE CHECH CREDENTIALS");
                        }
                    }
                };
                xhr.send("username=" + encodeURIComponent(username) + "&password=" + encodeURIComponent(password));
            }
        </script>
        <?php
    }
}

class online_check
{
    function __destruct()
    {
        ?>

        <div id="noInternetPopup" class="popup">
            <div class="popup-content">
                <h2 class="header">You are offline</h2>
                <p class="text1">Internet connection lost. <br>Please check your internet connection and Please try again.</p>
            </div>
        </div>
        <script>
            function checkInternetConnection() {
                if (navigator.onLine) {
                    console.log("The browser is online.");
                    document.getElementById('noInternetPopup').style.display = 'none';

                    return 1;
                } else {
                    console.log("The browser is offline.");
                    document.getElementById('noInternetPopup').style.display = 'flex';

                    return 0;
                }
            }

            setInterval(checkInternetConnection, 1000);
        </script>
        <?php
    }
}

class navbar
{

    /**
     * Generates the basic HTML structure for the sidebar
     * 
     * This function is the constructor for the navbar class and is called when an object of the class is created.
     * It creates the basic HTML structure for the sidebar, which includes a container div and a sidebar div.
     * The container div contains the sidebar div, which contains the logo and the navigation menu.
     * The navigation menu is created by calling the add_menu_item method.
     * The logo is added by calling the add_logo method.
     */
    function __construct()
    {
        ?>
        <div class="container">
            <div class="sidebar">
                <div style="display: flex; flex-direction: column; align-items: center;">
                    <?php
    }

    /**
     * Adds the logo to the sidebar
     * 
     * This function adds the logo to the sidebar. The logo is a clickable image that redirects the user to the home page.
     */
    function add_logo()
    {
        ?>
                    <img src="icons/logo.svg" alt="Logo" onclick="change_to('home.php')" class="logo">
                    <?php

    }

    /**
     * Opens a group of menu items in the sidebar
     * 
     * This function creates a button with the name of the group, and a dropdown div with the same name.
     * When the button is clicked, the dropdown is shown or hidden.
     * The dropdown div contains the menu items for the group, which are added by calling the add_button method.
     * @param string $name The name of the group
     */
    function open_group($name)
    {
        ?>
                    <button onclick="dropdown('<?php echo $name; ?>')"><?php echo $name; ?></button>
                    <div class="dropdown" id="<?php echo $name; ?>">
                        <?php
    }

    /**
     * Adds a heading to the sidebar
     * 
     * This function outputs an HTML heading element with the specified name.
     * The heading is styled with the class "sub_2".
     * 
     * @param string $name The text to be displayed as the heading
     */

    function add_heading($name)
    {

        ?>
                        <h2 class="sub_2"><?php echo $name; ?>
                        </h2>
                        <?php
    }
    /**
     * Adds a button to the sidebar
     * 
     * This function adds a button to the sidebar with the specified name and ID.
     * The button is styled with the class "mini_btn".
     * When the button is clicked, the page is redirected to the URL specified in the $page_path parameter.
     * If the $button_text parameter is not empty, the button text is set to that value, otherwise the button text is set to the $name parameter.
     * @param string $name The name of the button
     * @param string $page_path The URL to redirect to when the button is clicked
     * @param string $button_html_id The ID of the button
     * @param string $button_text The text to be displayed on the button, if not empty
     */
    function add_button($name, $page_path, $button_html_id, $button_text = "")
    {
        ?>

                        <button onclick="change_to('<?php echo $page_path; ?>')" class="mini_btn"
                            id="<?php echo $button_html_id; ?>"><?php echo $button_text; ?></button>
                        <?php
    }

    /**
     * Adds a logout button to the sidebar
     * 
     * This function adds a button to the sidebar with the text "LOG OUT" and the class "mini_btn".
     * When the button is clicked, the logout function is called, which redirects the user to the logout page.
     */
    function add_logout_button()
    {
        ?>
                        <button onclick="logout()" class="mini_btn">LOG OUT</button>
                        <?php

    }

    function add_dev_mode_button()
    {
        ?>
                        <div id='dev_mode'
                            style="width:100%; height:100%;z-index:9999999;background-color: blue;display:none;top:0;left:0; color:white;">

                        </div>
                        <button onclick="toggle_dev_mode()" class="mini_btn">DEV MODE</button>
                        <?php

    }

    /**
     * Closes the group div and dropdown div that were opened by open_group.
     * This function should be called after all the buttons for the group have been added.
     * It is called automatically by the destructor of this class.
     */
    function end_group()
    {
        ?>
                    </div>
                    <?php
    }

    function navbar_end()
    {
        ?>
                </div>
            </div>
            <script>
                function change_to(url) {
                    if (url.includes('/')) {
                        document.getElementById("app_frame").src = 'app/' + url;
                        return;
                    }
                    document.getElementById("app_frame").src = 'app/' + url + '/home.php';
                }
                var set = 0;
                var input_n = document.getElementById("username");
                var input_p = document.getElementById("password");

                function dropdown(id) {
                    var dropdowns = document.querySelectorAll(".dropdown");
                    dropdowns.forEach(function (el) {
                        if (el.id != id) {
                            el.style.transition = "all 0.5s ease-in-out";
                            setTimeout(function () {
                                el.style.display = "none";
                            }, 500);
                        }
                    });
                    document.getElementById(id).style.display = document.getElementById(id).style.display == "flex" ? "none" : "flex";
                }


                setInterval(get_dev_console, 1000);
                function get_dev_console() {
                    console.log("get_dev_console");
                    var xhr = new XMLHttpRequest();
                    xhr.open("POST", "root.class.php", true);
                    xhr.onload = function () {
                        if (xhr.status === 200) {
                            document.getElementById('dev_mode').innerHTML = xhr.responseText;
                            console.log(xhr.responseText);

                        } else {
                            console.error("Error:", xhr.statusText);
                        }
                    };
                    xhr.send("ajax_type=dev_mode_check");
                }
                function toggle_dev_mode() {
                    document.getElementById('dev_mode').style.display = document.getElementById('dev_mode').style.display == "none" ? "block" : "none";
                }
            </script>
            <?php
    }

}
class select
{
    private $attributes = [];
    private $option = ["" => ""];

    private $value;

    function addAttribute($name, $value)
    {
        $this->attributes[$name] = $value;
    }
    function name($name)
    {
        $this->addAttribute('name', $name);
    }

    function id($id)
    {
        $this->addAttribute('id', $id);
    }

    function add_option($value, $label)
    {
        $this->option[$value] = $label;
    }

    function onchange($onchange)
    {
        $this->addAttribute('onchange', $onchange);
    }
    function onclick($onclick)
    {
        $this->addAttribute('onclick', $onclick);
    }
    function oninput($oninput)
    {
        $this->addAttribute('oninput', $oninput);
    }
    function required()
    {
        $this->addAttribute('required', 'required');
    }
    function disabled()
    {
        $this->addAttribute('disabled', 'disabled');

    }
    function readonly()
    {
        $this->addAttribute('readonly', 'readonly');
    }

    function autofocus()
    {
        $this->addAttribute('autofocus', 'autofocus');
    }

    function style($style)
    {
        $this->addAttribute('style', $style);
    }

    function class($class = "inputs")
    {
        $this->addAttribute('class', $class);
    }

    function fill_from_db($table_name, $column_for_value, $column_for_label, $where_clause = ' 1 ')
    {
        $db = new db_safeguard();
        $query = "SELECT $column_for_value, $column_for_label FROM $table_name WHERE $where_clause";
        $result = $db->query($table_name, $query);
        while ($row = $result->fetch_assoc()) {
            $this->option[$row[$column_for_value]] = $row[$column_for_label];
        }
    }

    function value_from_db($table_name, $value_column, $where_clause)
    {
        $db = new db_safeguard();
        $res = $db->query($table_name, "SELECT $value_column FROM $table_name WHERE $where_clause");
        $row = $res->fetch_assoc();
        $this->value = $row[$value_column];

    }
    function add()
    {
        if (!array_key_exists('class', $this->attributes)) {
            $this->class();
        }
        $select = "<select";
        foreach ($this->attributes as $key => $value) {
            $select .= " $key='$value'";
        }
        $select .= ">";

        foreach ($this->option as $value => $label) {
            $select .= "<option value='$value'>$label</option>";
        }

        $select .= "</select>";

        $select .= "<script>document.getElementById('" . $this->attributes['id'] . "').value = '" . $this->value . "';</script>";
        echo $select;
    }

}

class label
{
    private $attributes = [];

    private $value;

    function addAttribute($name, $value)
    {
        $this->attributes[$name] = $value;
    }
    function for($for)
    {
        $this->addAttribute('for', $for);
    }
    function value($text)
    {
        $this->value = $text;
    }
    function class($class = "labels")
    {
        $this->addAttribute('class', $class);
    }
    function add()
    {

        if (!array_key_exists('class', $this->attributes)) {
            $this->class();
        }
        $label = "<label";
        foreach ($this->attributes as $key => $value) {
            $label .= " $key='$value'";
        }
        $label .= ">" . $this->value;
        $label .= "</label>";
        echo $label;
    }

}

class input
{
    private $attributes = [];

    private $value;

    /**
     * Adds an attribute to the input element.
     * This function adds a single attribute to the input element. The attribute is
     * specified by the name and value parameters.
     * @param string $name The name of the attribute.
     * @param string $value The value of the attribute.
     */
    function addAttribute($name, $value)
    {
        $this->attributes[$name] = $value;
    }
    /**
     * Sets the name attribute for the input element.
     *
     * This function assigns a name attribute to the input element, which is used
     * to identify the input when the form is submitted. The name is specified by
     * the $name parameter.
     *
     * @param string $name The name of the input element.
     */

    function name($name)
    {
        $this->addAttribute('name', $name);
    }

    function id($id)
    {
        $this->addAttribute('id', $id);
    }

    function onchange($onchange)
    {
        $this->addAttribute('onchange', $onchange);
    }
    function onkeyup($onchange)
    {
        $this->addAttribute('onkeyup', $onchange);
    }
    function onclick($onclick)
    {
        $this->addAttribute('onclick', $onclick);
    }
    function oninput($oninput)
    {
        $this->addAttribute('oninput', $oninput);
    }
    function required()
    {
        $this->addAttribute('required', 'required');
    }
    function disabled()
    {
        $this->addAttribute('disabled', 'disabled');

    }
    function readonly()
    {
        $this->addAttribute('readonly', 'readonly');
    }
    function autofocus()
    {
        $this->addAttribute('autofocus', 'autofocus');
    }
    function min($min)
    {
        $this->addAttribute('min', $min);
    }
    function max($max)
    {
        $this->addAttribute('max', $max);
    }
    function step($step)
    {
        $this->addAttribute('step', $step);
    }
    /**
     * Sets the pattern attribute for the input element.
     *
     * This function assigns a pattern attribute to the input element, which is
     * used to validate the input when the form is submitted. The pattern is
     * specified by the $pattern parameter.
     *
     * @param string $pattern The pattern to be used for validation.
     */
    function pattern($pattern)
    {
        $this->addAttribute('pattern', $pattern);
    }
    function placeholder($placeholder)
    {
        $this->addAttribute('placeholder', $placeholder);
    }

    function value($value)
    {
        $this->value = $value;


    }

    function style($style)
    {
        $this->addAttribute('style', $style);
    }

    function class($class = "inputs")
    {
        $this->addAttribute('class', $class);
    }

    function value_from_db($table_name, $value_column, $where_clause)
    {
        $db = new db_safeguard();
        $res = $db->query($table_name, "SELECT $value_column FROM $table_name WHERE $where_clause");
        $row = $res->fetch_assoc();

        if (isset($this->attributes['id']) && $this->attributes['id'] == 'password') {
            $auth = new authentication();
            $this->value = $auth->decrypt_password($row[$value_column]);
        } else {
            $this->value = $row[$value_column];
        }

    }
    function type($type = "text")
    {
        $knownTypes = ['text', 'password', 'email', 'number', 'url', 'tel', 'search', 'color', 'date', 'datetime-local', 'month', 'week', 'time', 'checkbox', 'radio', 'file', 'hidden', 'image', 'button', 'reset', 'submit', 'range'];
        if (in_array($type, $knownTypes)) {
            $this->addAttribute('type', $type);
        } else {
            $this->value = "[HTML ERROR] - Unknown type: " . $type . " expected one of: " . implode(", ", $knownTypes);
            ;
        }
    }
    function add()
    {
        if (!array_key_exists('class', $this->attributes)) {
            $this->class();
        }

        $input = "<input";
        foreach ($this->attributes as $key => $value) {
            $input .= " $key='$value'";
        }
        $input .= " value=\"{$this->value}\"/>";
        echo $input;
    }

}

class button
{
    private $attributes = [];

    function addAttribute($name, $value)
    {
        $this->attributes[$name] = $value;
    }
    function name($name)
    {
        $this->addAttribute('name', $name);
    }

    function id($id = 'submit')
    {
        $this->addAttribute('id', $id);
    }

    function onchange($onchange)
    {
        $this->addAttribute('onchange', $onchange);
    }
    function onclick($onclick)
    {
        $this->addAttribute('onclick', $onclick);
    }
    function oninput($oninput)
    {
        $this->addAttribute('oninput', $oninput);
    }
    function required()
    {
        $this->addAttribute('required', 'required');
    }
    function disabled()
    {
        $this->addAttribute('disabled', 'disabled');

    }

    function readonly()
    {
        $this->addAttribute('readonly', 'readonly');
    }

    function autofocus()
    {
        $this->addAttribute('autofocus', 'autofocus');
    }
    function value($value)
    {
        $this->value = $value;
    }

    function class($class = "submit_btn")
    {
        $this->addAttribute('class', $class);
    }

    function add()
    {
        if (!array_key_exists('id', $this->attributes)) {
            $this->id();
        }
        if (!array_key_exists('class', $this->attributes)) {
            $this->class();
        }
        $button = "<button";
        foreach ($this->attributes as $key => $value) {
            $button .= " $key='$value' ";
        }
        $button .= ">" . $this->value . "</button>";
        echo $button;
    }
}

class root
{

    /*************  ✨ Codeium Command 🌟  *************/
    public function Main_iframe()
    {
        // Include the root styles
        // The root styles are used to style the main page of the application
        // This includes the background color, font styles, and other general styles
        new root_styles();
        ?>
            <iframe src="app/home.php" id="app_frame" class="frame transparent-iframe">

            </iframe>
            <?php
    }
    /******  4b74866a-5ec7-44a1-8dcc-03aef436633f  *******/

    public function OnPageScripts()
    {
        ?>


            <script>
                setInterval(check_work_orders, 1000);
                setInterval(reviews, 1000);
                setInterval(service_tickets, 1000);
                setInterval(approvals, 1000);
                function closePopup() {
                    document.getElementById('loginPopup').style.display = 'none';
                }

                function check_work_orders() {
                    var xhr = new XMLHttpRequest();
                    xhr.open("POST", "root.class.php", true);
                    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                    xhr.onreadystatechange = function () {
                        console.log("work_orders: " + xhr.responseText); // Handle response from server
                        var number = parseInt(xhr.responseText);
                        if (number > 0) {
                            document.getElementById('work_orders').style.backgroundColor = "#145693";
                            setTimeout(function () {
                                document.getElementById('work_orders').style.backgroundColor = "white";
                                setTimeout(function () {
                                    document.getElementById('work_orders').style.backgroundColor = "#145693";
                                }, 2000); // Reset after 2000ms
                            }, 2000); // Reset after 2000ms
                        } else {
                            document.getElementById('work_orders').style.backgroundColor = "white";
                        }
                        document.getElementById('work_orders').innerHTML = "( " + xhr.responseText + " )";
                    };
                    xhr.send("ajax_type=get_work_orders");
                }

                function reviews() {
                    var xhr = new XMLHttpRequest();
                    xhr.open("POST", "root.class.php", true);
                    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                    xhr.onreadystatechange = function () {
                        console.log("reviews: " + xhr.responseText); // Handle response from server
                        var number = parseInt(xhr.responseText);
                        if (number > 0) {
                            document.getElementById('reviews').style.backgroundColor = "#145693";
                            setTimeout(function () {
                                document.getElementById('reviews').style.backgroundColor = "white";
                                setTimeout(function () {
                                    document.getElementById('reviews').style.backgroundColor = "#145693";
                                }, 2000); // Reset after 2000ms
                            }, 2000); // Reset after 2000ms
                        } else {
                            document.getElementById('reviews').style.backgroundColor = "white";
                        }
                        document.getElementById('reviews').innerHTML = "( " + xhr.responseText + " )";
                    };
                    xhr.send("ajax_type=reviews");
                }

                function service_tickets() {
                    var xhr = new XMLHttpRequest();
                    xhr.open("POST", "root.class.php", true);
                    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                    xhr.onreadystatechange = function () {
                        console.log("service_tickets: " + xhr.responseText); // Handle response from server
                        var number = parseInt(xhr.responseText);
                        if (number > 0) {
                            document.getElementById('service_tickets').style.backgroundColor = "#145693";
                            setTimeout(function () {
                                document.getElementById('service_tickets').style.backgroundColor = "white";
                                setTimeout(function () {
                                    document.getElementById('service_tickets').style.backgroundColor = "#145693";
                                }, 2000); // Reset after 2000ms
                            }, 2000); // Reset after 2000ms
                        } else {
                            document.getElementById('service_tickets').style.backgroundColor = "white";
                        }
                        document.getElementById('service_tickets').innerHTML = "( " + xhr.responseText + " )";
                    };
                    xhr.send("ajax_type=service_tickets");
                }

                function approvals() {
                    var xhr = new XMLHttpRequest();
                    xhr.open("POST", "root.class.php", true);
                    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                    xhr.onreadystatechange = function () {
                        console.log("approvals: " + xhr.responseText); // Handle response from server
                        var number = parseInt(xhr.responseText);
                        if (number > 0) {
                            document.getElementById('approvals').style.backgroundColor = "#145693";
                            setTimeout(function () {
                                document.getElementById('approvals').style.backgroundColor = "white";
                                setTimeout(function () {
                                    document.getElementById('approvals').style.backgroundColor = "#145693";
                                }, 2000); // Reset after 2000ms
                            }, 2000); // Reset after 2000ms
                        } else {
                            document.getElementById('approvals').style.backgroundColor = "white";
                        }
                        document.getElementById('approvals').innerHTML = "( " + xhr.responseText + " )";
                    };
                    xhr.send("ajax_type=approvals");
                }

                function showPopup() {
                    document.getElementById('loginPopup').style.display = 'flex';
                }


            </script>

            <?php
    }


    public function __destruct()
    {
        // session_destroy();
    }
}

class js_ajax
{

    private $table_name;
    private $type;
    private $redirect;
    private $excloded_colum_names;
    private $add_column_and_value;
    private $function_name;
    private $submit_btn_id;
    private $list_of_ids_for_text_formators;
    private $dev_mode = 0;
    private $return_columns;
    private $on_success;
    private $run_on_load = 0;
    function dev_mode()
    {
        $this->dev_mode = 1;
    }
    function on_success($message)
    {
        $this->on_success = $message;
    }
    // submit button handler to prevent double clicking and multiple form submission
    function function_name($function_name)
    {
        $this->function_name = $function_name;

    }

    function submit_btn_id($submit_btn_id)
    {

        $this->submit_btn_id = $submit_btn_id;
    }

    function select($table_name)
    {
        $this->table_name = $table_name;
        $this->type = "SELECT";

    }

    function insert($table_name)
    {
        $this->table_name = $table_name;
        $this->type = "INSERT";

    }

    function update($table_name)
    {
        $this->table_name = $table_name;
        $this->type = "UPDATE";

    }

    function delete($table_name)
    {
        $this->table_name = $table_name;
        $this->type = "DELETE";

    }
    function redirect($file_path)
    {
        $this->redirect = $file_path;
    }

    function exclude_inputs($excloded_colum_names)
    {
        $this->excloded_colum_names = $excloded_colum_names;
    }

    function add_column_and_value($add_column_and_value)
    {
        $this->add_column_and_value = $add_column_and_value;
    }

    function text_formaters($list_of_ids_for_text_formators)
    {
        $this->list_of_ids_for_text_formators = $list_of_ids_for_text_formators;
    }

    function return_columns($return_columns)
    {
        $this->return_columns = $return_columns;
    }

    function run_on_load()
    {
        $this->run_on_load = 1;
    }
    function __destruct()
    {
        ?>
            <script>

                <?php if ($this->run_on_load == 1) {
                    echo $this->function_name . "();";
                } ?>
                document.addEventListener('DOMContentLoaded', function () {
                    var button = document.getElementById('<?php echo $this->submit_btn_id; ?>');
                    if (button) {

                        button.addEventListener('click', function () {
                            console.log('test ----------------------------------');
                            button.disabled = true;
                            var originalText = button.textContent;
                            button.textContent = 'Loading...';
                            setTimeout(function () {
                                button.disabled = false;
                                button.textContent = originalText;
                            }, 5000);
                        });
                    }
                });
                function <?php echo $this->function_name; ?>() {

                    <?php if ($this->type == "INSERT" || $this->type == "UPDATE") { ?>
                        var requiredInputs = document.querySelectorAll(".form_down input[required], .form_down select[required], .form_down textarea[required], .search_form_top input[required], .search_form_top select[required], .search_form_top textarea[required], .search_form input[required], .search_form select[required], .search_form textarea[required]");
                        var isAllFilled = true;
                        requiredInputs.forEach(function (input) {
                            if (input.value == "") {
                                isAllFilled = false;
                                input.style.backgroundColor = "red";
                                input.focus();
                            } else {
                                input.style.backgroundColor = "";
                            }
                        });
                        if (!isAllFilled) {
                            return;
                        }
                    <?php } ?>

                    var data = {};
                    var inputs = document.querySelectorAll(".form_down input, .form_down select, .form_down textarea, .search_form_top input, .search_form_top select, .search_form_top textarea, .search_form input, .search_form select, .search_form textarea");
                    inputs.forEach(function (input) {
                        if (input.value != "") {
                            if (input.id.includes("date_time")) {
                                data[input.id] = input.value.replace("T", " ");
                            } else {
                                data[input.id] = input.value;
                            }
                        }
                    });
                    data["ajax_type"] = "<?php echo $this->type; ?>";
                    data["table_name"] = "<?php echo $this->table_name; ?>";
                    data["edit_file_name"] = "<?php echo $this->redirect; ?>";
                    data["excloded_colum_names"] = "<?php echo $this->excloded_colum_names; ?>";
                    data["add_column_and_value"] = "<?php echo $this->add_column_and_value; ?>";


                    <?php
                    if (is_array($this->list_of_ids_for_text_formators) && count($this->list_of_ids_for_text_formators) > 0) {
                        foreach ($this->list_of_ids_for_text_formators as $list_of_id) {
                            ?> data["<?php echo $list_of_id; ?>"] = document.getElementById("<?php echo $list_of_id; ?>").innerHTML;

                            data = Object.keys(data).filter(key => !key.startsWith('imageInput_<?php echo $list_of_id; ?>')).reduce((obj, key) => {
                                obj[key] = data[key];
                                return obj;
                            }, {});
                            <?php
                        }
                    }

                    ?>

                    function popup(message) {
                        var popup = document.createElement('div');
                        popup.classList.add('popup');
                        popup.innerHTML = '<h2>' + message + '</h2><button class="submit_btn">OKAY</button>';
                        document.body.appendChild(popup);
                        popup.style.top = "50%";
                        popup.style.left = "50%";
                        popup.style.transform = "translate(-50%, -50%)";
                        popup.style.position = "fixed";
                        popup.style.zIndex = "9999";
                        popup.style.background = "#fff";
                        popup.style.padding = "2%";
                        popup.style.border = "1px solid #333";
                        popup.style.borderRadius = "10px";
                        popup.style.boxShadow = "0px 0px 10px rgba(0,0,0,0.5)";
                        var background = document.createElement('div');
                        background.classList.add('background');
                        background.style.position = "fixed";
                        background.style.top = "0%";
                        background.style.left = "0%";
                        background.style.width = "100%";
                        background.style.height = "100%";
                        background.style.background = "rgba(0,0,0,0.5)";
                        document.body.appendChild(background);
                        var closePopup = popup.querySelector('.submit_btn');
                        closePopup.addEventListener('click', function () {
                            background.remove();
                            popup.remove();
                            <?php if (!isset($this->redirect)) {
                                ?>
                                location.reload();
                                <?php
                            } else {
                                ?>
                                window.location.href = "<?php echo $this->redirect; ?>";
                                <?php
                            }
                            ?>
                        });
                    }

                    var xhr = new XMLHttpRequest();
                    xhr.open('POST', "/root.class.php", true);
                    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                    xhr.onloadstart = function () {
                        var background = document.createElement('div');
                        background.classList.add('background');
                        background.style.position = "fixed";
                        background.style.top = "50%";
                        background.style.left = "50%";
                        background.style.transform = "translate(-50%, -50%)";
                        background.style.width = "20%";
                        background.style.height = "20%";
                        background.style.background = "rgba(255, 255, 255, 0.8)";
                        background.style.borderRadius = "10px";
                        background.style.border = "2px solid #000"
                        background.style.display = "flex";
                        background.style.justifyContent = "center";
                        background.style.alignItems = "center";

                        var style = document.createElement('style');
                        style.innerHTML = `
                            @keyframes loadingAnimation {
                                0% { transform: rotate(0deg); }
                                100% { transform: rotate(360deg); }
                            }
                        `;
                        document.head.appendChild(style);

                        var shape = document.createElement('div');
                        shape.style.width = "30px";
                        shape.style.height = "30px";
                        shape.style.borderRadius = "50%";
                        shape.style.border = "3px solid #fff";
                        shape.style.borderTop = "3px solid #000";
                        shape.style.animation = "loadingAnimation 2s linear infinite";
                        background.appendChild(shape);
                        document.body.appendChild(background);
                    };
                    xhr.onload = function () {
                        var background = document.querySelector('.background');
                        background.remove();
                        if (xhr.status === 200) {
                            if (xhr.responseText == "1" || xhr.responseText == 1) {
                                <?php if ($this->dev_mode == true) { ?>
                                    popup(xhr.responseText);
                                    // alert(xhr.responseText);
                                    console.log(xhr.responseText);
                                <?php } else { ?>
                                    popup("<?php echo $this->on_success; ?>");
                                <?php } ?>
                            } else {
                                <?php if ($this->type == "SELECT") { ?>

                                    document.getElementById("ajax_response").innerHTML = xhr.responseText;
                                    document.getElementById("ajax_response").style.display = "flex";

                                <?php } else { ?>

                                    popup(xhr.responseText);

                                <?php } ?>

                            }
                        } else {
                            popup('Request failed.  Returned status of ' + xhr.status);
                        }
                    };

                    <?php if (is_array($this->return_columns) && count($this->return_columns) > 0) { ?>
                        data["return_columns"] = "<?php echo implode(",", $this->return_columns); ?>";
                    <?php } ?>
                    // Send the data as a URL-encoded string
                    xhr.send(Object.keys(data).map(function (key) {
                        return encodeURIComponent(key) + "=" + encodeURIComponent(data[key]);
                    }).join("&"));
                }
            </script>

            <div id='ajax_response'
                style="display: flex;flex-direction: row;flex-wrap: wrap;justify-content: space-around;align-content: space-around;">
            </div>
            <?php
    }



}

class html
{
    public $idTag;

    function check_session_redirect($session_name, $href_path)
    {
        if (!isset($_SESSION["$session_name"])) {
            echo "<script>window.location.href='$href_path';</script>";
        }
    }

    public function QRrender($idTag)
    {
        $this->idTag = $idTag;
        $idTag = htmlspecialchars($this->idTag, ENT_QUOTES, 'UTF-8');
        ?>
            <div id="scanner-container">
                <button id="start-scanner" class="submit_btn">SCAN</button>
                <div id="reader" style="width: 300px; height: 300px; display: none;">
                    <video id="video" width="300" height="300" style="border: 1px solid black;"></video>
                </div>
            </div>
            <script src="https://cdn.jsdelivr.net/npm/jsqr@1.4.0/dist/jsQR.js"></script>
            <script>
                document.getElementById('start-scanner').addEventListener('click', function () {
                    const scannerElement = document.getElementById('reader');
                    const video = document.getElementById('video');

                    // Make the video element visible
                    scannerElement.style.display = 'block';

                    // Request camera access
                    navigator.mediaDevices.getUserMedia({ video: { facingMode: "environment" } })
                        .then((stream) => {
                            video.srcObject = stream;
                            video.play();

                            // Once the video starts playing, begin scanning for QR codes
                            video.onplay = function () {
                                scanQRCode(video);
                            };
                        })
                        .catch((err) => {
                            console.error("Error accessing webcam:", err);
                        });

                    // Function to scan the QR code
                    function scanQRCode(video) {
                        const canvas = document.createElement("canvas");
                        const context = canvas.getContext("2d");

                        // Set the canvas size to match the video feed
                        canvas.width = video.width;
                        canvas.height = video.height;

                        // Capture the video frame and process it
                        function processFrame() {
                            // Draw the current frame to the canvas
                            context.drawImage(video, 0, 0, canvas.width, canvas.height);

                            // Get the image data from the canvas
                            const imageData = context.getImageData(0, 0, canvas.width, canvas.height);

                            // Invert the colors (black becomes white, white becomes black)
                            invertColors(imageData);

                            // Attempt to decode the QR code from the image data
                            const qrCode = jsQR(imageData.data, canvas.width, canvas.height);

                            // If a QR code is found
                            if (qrCode) {
                                // Insert result into the input field
                                document.getElementById('<?php echo $idTag; ?>').value = qrCode.data;
                                document.getElementById('start-scanner').innerHTML = qrCode.data;
                                alert("Scanned Code: " + qrCode.data);
                                // Stop scanning
                                video.srcObject.getTracks().forEach(track => track.stop());
                                scannerElement.style.display = 'none';
                            } else {
                                // Continue scanning
                                requestAnimationFrame(processFrame);
                            }
                        }

                        // Start processing the video feed
                        processFrame();
                    }

                    // Function to invert the colors of the image
                    function invertColors(imageData) {
                        const data = imageData.data;

                        for (let i = 0; i < data.length; i += 4) {
                            // Invert colors: R, G, B
                            data[i] = 255 - data[i];     // Red
                            data[i + 1] = 255 - data[i + 1]; // Green
                            data[i + 2] = 255 - data[i + 2]; // Blue
                        }

                        // Update the image data
                        imageData.data = data;
                    }
                });
            </script>
            <?php
    }

    public function add_styles_page($file_name = "styles.css")
    {
        $random_number = rand(); // Generates a random integer

        echo "<link rel='stylesheet' href='/styles/$file_name?v.$random_number'>";
    }

    function selectable_block($page_name, $name)
    {
        $name = strtoupper($name);
        echo "<div class='blocks' onclick='window.location.href=\"$page_name\"' >$name</div>";
    }

    function submit_btn($html_name_and_id_tag, $value, $js_function = "", $class = 'submit_btn')
    {
        $name = $html_name_and_id_tag;
        echo "<input type='submit' class='$class' name='$name' id='$name' onclick='$js_function' value='$value'/>";
    }

    function button($html_name_and_id_tag = '', $value, $js_function = "", $class = 'submit_btn')
    {
        $name = $html_name_and_id_tag;
        echo "<button class='$class' value='$value' name='$name' id='$name' onclick='$js_function'>$name</button>";
    }

    function select_html_from_db($table, $option_value_column, $option_name_column, $where_clause = "", $html_name_tag = '', $html_id_tag = "", $css_class_name = "inputs", $css_custom_styles = "", $js_function = "", $special_tags = "", $default_table = '', $default_value_where_clause = "")
    {
        $db = new db_safeguard();

        if (strlen($where_clause) <= 1) {
            $where_clause = "1";
        }

        $results = $db->select_query($table, "$option_value_column,$option_name_column", $where_clause);
        if (is_string($results)) {
            return $results;
        }

        if (strlen($default_value_where_clause) > 1) {
            $res = $db->select_query($default_table, "*", $default_value_where_clause);
            $data = $res->result_assoc();
        }

        $label_name = strtoupper((str_replace("id", "", str_replace("_", " ", $html_name_tag))));
        $html = "<label class='label'>$label_name</label><select id='$html_id_tag' name='$html_name_tag' class='$css_class_name' $special_tags style='$css_custom_styles' $js_function><option></option>";
        while ($row = $results->fetch_assoc()) {
            $html .= "<option value='" . $row[$option_value_column] . "'> " . $row[$option_name_column] . "</option>";
        }
        $html .= "</select><script>document.getElementById('$html_id_tag').value = '" . $data[$option_value_column] . "';</script>";
        return $html;

    }

    function input_html_from_db($table, $value_column_name, $where_clause, $placeholder = '', $html_name_tag = '', $html_id_tag = "", $css_class_name = "inputs", $css_custom_styles = "", $js_function = "", $input_type = 'text', $special_tags = "")
    {
        $db = new db_safeguard();

        if (strlen($where_clause) <= 1) {
            $where_clause = "1";
        }


        $results = $db->select_query($table, "$value_column_name", $where_clause);
        if (is_string($results)) {
            return $results;
        }
        $data = $results->fetch_assoc();



        $returned_value = $data[$value_column_name];

        if ($value_column_name == "password") {
            $auth = new authentication();
            $returned_value = $auth->decrypt_password($returned_value);
        }

        $label_name = strtoupper((str_replace("id", "", str_replace("_", " ", $html_name_tag))));

        $html = "<label $special_tags class='label'>$label_name</label><input type='$input_type' id='$html_id_tag' name='$html_name_tag' placeholder='$placeholder'  class='$css_class_name' style='$css_custom_styles' $js_function value='" . $returned_value . "' $special_tags/>";
        return $html;
    }

    function input_html($placeholder = '', $value = '', $html_name_tag = '', $html_id_tag = "", $css_class_name = "inputs", $css_custom_styles = "", $js_function = "", $input_type = 'text', $special_tags = "")
    {
        $label_name = strtoupper((str_replace("id", "", str_replace("_", " ", $html_name_tag))));
        $html = "<label $special_tags class='label'>$label_name</label><input type='$input_type' id='$html_id_tag' name='$html_name_tag' placeholder='$placeholder' class='$css_class_name' style='$css_custom_styles' $js_function value='" . $value . "' $special_tags/>";
        return $html;
    }

    function date_input_html_from_db($table, $value_column_name, $where_clause, $html_id_tag = '', $html_name_tag = '', $input_class = 'inputs', $input_style = '', $js_function = '', $special_tags = '')
    {
        $db = new db_safeguard();

        if (strlen($where_clause) <= 1) {
            $where_clause = "1";
        }

        $results = $db->select_query($table, "$value_column_name", $where_clause);
        if (is_string($results)) {
            return $results;
        }
        $data = $results->fetch_assoc();

        $returned_value = $data[$value_column_name];
        $label_name = strtoupper((str_replace("id", "", str_replace("_", " ", str_replace("date", "", str_replace("time", "", $html_name_tag))))));
        $html = "<label class='label'>$label_name</label><input type='datetime-local' id='$html_id_tag' name='$html_name_tag' class='$input_class' style='$input_style' $js_function value='$returned_value' $special_tags/>";
        return $html;
    }

    function date_input_html($html_id_tag = '', $html_name_tag = '', $input_class = 'inputs', $input_style = '', $input_value = '', $js_function = '', $special_tags = '')
    {
        $label_name = strtoupper((str_replace("id", "", str_replace("_", " ", str_replace("date", "", str_replace("time", "", $html_name_tag))))));
        $html = "<label class='label' $special_tags>$label_name</label><input type='datetime-local' id='$html_id_tag' name='$html_name_tag' class='$input_class' style='$input_style' $js_function value='" . $input_value . "' $special_tags/>";
        return $html;
    }

    function file_upload_html($input_id = '', $input_name = '', $input_class = 'inputs', $input_style = '', $js_function = '', $special_tags = '')
    {
        $html = "<input type='file' id='$input_id' name='$input_name' class='$input_class' style='$input_style' $js_function ,$special_tags/>";

        // js code for ajax root.class.php

        ?>

            <script>

                var form = document.getElementById("file");

                form.addEventListener("change", function () {
                    var file = form.files[0];
                    var xhr = new XMLHttpRequest();
                    xhr.open("POST", "/upload.php", true);
                    xhr.send(file);
                });
            </script>

            <?php

            return $html;
    }

    function html_form_ajax($function_name, $type, $table_name, $where_clause = '', $dev_mode = false, $return_columns = [], $edit_file_name = "", $list_of_ids_for_text_formators = [], $excloded_colum_names = '', $add_column_and_value = '')
    {
        ?>
            <script>
                function <?php echo $function_name; ?>() {

                    document.getElementById("submit").disabled = true;
                    document.getElementById("submit").value = "LOADING...";

                    var data = {};
                    var inputs = document.querySelectorAll(".form_down input, .form_down select, .form_down textarea, .search_form_top input, .search_form_top select, .search_form_top textarea, .search_form input, .search_form select, .search_form textarea");
                    inputs.forEach(function (input) {
                        if (input.value != "") {
                            if (input.id.includes("date_time")) {
                                data[input.id] = input.value.replace("T", " ");
                            } else {
                                data[input.id] = input.value;
                            }
                        }
                    });
                    data["ajax_type"] = "<?php echo $type; ?>";
                    data["table_name"] = "<?php echo $table_name; ?>";
                    data["where_clause"] = "<?php echo $where_clause; ?>";
                    data["edit_file_name"] = "<?php echo $edit_file_name; ?>";
                    data["excloded_colum_names"] = "<?php echo $excloded_colum_names; ?>";
                    data["add_column_and_value"] = "<?php echo $add_column_and_value; ?>";

                    <?php
                    foreach ($list_of_ids_for_text_formators as $list_of_id) {
                        ?> data["<?php echo $list_of_id; ?>"] = document.getElementById("<?php echo $list_of_id; ?>").innerHTML;

                        data = Object.keys(data).filter(key => !key.startsWith('imageInput_<?php echo $list_of_id; ?>')).reduce((obj, key) => {
                            obj[key] = data[key];
                            return obj;
                        }, {});
                        <?php
                    }
                    ?>



                    var xhr = new XMLHttpRequest();
                    xhr.open('POST', "/root.class.php", true);
                    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                    xhr.onload = function () {
                        document.getElementById("submit").disabled = false;
                        document.getElementById("submit").value = "SEARCH";
                        if (xhr.status === 200) {
                            <?php if ($dev_mode == true) { ?>
                                alert(xhr.responseText);
                                console.log(xhr.responseText);
                            <?php } elseif ($type == "SELECT") { ?>
                                document.getElementById("ajax_response").innerHTML = xhr.responseText;
                                document.getElementById("ajax_response").style.display = "flex";
                                // location.reload();
                            <?php } else { ?>
                                location.reload();
                            <?php } ?>
                        }
                        else {
                            alert('Request failed.  Returned status of ' + xhr.status);
                        }
                    };
                    data["return_columns"] = "<?php echo implode(",", $return_columns); ?>";
                    // Send the data as a URL-encoded string
                    xhr.send(Object.keys(data).map(function (key) {
                        return encodeURIComponent(key) + "=" + encodeURIComponent(data[key]);
                    }).join("&"));
                }
            </script>

            <div id='ajax_response'
                style="display: flex;flex-direction: row;flex-wrap: wrap;justify-content: space-around;align-content: space-around;">
            </div><?php
    }

    function check_user_type($user_type, $redirect_or_return_bool = true)
    {
        $db = new db_safeguard();
        $sql = "SELECT * FROM users WHERE `record_id` = {$_SESSION['user_id']} AND (`user_type` = '$user_type' OR `user_type` = 'ADMIN')";
        $result = $db->query('users', $sql);

        if ($redirect_or_return_bool) {
            if ($result->num_rows < 1) {
                echo "<script>alert('unauthorized access');window.location.href = '/home.php';</script>";
            }
        } else {
            if ($result->num_rows < 1) {
                return false;
            } else {
                return true;
            }
        }
    }

    function select_from_db_add_current_selected_column($table_name = '', $column_name_to_display = '', $where_clause = '', $html_select_id_tag_to_change = '')
    {

        $db = new db_safeguard();

        $result = $db->select_query($table_name, $column_name_to_display, $where_clause);
        $data = $result->fetch_assoc();

        return "<script>document.getElementById('$html_select_id_tag_to_change').value = '" . $data[$column_name_to_display] . "';</script>";

    }

    function text_formator($content_id_html_tag = '')
    {

        ?>

            <style>
                h1 {
                    margin: 0;
                }

                .controls {
                    background-color: #fff;
                    padding: 10px 20px;
                    border-bottom: 1px solid #ddd;
                    display: flex;
                    justify-content: flex-start;
                    align-items: center;
                    gap: 10px;
                    flex-wrap: wrap;
                }

                .controls button,
                .controls input {
                    padding: 8px 15px;
                    font-size: 16px;
                    border: 1px solid #ddd;
                    border-radius: 4px;
                    cursor: pointer;
                    background-color: #f4f7fa;
                }

                .controls button:hover,
                .controls input:hover {
                    background-color: #e0e0e0;
                }

                .controls input[type="file"] {
                    display: none;
                }

                <?php echo "#" . $content_id_html_tag; ?>
                    {
                    background-color: #fff;
                    border: 1px solid #ddd;
                    padding: 20px;
                    margin: 20px 0;
                    min-height: 200px;
                    box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
                    border-radius: 4px;
                }

                <?php echo "#" . $content_id_html_tag; ?>
                img {
                    max-width: 100%;
                    height: auto;
                    border-radius: 4px;
                }

                .content {
                    max-width: 900px;
                    margin: 20px auto;
                    padding: 20px;
                    background-color: #fff;
                    border-radius: 6px;
                    box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);
                }

                .controls button,
                .controls input {
                    margin-right: 10px;
                }

                .controls input[type="file"] {
                    display: none;
                }
            </style>

            <div class="content">
                <div id="<?php echo $content_id_html_tag; ?>" contenteditable="true">
                </div>
                <div class="controls">
                    <button onclick="formatText_<?php echo $content_id_html_tag; ?>('bold')">Bold</button>
                    <button onclick="formatText_<?php echo $content_id_html_tag; ?>('italic')">Italic</button>
                    <button onclick="formatText_<?php echo $content_id_html_tag; ?>('underline')">Underline</button>
                    <button onclick="formatText_<?php echo $content_id_html_tag; ?>('formatBlock', 'h1')">Heading 1</button>
                    <button onclick="formatText_<?php echo $content_id_html_tag; ?>('formatBlock', 'h2')">Heading 2</button>
                    <button onclick="formatText_<?php echo $content_id_html_tag; ?>('formatBlock', 'h3')">Heading 3</button>
                    <button onclick="formatText_<?php echo $content_id_html_tag; ?>('formatBlock', 'p')">Normal
                        Font</button>
                </div>
            </div>


            <script>
                // Format the text (bold, italic, underline, headings)
                function formatText_<?php echo $content_id_html_tag; ?>(command, value = null) {
                    if (value) {
                        document.execCommand(command, false, value); // Used for headings (e.g., h1, h2, h3) or normal font
                    } else {
                        document.execCommand(command, false, null); // For other text formatting like bold, italic, etc.
                    }
                }
            </script>
            <?php

    }

    function image($content_id_html_tag = '')
    {
        ?>

            <style>
                h1 {
                    margin: 0;
                }

                .controls {
                    background-color: #fff;
                    padding: 10px 20px;
                    border-bottom: 1px solid #ddd;
                    display: flex;
                    justify-content: flex-start;
                    align-items: center;
                    gap: 10px;
                    flex-wrap: wrap;
                }

                .controls button,
                .controls input {
                    padding: 8px 15px;
                    font-size: 16px;
                    border: 1px solid #ddd;
                    border-radius: 4px;
                    cursor: pointer;
                    background-color: #f4f7fa;
                }

                .controls button:hover,
                .controls input:hover {
                    background-color: #e0e0e0;
                }

                <?php echo "#" . $content_id_html_tag; ?>
                    {
                    background-color: #fff;
                    border: 1px solid #ddd;
                    padding: 20px;
                    margin: 20px 0;
                    min-height: 200px;
                    box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
                    border-radius: 4px;
                }

                <?php echo "#" . $content_id_html_tag; ?>
                img {
                    max-width: 100%;
                    height: auto;
                    border-radius: 4px;
                }

                .content {
                    border: 3px solid grey;
                    /* max-width: 90%; */
                    width: 80%;
                    height: fit-content;
                    margin: 20px auto;
                    padding: 20px;
                    background-color: #fff;
                    border-radius: 1vw;
                    box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);
                }

                .controls input[type="file"] {
                    display: none;
                }
            </style>

            <div class="content">
                <div id="<?php echo $content_id_html_tag; ?>" style="display:none;" contenteditable="true"></div>
                <div class="controls">
                    <input type="file" id="imageInput_<?php echo $content_id_html_tag; ?>" accept="image/*"
                        onchange="compressAndInsertImage_<?php echo $content_id_html_tag; ?>()" hidden>
                    <button
                        onclick="document.getElementById('<?php echo $content_id_html_tag; ?>').style.display = 'block';document.getElementById('imageInput_<?php echo $content_id_html_tag; ?>').click();">Add
                        Image</button>
                </div>
            </div>

            <script>
                async function compressBase64Image(base64Data, quality = 0.7, maxWidth = 800, maxHeight = 800) {
                    return new Promise((resolve, reject) => {
                        const img = new Image();
                        img.src = base64Data;

                        img.onload = () => {
                            let width = img.width;
                            let height = img.height;

                            if (width > maxWidth || height > maxHeight) {
                                const aspectRatio = width / height;
                                if (width > height) {
                                    width = maxWidth;
                                    height = Math.round(maxWidth / aspectRatio);
                                } else {
                                    height = maxHeight;
                                    width = Math.round(maxHeight * aspectRatio);
                                }
                            }

                            const canvas = document.createElement("canvas");
                            canvas.width = width;
                            canvas.height = height;
                            const ctx = canvas.getContext("2d");

                            ctx.drawImage(img, 0, 0, width, height);

                            const compressedBase64 = canvas.toDataURL("image/jpeg", quality);
                            resolve(compressedBase64);
                        };

                        img.onerror = () => reject(new Error("Invalid base64 image data."));
                    });
                }

                async function compressAndInsertImage_<?php echo $content_id_html_tag; ?>() {
                    const input = document.getElementById('imageInput_<?php echo $content_id_html_tag; ?>');
                    const file = input.files[0];

                    if (!file) return;

                    const reader = new FileReader();
                    reader.onload = async function (e) {
                        const originalBase64 = e.target.result;

                        try {
                            const compressedBase64 = await compressBase64Image(originalBase64, 0.7);

                            const compressedImg = document.createElement('img');
                            compressedImg.src = compressedBase64;

                            const output = document.getElementById('<?php echo $content_id_html_tag; ?>');
                            output.appendChild(compressedImg);
                        } catch (error) {
                            console.error("Compression failed:", error.message);
                        }
                    };

                    reader.onerror = function () {
                        console.error('FileReader failed to read file.');
                    };

                    reader.readAsDataURL(file);
                }
            </script>


            <?php
    }

    function text_formator_from_db($content_id_html_tag = '', $table_name = '', $column_name_to_display = '', $where_clause = '')
    {

        ?>

            <style>
                h1 {
                    margin: 0;
                }

                .controls {
                    background-color: #fff;
                    padding: 10px 20px;
                    border-bottom: 1px solid #ddd;
                    display: flex;
                    justify-content: flex-start;
                    align-items: center;
                    gap: 10px;
                    flex-wrap: wrap;
                }

                .controls button,
                .controls input {
                    padding: 8px 15px;
                    font-size: 16px;
                    border: 1px solid #ddd;
                    border-radius: 4px;
                    cursor: pointer;
                    background-color: #f4f7fa;
                }

                .controls button:hover,
                .controls input:hover {
                    background-color: #e0e0e0;
                }

                .controls input[type="file"] {
                    display: none;
                }

                <?php echo "#" . $content_id_html_tag; ?>
                    {
                    background-color: #fff;
                    border: 1px solid #ddd;
                    padding: 20px;
                    margin: 20px 0;
                    min-height: 200px;
                    box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
                    border-radius: 4px;
                }

                <?php echo "#" . $content_id_html_tag; ?>
                img {
                    max-width: 100%;
                    height: auto;
                    border-radius: 4px;
                }

                .content {
                    border: 3px solid grey;
                    /* max-width: 90%; */
                    width: 40%;
                    height: fit-content;
                    margin: 20px auto;
                    padding: 20px;
                    background-color: #fff;
                    border-radius: 1vw;
                    box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);

                }

                .controls button,
                .controls input {
                    margin-right: 10px;
                }

                .controls input[type="file"] {
                    display: none;
                }
            </style>

            <div class="content">

                <div id="<?php echo $content_id_html_tag; ?>" contenteditable="true">
                    <?php
                    $db = new db_safeguard();

                    $res = $db->select_query($table_name, $column_name_to_display, $where_clause);
                    $data = $res->fetch_assoc();
                    echo $data[$column_name_to_display];
                    ?>
                </div>
                <div class="controls">
                    <button onclick="formatText_<?php echo $content_id_html_tag; ?>('bold')">Bold</button>
                    <button onclick="formatText_<?php echo $content_id_html_tag; ?>('italic')">Italic</button>
                    <button onclick="formatText_<?php echo $content_id_html_tag; ?>('underline')">Underline</button>
                    <button onclick="formatText_<?php echo $content_id_html_tag; ?>('formatBlock', 'h1')">Heading 1</button>
                    <button onclick="formatText_<?php echo $content_id_html_tag; ?>('formatBlock', 'h2')">Heading 2</button>
                    <button onclick="formatText_<?php echo $content_id_html_tag; ?>('formatBlock', 'h3')">Heading 3</button>
                    <button onclick="formatText_<?php echo $content_id_html_tag; ?>('formatBlock', 'p')">Normal
                        Font</button>

                </div>

            </div>


            <script>
                // Format the text (bold, italic, underline, headings)
                function formatText_<?php echo $content_id_html_tag; ?>(command, value = null) {
                    if (value) {
                        document.execCommand(command, false, value); // Used for headings (e.g., h1, h2, h3) or normal font
                    } else {
                        document.execCommand(command, false, null); // For other text formatting like bold, italic, etc.
                    }
                }
            </script>
            <?php

    }

    function image_from_db($content_id_html_tag = '', $table_name = '', $column_name_to_display = '', $where_clause = '')
    {

        ?>

            <style>
                h1 {
                    margin: 0;
                }

                .controls {
                    background-color: #fff;
                    padding: 10px 20px;
                    border-bottom: 1px solid #ddd;
                    display: flex;
                    justify-content: flex-start;
                    align-items: center;
                    gap: 10px;
                    flex-wrap: wrap;
                }

                .controls button,
                .controls input {
                    padding: 8px 15px;
                    font-size: 16px;
                    border: 1px solid #ddd;
                    border-radius: 4px;
                    cursor: pointer;
                    background-color: #f4f7fa;
                }

                .controls button:hover,
                .controls input:hover {
                    background-color: #e0e0e0;
                }

                .controls input[type="file"] {
                    display: none;
                }

                <?php echo "#" . $content_id_html_tag; ?>
                    {
                    background-color: #fff;
                    border: 1px solid #ddd;
                    padding: 20px;
                    margin: 20px 0;
                    min-height: 200px;
                    box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
                    border-radius: 4px;
                }

                <?php echo "#" . $content_id_html_tag; ?>
                img {
                    max-width: 100%;
                    height: auto;
                    border-radius: 4px;
                }

                .content {
                    border: 3px solid grey;
                    /* max-width: 90%; */
                    width: 40%;
                    height: fit-content;
                    margin: 20px auto;
                    padding: 20px;
                    background-color: #fff;
                    border-radius: 1vw;
                    box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);

                }

                .controls button,
                .controls input {
                    margin-right: 10px;
                }

                .controls input[type="file"] {
                    display: none;
                }
            </style>

            <div class="content">
                <div id="<?php echo $content_id_html_tag; ?>" contenteditable="true">
                    <?php
                    $db = new db_safeguard();

                    $res = $db->select_query($table_name, $column_name_to_display, $where_clause);
                    $data = $res->fetch_assoc();
                    echo $data[$column_name_to_display];
                    ?>
                </div>
                <div class="controls">
                    <input type="file" id="imageInput_<?php echo $content_id_html_tag; ?>" accept="image/*"
                        onchange="insertImage_<?php echo $content_id_html_tag; ?>()" hidden>
                    <button onclick="document.getElementById('imageInput_<?php echo $content_id_html_tag; ?>').click()">Add
                        Image</button>

                </div>
            </div>


            <script>
                // Insert an image
                function insertImage_<?php echo $content_id_html_tag; ?>() {
                    const input = document.getElementById('imageInput_<?php echo $content_id_html_tag; ?>');
                    const file = input.files[0];

                    if (file) {
                        const reader = new FileReader();

                        reader.onload = function (e) {
                            const img = document.createElement('img');
                            img.src = e.target.result;
                            const output = document.getElementById('<?php echo $content_id_html_tag; ?>');
                            output.appendChild(img);
                        };

                        reader.readAsDataURL(file);
                    }
                }
            </script>
            <?php

    }

    function complete_text_editor($content_id_html_tag = '', $table_name = '', $column_name_to_display = '', $where_clause = '')
    {

        ?>

            <style>
                h1 {
                    margin: 0;
                }

                .controls {
                    background-color: #fff;
                    padding: 10px 20px;
                    border-bottom: 1px solid #ddd;
                    display: flex;
                    justify-content: flex-start;
                    align-items: center;
                    gap: 10px;
                    flex-wrap: wrap;
                }

                .controls button,
                .controls input {
                    padding: 8px 15px;
                    font-size: 16px;
                    border: 1px solid #ddd;
                    border-radius: 4px;
                    cursor: pointer;
                    background-color: #f4f7fa;
                }

                .controls button:hover,
                .controls input:hover {
                    background-color: #e0e0e0;
                }

                .controls input[type="file"] {
                    display: none;
                }

                <?php echo "#" . $content_id_html_tag; ?>
                    {
                    background-color: #fff;
                    border: 1px solid #ddd;
                    padding: 20px;
                    margin: 20px 0;
                    min-height: 200px;
                    box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
                    border-radius: 4px;
                }

                <?php echo "#" . $content_id_html_tag; ?>
                img {
                    max-width: 100%;
                    height: auto;
                    border-radius: 4px;
                }

                .content {
                    border: 3px solid grey;
                    /* max-width: 90%; */
                    width: 80%;
                    height: fit-content;
                    margin: 20px auto;
                    padding: 20px;
                    background-color: #fff;
                    border-radius: 1vw;
                    box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);
                }

                .controls button,
                .controls input {
                    margin-right: 10px;
                }

                .controls input[type="file"] {
                    display: none;
                }
            </style>

            <div class="content">


                <div id="<?php echo $content_id_html_tag; ?>" contenteditable="true">
                    <?php
                    if ($table_name != "") {
                        $db = new db_safeguard();

                        $res = $db->select_query($table_name, $column_name_to_display, $where_clause);
                        $data = $res->fetch_assoc();
                        echo $data[$column_name_to_display];
                    }
                    ?>
                </div>
                <div class="controls">
                    <button onclick="formatText_<?php echo $content_id_html_tag; ?>('bold')">Bold</button>
                    <button onclick="formatText_<?php echo $content_id_html_tag; ?>('italic')">Italic</button>
                    <button onclick="formatText_<?php echo $content_id_html_tag; ?>('underline')">Underline</button>
                    <button onclick="formatText_<?php echo $content_id_html_tag; ?>('formatBlock', 'h1')">Heading 1</button>
                    <button onclick="formatText_<?php echo $content_id_html_tag; ?>('formatBlock', 'h2')">Heading 2</button>
                    <button onclick="formatText_<?php echo $content_id_html_tag; ?>('formatBlock', 'h3')">Heading 3</button>
                    <button onclick="formatText_<?php echo $content_id_html_tag; ?>('formatBlock', 'p')">Normal
                        Font</button>
                    <input type="file" id="imageInput_<?php echo $content_id_html_tag; ?>" accept="image/*"
                        onchange="insertImage_<?php echo $content_id_html_tag; ?>()" hidden>
                    <button onclick="document.getElementById('imageInput_<?php echo $content_id_html_tag; ?>').click()">Add
                        Image</button>

                </div>
            </div>


            <script>
                // Format the text (bold, italic, underline, headings)
                function formatText_<?php echo $content_id_html_tag; ?>(command, value = null) {
                    if (value) {
                        document.execCommand(command, false, value); // Used for headings (e.g., h1, h2, h3) or normal font
                    } else {
                        document.execCommand(command, false, null); // For other text formatting like bold, italic, etc.
                    }
                }

                // Insert an image
                function insertImage_<?php echo $content_id_html_tag; ?>() {
                    const input = document.getElementById('imageInput_<?php echo $content_id_html_tag; ?>');
                    const file = input.files[0];

                    if (file) {
                        const reader = new FileReader();

                        reader.onload = function (e) {
                            const img = document.createElement('img');
                            img.src = e.target.result;
                            const output = document.getElementById('<?php echo $content_id_html_tag; ?>');
                            output.appendChild(img);
                        };

                        reader.readAsDataURL(file);
                    }
                }
            </script>

            <?php

    }

}

class db_safeguard
{

    private $connection;
    private $sql;
    private $table_name;

    public function __construct($host = "elegantwork.co.za", $user = 'elegaysv_Code2', $password = 'EWG2Cod!@#', $dbname = 'elegaysv_systems')
    {
        $this->connection = mysqli_connect($host, $user, $password, $dbname);

        if (!$this->check_table_exists('logs')) {
            $sql = "CREATE TABLE IF NOT EXISTS logs (
                record_id INT AUTO_INCREMENT PRIMARY KEY,
                table_name TEXT,
                user_id INT(255),
                query TEXT,
                date_time VARCHAR(50)
            )";

            if (!mysqli_query($this->connection, $sql)) {
                return "Error creating table: " . mysqli_error($this->connection);
                exit();
            }
        }

        if (!$this->check_table_exists('users')) {
            $sql = "CREATE TABLE IF NOT EXISTS users (
                record_id INT AUTO_INCREMENT PRIMARY KEY,
                username TEXT,
                user_password TEXT
            )";

            if (!mysqli_query($this->connection, $sql)) {
                return "Error creating table: " . mysqli_error($this->connection);
                exit();
            }

            $sql = "INSERT INTO users (username, user_password) VALUES ('DEV', '4030fe15babb7045f9036c2316babda746af34b61e623354c61828526c4e2ad5')";

            if (!mysqli_query($this->connection, $sql)) {
                return "Error inserting first user: " . mysqli_error($this->connection);
                exit();
            }
        }

        if (mysqli_connect_errno()) {
            return "Failed to connect to MySQL: " . mysqli_connect_error();
            exit();
        }

    }

    function session_check()
    {
        if (strlen($_SESSION["user_id"]) >= 1) {
            return $_SESSION["user_id"];
        } else {
            return 0;
        }
    }

    /**
     * Logs in a user with the given username and password.
     *
     * @param string $username The username to log in with.
     * @param string $password The password to log in with.
     *
     * @return int 1 if the login was successful, 0 otherwise.
     */
    function login($username, $password)
    {
        $hash_pass = hash("SHA256", $password);
        $sql = "SELECT * FROM users WHERE username = '$username' AND user_password = '$hash_pass'";
        $result = mysqli_query($this->connection, $sql);
        if (mysqli_num_rows($result) > 0) {
            $row = mysqli_fetch_assoc($result);
            $_SESSION["user_id"] = $row["record_id"];
            $_SESSION["database_log"] = "hello";

            return 1;
        } else {
            return "0";
        }
    }

    function check_table_exists($table)
    {
        $this->table_name = $table;
        $sql = "SHOW TABLES LIKE '$table' ";
        $result = mysqli_query($this->connection, $sql);

        if (mysqli_num_rows($result) > 0) {

            return true;

        } else {

            return false;

        }
    }

    public function select_query($table_name, $selector, $where_clause)
    {

        $this->sql = "SELECT $selector FROM $table_name WHERE $where_clause";

        if (!$this->check_table_exists($table_name)) {

            echo "[SQL] TABLE NAME DOES NOT EXIST OR IS INCORRECT $table_name";
            echo "[SQL QUERY FAILED]" . mysqli_error($this->connection) . "<br>";
            echo "[SQL QUERY]: " . $this->sql;

        }

        $result = mysqli_query($this->connection, $this->sql);


        if (mysqli_error($this->connection)) {

            echo "[SQL QUERY FAILED]" . mysqli_error($this->connection) . "<br>";
            echo "[SQL QUERY]: " . $this->sql;
            exit();
        } else {

            return $result;

        }
    }

    public function query($table_name, $sql)
    {
        $this->sql = $sql;
        $this->table_name = $table_name;
        if (!$this->check_table_exists($table_name)) {
            echo "[SQL] TABLE NAME DOES NOT EXIST OR IS INCORRECT $table_name";
        }
        $result = mysqli_query($this->connection, $this->sql);

        if (mysqli_error($this->connection)) {
            echo "[SQL QUERY FAILED] on " . $_SERVER['REQUEST_URI'] . " at line " . __LINE__ . ": " . mysqli_error($this->connection) . "<br>";
            echo "[SQL QUERY]: " . $sql;
            exit();
        } else {
            if (stripos(trim($sql), 'INSERT') === 0) {
                return mysqli_insert_id($this->connection);
            } else {
                return $result;
            }
        }
    }

    public function __destruct()
    {

        if (strlen($this->sql) > 1) {
            if (stripos(trim($this->sql), 'SELECT') !== 0) {
                $log_sql = "INSERT INTO logs (`table_name`,`user_id`,`query`,`date_time`) VALUES (\"$this->table_name\", \"{$_SESSION['user_id']}\", \"$this->sql\", NOW())";
                $_SESSION["database_log"];
                mysqli_query($this->connection, $log_sql);
            }
        }
        mysqli_close($this->connection);
    }
}

class authentication
{
    public $key;

    function __construct()
    {
        $this->key = "password";
    }
    function encrypt_password($password)
    {
        $cipher = "AES-256-CBC"; // Encryption cipher
        $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher)); // Generate IV
        $encrypted = openssl_encrypt($password, $cipher, $this->key, 0, $iv); // Encrypt the password

        // Combine encrypted password and IV for storage
        return base64_encode($encrypted . "::" . $iv);
    }

    function decrypt_password($encryptedPassword)
    {
        $cipher = "AES-256-CBC";
        list($encryptedData, $iv) = explode("::", base64_decode($encryptedPassword), 2);

        return openssl_decrypt($encryptedData, $cipher, $this->key, 0, $iv);
    }
}

class ajax
{
    function upload($file)
    {
        $target_dir = "/";
        $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
            echo "The file " . htmlspecialchars(basename($_FILES["fileToUpload"]["name"])) . " has been uploaded.";
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }

    function insert()
    {
        $table_name = $_POST['table_name'];
        $edit_file_name = $_POST['edit_file_name'];
        $returned_cols = explode(",", $_POST['return_columns']);
        $add_column_and_value = explode(",", $_POST['add_column_and_value']);
        if (count($add_column_and_value) > 0) {
            foreach ($add_column_and_value as $add_column_and_value) {
                $add_column_and_value = explode("=", $add_column_and_value);
                $_POST[$add_column_and_value[0]] = $add_column_and_value[1];
            }
        }
        $excloudedcolumns = explode(',', $_POST['excloded_colum_names']);
        if (count($excloudedcolumns) > 0) {
            foreach ($excloudedcolumns as $excloudedcolumn) {
                unset($_POST[$excloudedcolumn]);
            }
        }
        unset($_POST['excloded_colum_names']);
        unset($_POST['add_column_and_value']);
        unset($_POST['return_columns']);
        unset($_POST['edit_file_name']);
        unset($_POST['ajax_type']);
        unset($_POST['table_name']);
        unset($_POST['where_clause']);
        unset($_POST['submit']);

        if (isset($_POST['password'])) {
            $auth = new authentication();
            $_POST['password'] = $auth->encrypt_password($_POST['password']);
        }

        if (isset($_POST['user_password'])) {
            $_POST['user_password'] = hash('SHA256', $_POST['user_password']);
        }

        $columns = array_keys($_POST);
        $values = array_values($_POST);

        $columns_string = "`" . implode("` , `", $columns) . "`";
        $values_string = "'" . implode("','", $values) . "'";

        $sql = "INSERT INTO $table_name ($columns_string) VALUES ($values_string)";
        $db = new db_safeguard();
        $res = $db->query($table_name, $sql);
        if ($res > 0) {
            return 1;
        } else {
            return $res;
        }

    }

    function delete()
    {
        $table_name = $_POST['table_name'];
        $record_id = $_POST['record_id'];

        $sql = "DELETE FROM $table_name WHERE record_id = $record_id";
        $db = new db_safeguard();
        $res = $db->query($table_name, $sql);
        if ($res > 0) {
            return 1;
        } else {
            return $res;
        }

    }

    function select()
    {
        $table_name = $_POST['table_name'];
        $edit_file_name = $_POST['edit_file_name'];
        $returned_cols = explode(",", $_POST['return_columns']);
        $add_column_and_value = explode(",", $_POST['add_column_and_value']);
        if (count($add_column_and_value) > 0) {
            foreach ($add_column_and_value as $add_column_and_value) {
                $add_column_and_value = explode("=", $add_column_and_value);
                $_POST[$add_column_and_value[0]] = $add_column_and_value[1];
            }
        }
        $excloudedcolumns = explode(',', $_POST['excloded_colum_names']);
        if (count($excloudedcolumns) > 0) {
            foreach ($excloudedcolumns as $excloudedcolumn) {
                unset($_POST[$excloudedcolumn]);
            }
        }
        unset($_POST['excloded_colum_names']);
        unset($_POST['add_column_and_value']);
        unset($_POST['return_columns']);
        unset($_POST['edit_file_name']);
        unset($_POST['ajax_type']);
        unset($_POST['table_name']);
        unset($_POST['where_clause']);
        unset($_POST['submit']);

        $columns = array_keys($_POST);
        $values = array_values($_POST);

        $conditions = [];
        foreach ($columns as $key => $value) {

            if (strlen($values[$key]) >= 1) {
                if (strpos($columns[$key], '_id') !== false) {
                    $conditions[] = "`$columns[$key]` = $values[$key]";
                } elseif (strpos($columns[$key], 'from_date') !== false) {
                    foreach ($columns[$key] as $key2 => $value2) {
                        if (strpos($columns[$key2], 'to_date') !== false) {
                            $to_Date = $columns[$key2];
                        }
                    }
                    if ($to_date_key !== false) {
                        $conditions[] = "`$columns[$key]` BETWEEN '$values[$key]' AND '$to_Date'";
                    }
                } else {
                    $conditions[] = "`$columns[$key]` LIKE '%$values[$key]%'";
                }
            }

        }

        if (count($conditions) < 1) {
            $conditions[] = "1";
        }

        $conditions_string = implode(" AND ", $conditions);


        $sql = "SELECT * FROM $table_name WHERE $conditions_string";
        $db = new db_safeguard();

        $result = $db->select_query($table_name, '*', $conditions_string);

        // return json_encode($data);

        while ($data = $result->fetch_assoc()) {


            $html .= "
                <div class='searched_data'>";

            foreach ($returned_cols as $column) {

                $label_name = strtoupper((str_replace("id", "", str_replace("_", " ", str_replace("date", "", str_replace("time", "", $column))))));

                if (strpos($column, '_id') !== false) {
                    $possible_table_name = $table_name . "_" . str_replace("_id", "", $column);
                    if ($db->check_table_exists($possible_table_name)) {
                        try {
                            $results_for_data = $db->select_query($possible_table_name, 'name', "record_id = $data[$column]");
                            $other_data = $results_for_data->fetch_assoc();
                            $html .= "<div class='group_div'><label class='label'> $label_name </label><textarea type='text' class='inputs' readonly >" . $other_data['name'] . "</textarea></div>";
                        } catch (Exception $e) {
                            $results_for_data = $db->select_query($possible_table_name, 'username', "record_id = $data[$column]");
                            $other_data = $results_for_data->fetch_assoc();
                            $html .= "<div class='group_div'><label class='label'> $label_name </label><textarea type='text' class='inputs' readonly >" . $other_data['username'] . "</textarea></div>";
                        }
                    } else {

                        $possible_table_name = substr($table_name, 0, -1) . "_" . str_replace("_id", "", $column);
                        if (substr($possible_table_name, -1) !== 's') {
                            $possible_table_name .= 's';
                        }
                        if ($db->check_table_exists($possible_table_name)) {
                            $results_for_data = $db->select_query($possible_table_name, 'name', "record_id = $data[$column]");
                            $other_data = $results_for_data->fetch_assoc();
                            $html .= "<div class='group_div'><label class='label'> $label_name </label><textarea type='text' class='inputs' readonly >" . $other_data['name'] . "</textarea></div>";
                        } else {
                            $possible_table_name = str_replace("_id", "", $column);
                            if (substr($possible_table_name, -1) !== 's') {
                                $possible_table_name .= 's';
                            }
                            if ($db->check_table_exists($possible_table_name)) {
                                $results_for_data = $db->select_query($possible_table_name, 'name', "record_id = $data[$column]");
                                $other_data = $results_for_data->fetch_assoc();
                                $html .= "<div class='group_div'><label class='label'> $label_name </label><textarea type='text' class='inputs' readonly >" . $other_data['name'] . "</textarea></div>";

                            } else {
                                $html .= "<div class='group_div'><label class='label'> $label_name </label><textarea type='text' class='inputs' readonly > NO TABLE FOUND $possible_table_name PLEASE MAKE SURE THAT THE TABLE IS NAMED CORRECTLY AND THERE IS A NAME COLUMN IN THE TABLE</textarea></div>";

                            }

                        }
                    }

                } else {
                    $html .= "<div class='group_div'><label class='label'> $label_name </label><textarea type='text' class='inputs' readonly >" . $data[$column] . "</textarea></div>";
                }
            }
            $html .= "<input type='submit' value='EDIT' class='submit_btn' onclick='window.location.href=\"$edit_file_name?record_id=" . $data['record_id'] . "\"'/>";
            $html .= " </div>
            ";
        }

        return "$html";

    }

    function project_reports()
    {
        $table_name = $_POST['table_name'];
        $edit_file_name = $_POST['edit_file_name'];
        $returned_cols = explode(",", $_POST['return_columns']);
        $add_column_and_value = explode(",", $_POST['add_column_and_value']);
        if (count($add_column_and_value) > 0) {
            foreach ($add_column_and_value as $add_column_and_value) {
                $add_column_and_value = explode("=", $add_column_and_value);
                $_POST[$add_column_and_value[0]] = $add_column_and_value[1];
            }
        }
        $excloudedcolumns = explode(',', $_POST['excloded_colum_names']);
        if (count($excloudedcolumns) > 0) {
            foreach ($excloudedcolumns as $excloudedcolumn) {
                unset($_POST[$excloudedcolumn]);
            }
        }
        unset($_POST['excloded_colum_names']);
        unset($_POST['add_column_and_value']);
        unset($_POST['return_columns']);
        unset($_POST['edit_file_name']);
        unset($_POST['ajax_type']);
        unset($_POST['table_name']);
        unset($_POST['where_clause']);
        unset($_POST['submit']);

        $columns = array_keys($_POST);
        $values = array_values($_POST);

        $conditions = [];
        foreach ($columns as $key => $value) {

            if (strlen($values[$key]) >= 1) {
                if (strpos($columns[$key], '_id') !== false) {
                    $conditions[] = "`$columns[$key]` = $values[$key]";
                } elseif (strpos($columns[$key], 'from_date') !== false) {
                    foreach ($columns[$key] as $key2 => $value2) {
                        if (strpos($columns[$key2], 'to_date') !== false) {
                            $to_Date = $columns[$key2];
                        }
                    }
                    if ($to_date_key !== false) {
                        $conditions[] = "`$columns[$key]` BETWEEN '$values[$key]' AND '$to_Date'";
                    }
                } else {
                    $conditions[] = "`$columns[$key]` LIKE '%$values[$key]%'";
                }
            }

        }

        if (count($conditions) < 1) {
            $conditions[] = "1";
        }

        $conditions_string = implode(" AND ", $conditions);


        $sql = "SELECT * FROM $table_name WHERE $conditions_string";
        $db = new db_safeguard();

        $result = $db->select_query($table_name, '*', $conditions_string);

        // return json_encode($data);

        while ($data = $result->fetch_assoc()) {


            $html .= "
                <div class='searched_data'>";

            foreach ($returned_cols as $column) {

                $label_name = strtoupper((str_replace("id", "", str_replace("_", " ", str_replace("date", "", str_replace("time", "", $column))))));

                if (strpos($column, '_id') !== false) {
                    $possible_table_name = $table_name . "_" . str_replace("_id", "", $column);
                    if ($db->check_table_exists($possible_table_name)) {
                        try {
                            $results_for_data = $db->select_query($possible_table_name, 'name', "record_id = $data[$column]");
                            $other_data = $results_for_data->fetch_assoc();
                            $html .= "<div class='group_div'><label class='label'> $label_name </label><textarea type='text' class='inputs' readonly >" . $other_data['name'] . "</textarea></div>";
                        } catch (Exception $e) {
                            $results_for_data = $db->select_query($possible_table_name, 'username', "record_id = $data[$column]");
                            $other_data = $results_for_data->fetch_assoc();
                            $html .= "<div class='group_div'><label class='label'> $label_name </label><textarea type='text' class='inputs' readonly >" . $other_data['username'] . "</textarea></div>";
                        }
                    } else {

                        $possible_table_name = substr($table_name, 0, -1) . "_" . str_replace("_id", "", $column);
                        if (substr($possible_table_name, -1) !== 's') {
                            $possible_table_name .= 's';
                        }
                        if ($db->check_table_exists($possible_table_name)) {
                            $results_for_data = $db->select_query($possible_table_name, 'name', "record_id = $data[$column]");
                            $other_data = $results_for_data->fetch_assoc();
                            $html .= "<div class='group_div'><label class='label'> $label_name </label><textarea type='text' class='inputs' readonly >" . $other_data['name'] . "</textarea></div>";
                        } else {
                            $possible_table_name = str_replace("_id", "", $column);
                            if (substr($possible_table_name, -1) !== 's') {
                                $possible_table_name .= 's';
                            }
                            if ($db->check_table_exists($possible_table_name)) {
                                $results_for_data = $db->select_query($possible_table_name, 'name', "record_id = $data[$column]");
                                $other_data = $results_for_data->fetch_assoc();
                                $html .= "<div class='group_div'><label class='label'> $label_name </label><textarea type='text' class='inputs' readonly >" . $other_data['name'] . "</textarea></div>";

                            } else {
                                $html .= "<div class='group_div'><label class='label'> $label_name </label><textarea type='text' class='inputs' readonly > NO TABLE FOUND $possible_table_name PLEASE MAKE SURE THAT THE TABLE IS NAMED CORRECTLY AND THERE IS A NAME COLUMN IN THE TABLE</textarea></div>";

                            }

                        }
                    }

                } else {
                    $html .= "<div class='group_div'><label class='label'> $label_name </label><textarea type='text' class='inputs' readonly >" . $data[$column] . "</textarea></div>";
                }
            }
            $html .= "<input type='submit' value='EDIT' class='submit_btn' onclick='window.location.href=\"$edit_file_name?record_id=" . $data['record_id'] . "\"'/>";
            $html .= " </div>
            ";
        }

        return "$html";
    }

    function update()
    {

        $table_name = $_POST['table_name'];
        $edit_file_name = $_POST['edit_file_name'];
        $returned_cols = explode(",", $_POST['return_columns']);
        $add_column_and_value = explode(",", $_POST['add_column_and_value']);
        if (count($add_column_and_value) > 0) {
            foreach ($add_column_and_value as $add_column_and_value) {
                $add_column_and_value = explode("=", $add_column_and_value);
                $_POST[$add_column_and_value[0]] = $add_column_and_value[1];
            }
        }
        $excloudedcolumns = explode(',', $_POST['excloded_colum_names']);
        if (count($excloudedcolumns) > 0) {
            foreach ($excloudedcolumns as $excloudedcolumn) {
                unset($_POST[$excloudedcolumn]);
            }
        }
        unset($_POST['excloded_colum_names']);
        unset($_POST['add_column_and_value']);
        unset($_POST['return_columns']);
        unset($_POST['edit_file_name']);
        unset($_POST['ajax_type']);
        unset($_POST['table_name']);
        unset($_POST['where_clause']);
        unset($_POST['submit']);
        $record_id = $_POST['record_id'];
        unset($_POST['record_id']);

        if (isset($_POST['password'])) {
            $auth = new authentication();
            $_POST['password'] = $auth->encrypt_password($_POST['password']);
        }

        if (strlen($_POST['user_password']) < 1) {
            unset($_POST['user_password']);
        } else {
            $_POST['user_password'] = hash('SHA256', $_POST['user_password']);
        }

        $columns = array_keys($_POST);
        $values = array_values($_POST);
        $update_string = "";
        foreach ($columns as $key => $column) {
            if (strlen($column) > 1) {
                $update_string .= "`$column` = '$values[$key]', ";
            }
        }
        $update_string = rtrim($update_string, ', ');
        $sql = "UPDATE $table_name SET $update_string WHERE `record_id` = " . $record_id . "";
        $db = new db_safeguard();
        $result = $db->query($table_name, $sql);
        if ($result) {
            return 1;
        } else {
            return $result;
        }

    }

    function custom_insert()
    {
        $table_name = $_POST['table_name'];
        $edit_file_name = $_POST['edit_file_name'];
        $returned_cols = explode(",", $_POST['return_columns']);
        if (isset($_POST['date_time'])) {
            $_POST['date_time'] = date('Y-m-d H:i', strtotime("+2 hours"));
        }
        $add_column_and_value = explode(",", $_POST['add_column_and_value']);
        if (count($add_column_and_value) > 0) {
            foreach ($add_column_and_value as $add_column_and_value) {
                $add_column_and_value = explode("=", $add_column_and_value);
                $_POST[$add_column_and_value[0]] = $add_column_and_value[1];
            }
        }
        $excloudedcolumns = explode(',', $_POST['excloded_colum_names']);
        if (count($excloudedcolumns) > 0) {
            foreach ($excloudedcolumns as $excloudedcolumn) {
                unset($_POST[$excloudedcolumn]);
            }
        }
        unset($_POST['excloded_colum_names']);
        unset($_POST['add_column_and_value']);
        unset($_POST['return_columns']);
        unset($_POST['edit_file_name']);
        unset($_POST['ajax_type']);
        unset($_POST['table_name']);
        unset($_POST['where_clause']);
        unset($_POST['submit']);

        $columns = array_keys($_POST);
        $values = array_values($_POST);

        $columns_string = "`" . implode("` , `", $columns) . "`";
        $values_string = "'" . implode("','", $values) . "'";

        $sql = "INSERT INTO $table_name ($columns_string) VALUES ($values_string)";
        $db = new db_safeguard();

        return $db->query($table_name, $sql);
    }

}

class email
{

    public $email;
    public $mail;

    function __construct()
    {
        $this->mail = new PHPMailer(true);
        //Server settings
        $this->mail->isSMTP();
        $this->mail->Host = "mail.elegantwork.co.za";
        $this->mail->SMTPAuth = true;
        $this->mail->Username = "chris@elegantwork.co.za";
        $this->mail->Password = "EWG2Chr!@#";
        $this->mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $this->mail->Port = 465;
        $this->mail->SMTPDebug = 0;
        $this->mail->isHTML(true);
        $this->mail->setFrom('dewaalr@eskom.co.za', 'dewaalr@eskom.co.za');


    }
    function add_address($email, $name)
    {
        $this->mail->addAddress($email, $name);
    }

    function subject($subject = "TEST")
    {

        $this->mail->Subject = $subject;
    }

    function body($body = "")
    {
        $this->mail->Body = $body;
        // $this->mail->Body .= "<br><br><br><br><hr><br> <h1> Sent by Elegant Work Group Auto Mailer </h1> <bbr><br> <b> Please note this email address is unattended </b>";
    }

    function send()
    {
        try {

            return $this->mail->Send();
        } catch (Exception $e) {
            return $this->mail->ErrorInfo = $e->getMessage();
        }
    }
}
// ajax POST REq
if (isset($_POST['ajax_type'])) {
    $ajax = new ajax;
    if ($_POST['ajax_type'] == "INSERT") {
        echo $ajax->insert();
    }
    if ($_POST['ajax_type'] == "SELECT") {
        echo $ajax->select();
    }
    if ($_POST['ajax_type'] == "UPDATE") {
        echo $ajax->update();
    }
    if ($_POST['ajax_type'] == "DELETE") {
        echo $ajax->delete();
    }
    if ($_POST['ajax_type'] == "custom_insert") {
        echo $ajax->custom_insert();
    }
    if ($_POST['ajax_type'] == "get_work_orders") {
        $db = new db_safeguard();
        $work_order_res = $db->query("work_orders", "SELECT * FROM `work_orders` WHERE `in_review` = 0 AND `sent_for_review` = 0
AND `inprogress` = 0 AND `completed` = 0 AND `user_id_assigned` = {$_SESSION['user_id']}");
        echo $work_order_res->num_rows;
    }
    if ($_POST['ajax_type'] == "reviews") {
        $db = new db_safeguard();
        $work_order_res = $db->query("work_orders", "SELECT * FROM `work_orders` WHERE `in_review` = 0 AND `sent_for_review` = 1
AND `inprogress` = 0 AND `completed` = 0 AND `user_id_review` = {$_SESSION['user_id']}");
        echo $work_order_res->num_rows;
    }
    if ($_POST['ajax_type'] == "service_tickets") {
        $db = new db_safeguard();
        $work_order_res = $db->query("work_orders", "SELECT * FROM `service_tickets` WHERE  `completed` != 'COMPLETED' AND `user_id_assigned` = {$_SESSION['user_id']}");
        echo $work_order_res->num_rows;
    }
    if ($_POST['ajax_type'] == "approvals") {
        $db = new db_safeguard();
        $work_order_res = $db->query("approvals", "SELECT * FROM `approvals` WHERE  `approved_status` = 'WAITING'");
        echo $work_order_res->num_rows;
    }
    if ($_POST['ajax_type'] == "email_assets") {
        $email = new email();

        $email->add_address($_POST['email'], $_POST['email']);
        $email->body("Please use th following link to access your assets <a href='http://systems.elegantwork.co.za/app/reports/assets.report.php?client_id={$_POST['client_id']}'>Click Here</a>");
        echo $email->send();
    }
    if ($_POST['ajax_type'] == "email_passwords") {
        $email = new email();

        $email->add_address($_POST['email'], $_POST['email']);
        $email->body("Please use th following link to access your passwords <a href='http://systems.elegantwork.co.za/app/reports/passwords.report.php?client_id={$_POST['client_id']}'>Click Here</a>");
        echo $email->send();
    }
    if ($_POST['ajax_type'] == "projects_report") {
        echo $ajax->project_reports();
    }
    if ($_POST['ajax_type'] == "dev_mode_check") {
        echo $_SESSION['database_log'];
    }

}
