<?php
session_start();
require_once "classes/PHPMailer.php";
require_once "classes/SMTP.php";
require_once "classes/Exception.php";
require_once "classes/dashboard_class.php";
require_once "functions.class.php";
// $dashboard = new dashboard();

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// /* 
//             /* Small devices (portrait tablets and large phones, 600px and up) */
//             @media all and (min-width: 600px) {}

//             /* Medium devices (landscape tablets, 768px and up) */
//             @media all and (min-width: 768px) {}

//             /* Large devices (laptops/desktops, 992px and up) */
//             @media all and (min-width: 992px) {}

//             /* Extra large devices (large laptops and desktops, 1200px and up) */
//             @media all and (min-width: 1200px) {} */



class calendar
{
    function generateCalendar($monthOffset, $admin = false, $displayWeekends = true)
    {
        $dateStart = date('Y-m-d H:i', strtotime('-31 days'));
        $dateEnd = date('Y-m-d H:i', strtotime('+3 months'));
        $publicHolidays2025 = [
            "2025-01-01" => "New Year’s Day",
            "2025-03-21" => "Human Rights Day",
            "2025-04-18" => "Good Friday",
            "2025-04-21" => "Family Day",
            "2025-04-27" => "Freedom Day",
            "2025-04-28" => "Public holiday (Freedom Day observed)",
            "2025-05-01" => "Workers' Day",
            "2025-06-16" => "Youth Day",
            "2025-08-09" => "National Women’s Day",
            "2025-09-24" => "Heritage Day",
            "2025-12-16" => "Day of Reconciliation",
            "2025-12-25" => "Christmas Day",
            "2025-12-26" => "Day of Goodwill"
        ];

        $db = new db_safeguard();
        $durationTasks = [];
        $tasks = []; // Initialize early so it's available for all sections

        $user_data = $admin ? "" : " AND `user_id_assigned` = {$_SESSION['user_id']}";

        // Work Orders (Duration Tasks)
        // $work_order_res = $db->query("work_orders", "SELECT * FROM `work_orders` WHERE `completed` = 0 AND `sent_for_review` = 0 AND `in_review` = 0 $user_data");

        // if ($work_order_res->num_rows > 0) {
        //     while ($work_order = $work_order_res->fetch_assoc()) {
        //         $start_date = substr($work_order['action_date_time'], 0, 10);
        //         $end_date = substr($work_order['deadline_date_time'], 0, 10);
        //         $project_details = $db->query("projects", "SELECT * FROM projects WHERE record_id = {$work_order['project_id']}");
        //         $project_name = $project_details->fetch_assoc()['name'];
        //         $completed = $work_order['completed'];
        //         $class = ($end_date < date('Y-m-d H:i') && $completed != 1) ? "task task-overdue" : "task task-duration";
        //         $overdue = ($end_date < date('Y-m-d H:i') && $completed != 1) ? "(OVERDUE)" : "";

        //         if ($completed == 1) {
        //             $class = "duration_task task-complete";

        //         }

        //         $durationTasks[] = [
        //             'start' => "$start_date",
        //             'end' => "$end_date",
        //             'name' => htmlspecialchars(" {$work_order['name']} On Projcet: $project_name $overdue "),
        //             'description' => "",
        //             'link' => htmlspecialchars("/app/work_orders/work_order.php?record_id={$work_order['record_id']}"),
        //             'class' => "$class",
        //             "project" => "🗂️ " . "$project_name",
        //             "public_holiday" => $work_order['public_holiday'] ?? '0'
        //         ];
        //     }
        // }

        // // Meetings
        // $meetings_res = $db->query("meetings", "SELECT * FROM `meetings` WHERE date_time BETWEEN '$dateStart' AND '$dateEnd' AND (user_ids LIKE '%,{$_SESSION['user_id']},%' OR user_id = '{$_SESSION['user_id']}')");
        // if ($meetings_res->num_rows > 0) {
        //     while ($meeting = $meetings_res->fetch_assoc()) {
        //         $date = substr($meeting['date_time'], 0, 10);
        //         $time = str_replace("T", "", substr($meeting['date_time'], 11));
        //         $user_res = $db->query("users", "SELECT * FROM users WHERE record_id = {$meeting['user_id']}");
        //         $username = $user_res->fetch_assoc()['username'];
        //         $class = ("$date $time" < date('Y-m-d H:i')) ? "daily_task task-overdue " : "daily_task task-meeting ";
        //         $overdue = ("$date $time" < date('Y-m-d H:i') && $meeting['status'] != 1) ? "(OVERDUE)" : "";
        //         $username = ($meeting['client_id'] > 0) ? $db->query("clients", "SELECT * FROM clients WHERE record_id = {$meeting['client_id']}")->fetch_assoc()['name'] : $username;
        //         if ($meeting['status'] == 1) {
        //             $class = "daily_task task-complete";
        //         }
        //         if (strlen($meeting['client_visit']) > 1) {
        //             $client_visit = " WITH {$meeting['client_visit']} ";
        //         } else {
        //             $client_visit = " WITH $username ";
        //         }

        //         $tasks["$date"][] = [
        //             'time' => "$time",
        //             'icon' => "👥 <br> $username ({$meeting['duration']}) ",
        //             'description' => "MEETING $client_visit FOR {$meeting['duration']} AT {$meeting['location']} $overdue",
        //             'link' => "/app/meetings/meeting.php?record_id={$meeting['record_id']}",
        //             'class' => "$class",
        //             "user" => "$username",
        //             "completed" => $meeting['status'],
        //             "public_holiday" => $meeting['public_holiday'] ?? '0',
        //             "meeting" => 1
        //         ];
        //     }
        // }

        // // Service Tickets
        // $service_tickets_res = $db->query("service_tickets", "SELECT * FROM service_tickets WHERE action_date BETWEEN '$dateStart' AND '$dateEnd' $user_data");

        // if ($service_tickets_res->num_rows > 0) {
        //     while ($service_ticket = $service_tickets_res->fetch_assoc()) {
        //         $date = substr($service_ticket['action_date'], 0, 10);
        //         $time = str_replace("T", "", substr($service_ticket['action_date'], 11));
        //         $client_res = $db->query("clients", "SELECT * FROM clients WHERE record_id = {$service_ticket['client_id']}");
        //         $client_name = $client_res->fetch_assoc()['name'];
        //         $class = ("$date $time" < date('Y-m-d H:i') && $service_ticket['completed'] != "COMPLETED") ? "daily_task task-overdue " : "daily_task task-time ";
        //         $overdue = ("$date $time" < date('Y-m-d H:i') && $service_ticket['completed'] != "COMPLETED") ? " OVERDUE" : "";
        //         if ($service_ticket['completed'] == "COMPLETED") {
        //             $class = "task-complete";
        //         }

        //         if ($service_ticket['completed'] == "COMPLETED") {
        //             $completed = 1;
        //         } else {
        //             $completed = 0;
        //         }

        //         $tasks["$date"][] = [
        //             'time' => "$time ",
        //             'icon' => "📝 <br> $client_name",
        //             'description' => "{$service_ticket['name']} FOR $client_name  $overdue",
        //             'link' => "/app/service_tickets/complete_service_tickets.php?record_id={$service_ticket['record_id']}",
        //             'class' => "$class",
        //             "completed" => $completed,
        //             "public_holiday" => $service_ticket['public_holiday'] ?? '0',
        //             "service_ticket" => 1
        //         ];
        //     }
        // }
        // var_dump($tasks);
        ?>

        <script>
            function showPopup(event, name, description, link) {
                var popup = document.getElementById('popup');
                document.getElementById('popup-title').innerText = name;
                document.getElementById('popup-description').innerText = description;
                document.getElementById('popup-link').href = link;

                popup.style.display = 'block';
                popup.style.left = event.pageX + 'px';
                popup.style.top = event.pageY + 'px';
            }

            function closePopup() {
                document.getElementById('popup').style.display = 'none';
            }
        </script>

        <div id="popup" class="popup">
            <h3 id="popup-title"></h3>
            <p id="popup-description"></p>
            <a id="popup-link" href="#"><button class="submit_btn">Go To</button></a>
            <button onclick="closePopup()" class="submit_btn">Close</button>
        </div>

        <?php
        $year = date('Y');
        $month = date('n') + $monthOffset;

        if ($month > 12) {
            $month -= 12;
            $year++;
        }

        $firstDayOfMonth = strtotime("$year-$month-01");
        $daysInMonth = date('t', $firstDayOfMonth);
        $monthName = date('F', $firstDayOfMonth);
        $startDay = date('N', $firstDayOfMonth); // 1 (for Monday) through 7 (for Sunday)
        $currentDateTime = date('Y-m-d H:i');

        echo "<div class='calendar'>";
        echo "<h2>$monthName $year</h2>";
        echo "<table><tr>";

        $daysOfWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'];
        if ($displayWeekends) {
            $daysOfWeek = array_merge($daysOfWeek, ['Sat', 'Sun']);
        }

        foreach ($daysOfWeek as $dayOfWeek) {
            echo "<th>$dayOfWeek</th>";
        }
        echo "</tr><tr>";

        $dayCounter = 1;
        for ($i = 1; $i < $startDay; $i++) {
            if ($displayWeekends || ($i < 6)) {
                echo "<td></td>";
                $dayCounter++;
            }
        }

        for ($day = 1; $day <= $daysInMonth; $day++) {
            $dateKey = sprintf("%04d-%02d-%02d", $year, $month, $day);
            $dayOfWeekNumber = date('N', strtotime($dateKey));

            if ($displayWeekends || ($dayOfWeekNumber < 6)) {
                $isHoliday = array_key_exists($dateKey, $publicHolidays2025);
                $class = ($dateKey < substr($currentDateTime, 0, 10)) ? 'past-day' : (($dateKey == substr($currentDateTime, 0, 10)) ? 'current-day' : '');

                echo "<td class='$class'><div class='day'>$day</div>";

                if ($isHoliday) {
                    echo "<div class='holiday-label'>{$publicHolidays2025[$dateKey]}</div>";
                }

                foreach ($durationTasks as $task) {
                    if ($dateKey >= $task['start'] && $dateKey <= $task['end'] && date('N', strtotime($dateKey)) < 6) {
                        if ($isHoliday && $task['public_holiday'] != '1')
                            continue;
                        $userDisplay = $admin ? "<span style='font-size:1.25em;'><u>" . $task['user'] . "</u></span> <br><br>" : "";
                        echo "
                        <div class=' task {$task['class']}' style='background-color: {$task['color']};color: {$task['font_color']};' onclick=\"showPopup(event, ' {$task['name']}', '{$task['description']}', '{$task['link']}')\">
                            <div> 
                                {$task['project']}  
                            </div> 
                        </div>";
                    }
                }

                if (isset($tasks[$dateKey])) {
                    usort($tasks[$dateKey], fn($a, $b) => strtotime($a['time']) - strtotime($b['time']));

                    foreach ($tasks[$dateKey] as $task) {
                        if ($isHoliday && $task['public_holiday'] != '1')
                            continue;
                        $hidden_completed = ($task['completed'] == 1) ? "display: none" : "";
                        $completed_width_change = ($task['completed'] == 1) ? "width: 70%; padding: 0vh; padding-left: 0.75vh; margin-left: 35%;" : "";
                        if ($task['meeting'] == 1) {
                            $completed_icon = ($task['completed'] == 1) ? "👥 ✅" : "";

                        }
                        if ($task['service_ticket'] == 1) {
                            $completed_icon = ($task['completed'] == 1) ? "📝 ✅" : "";

                        }

                        echo "
                        <div class=' task {$task['class']}' style='$completed_width_change' 
                        
                        onclick=\"showPopup(event, '{$task['description']}', '{$task['description']}', '{$task['link']}')\">
                          <div class='task_inter_data_div'>
                           
                                <div class='time_section'> 
                                    {$task['time']} 
                                </div>
                                $completed_icon
                                <div class='data_section' style='$hidden_completed'> 
                                    {$task['icon']} 
                                </div>
                            </div>
                        </div>
                        ";
                    }
                }

                echo "</td>";
                $dayCounter++;
                if (($dayCounter - 1) % ($displayWeekends ? 7 : 5) == 0)
                    echo "</tr><tr>";
            }
        }

        while (($dayCounter - 1) % ($displayWeekends ? 7 : 5) != 0 && ($displayWeekends || (($dayCounter - 1) % 7 < 5))) {
            echo "<td></td>";
            $dayCounter++;
        }

        echo "</tr></table></div>";

        ?>
        <style>
            @media all and (max-width: 650px) {
                .task-time {
                    background-color: #DCEFFF;
                    color: #003366;
                }

                .task-duration {
                    background-color: #b4995e;
                    color: #42371b;
                }

                .task-meeting {
                    background-color: #EAF8E6;
                    color: #1F5D30;
                }

                .task-leave {
                    background-color: #FDECEC;
                    color: #991F1F;
                }

                .task-complete {
                    background-color: #E6F4EA;
                    color: #2D5F3B;
                    border-bottom-left-radius: 5px;
                }

                .task-overdue {
                    background-color: #ffcccc;
                    color: #B30000;
                    /* border: 1px dashed #B30000; */
                }

                .time_section {
                    width: 20%;
                    padding-right: 3.15vw;
                    margin: 4px;
                    padding-left: 0.85vw;
                    display: flex;
                    flex-direction: row;
                    align-content: center;
                    justify-content: center;
                    align-items: center;
                    border-right: 1px solid black;
                }

                .data_section {
                    display: flex;
                    width: 80%;
                    padding-left: 10px;
                    flex-direction: row;
                    flex-wrap: wrap;
                    align-content: center;
                    justify-content: flex-start;
                    align-items: center;
                }

                .task_inter_data_div {
                    display: flex;
                    flex-direction: row;
                    align-content: center;
                    align-items: center;
                }

                .calendar {
                    border: 1px solid #ccc;
                    background-color: #ffffff;
                    padding: 3vw;
                    border-radius: 24px;
                    box-shadow: -2px 3px 20px 0px rgba(0, 0, 0, 255);
                    text-align: center;
                    width: 90%;
                    overflow: auto;
                }

                table {
                    width: 100%;
                    border-collapse: collapse;
                    font-size: 1.25em;
                }

                th,
                td {
                    width:
                        <?php echo $displayWeekends ? '14%' : '20%'; ?>
                    ;
                    min-height: 100px;
                    overflow: hidden;
                    text-align: center;
                    border: 1px solid #494949;
                    vertical-align: top;
                }

                th {
                    background-color: #f3f3f3;
                }

                .day {
                    font-weight: bold;
                }

                .task {
                    padding: 2px;
                    /* border: 3px solid black; */
                    margin-top: 5px;
                    display: flex;
                    /* border-radius: 5px; */
                    font-size: 0.65em;
                    margin-top: 0.8vh;
                    cursor: pointer;
                    box-shadow: 3px 2px 5px 0px rgba(0, 0, 0, 0.2);
                    flex-direction: row;
                    width: 79%;
                    margin-left: auto;
                    margin-right: auto;
                    overflow: hidden;
                    flex-wrap: wrap;
                    align-content: center;
                }


                .daily_task {
                    max-width: 80%;
                    padding: 8px;
                    /* border: 3px solid black; */
                    box-shadow: 3px 2px 5px 0px rgba(0, 0, 0, 0.2);
                    margin-top: 0.8vh;
                    font-size: 0.65em;
                    margin-left: -3%;
                    cursor: pointer;

                }

                .past-day {
                    background-color: #f0f0f0;
                    color: #aaa;
                }

                .current-day {
                    background-color: rgba(151, 229, 243, 0.3);
                    /* border-bottom: #01b9f5 solid 5px; */
                    font-weight: bold;
                }

                .past-task {
                    background-color: #ff4d4d;
                }

                .holiday-label {
                    font-size: 0.75em;
                    font-weight: normal;
                    color: #999;
                    margin-top: 5px;
                }

                .popup {
                    display: none;
                    position: absolute;
                    background: white;
                    padding: 20px;
                    border: 1px solid #ccc;
                    box-shadow: 2px 2px 12px rgba(0, 0, 0, 0.3);
                    z-index: 1000;
                }

                .popup button {
                    margin-top: 10px;
                    padding: 5px 10px;
                }


            }

            @media all and (min-width: 651px) and (max-width: 1059px) {

                table {
                    font-size: 2em !important;
                }

                .task-time {
                    background-color: #DCEFFF;
                    color: #003366;
                }

                .task-duration {
                    background-color: #b4995e;
                    color: #42371b;
                }

                .task-meeting {
                    background-color: #EAF8E6;
                    color: #1F5D30;
                }

                .task-leave {
                    background-color: #FDECEC;
                    color: #991F1F;
                }

                .task-complete {
                    background-color: #E6F4EA;
                    color: #2D5F3B;
                    border-bottom-left-radius: 5px;
                }

                .task-overdue {
                    background-color: #ffcccc;
                    color: #B30000;
                    /* border: 1px dashed #B30000; */
                }

                .time_section {
                    width: 20%;
                    padding-right: 3vw;
                    margin: 4px;
                    padding-left: 0.15vw;
                    display: flex;
                    flex-direction: row;
                    align-content: center;
                    justify-content: center;
                    align-items: center;
                    border-right: 1px solid black;
                }

                .data_section {
                    display: flex;
                    width: 80%;
                    padding-left: 10px;
                    flex-direction: row;
                    flex-wrap: wrap;
                    align-content: center;
                    justify-content: flex-start;
                    align-items: center;
                }

                .task_inter_data_div {
                    display: flex;
                    flex-direction: row;
                    align-content: center;
                    align-items: center;
                }

                body {
                    font-family: Arial, sans-serif;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    flex-direction: column;
                    gap: 20px;
                }

                .calendar {
                    border: 1px solid #ccc;
                    background-color: white;
                    padding: 10px;
                    border-radius: 8px;
                    box-shadow: 2px 2px 12px rgba(0, 0, 0, 0.1);
                    text-align: center;
                    width: 90%;
                    overflow: auto;
                }

                table {
                    width: 100%;
                    border-collapse: collapse;
                    font-size: 2em;
                }


                th,
                td {
                    width:
                        <?php echo $displayWeekends ? '14%' : '20%'; ?>
                    ;
                    height: 100px;
                    overflow: hidden;
                    text-align: center;
                    border: 1px solid #ddd;
                    vertical-align: top;
                }

                th {
                    background-color: #f3f3f3;
                }

                .day {
                    font-weight: bold;
                }

                .task {
                    padding: 2px;
                    /* border: 3px solid black; */
                    margin-top: 0.8vh;

                    display: flex;
                    /* border-radius: 5px; */
                    font-size: 0.65em;
                    cursor: pointer;
                    box-shadow: 3px 2px 5px 0px rgba(0, 0, 0, 0.2);
                    flex-direction: row;
                    width: 79%;
                    margin-left: auto;
                    margin-right: auto;
                    overflow: hidden;
                    flex-wrap: wrap;
                    align-content: center;
                }

                .daily_task {
                    max-width: 80%;
                    padding: 8px;
                    /* border: 3px solid black; */
                    box-shadow: 3px 2px 5px 0px rgba(0, 0, 0, 0.2);
                    /* margin-top: 0.8vh; */
                    /* font-size: 0.65em; */
                    margin-left: -3%;
                    cursor: pointer;

                }

                .past-day {
                    background-color: #f0f0f0;
                    color: #aaa;
                }

                .current-day {
                    background-color: rgba(151, 229, 243, 0.3);
                    /* border-bottom: #01b9f5 solid 5px; */
                    font-weight: bold;
                }

                .past-task {
                    background-color: #ff4d4d;
                }

                .holiday-label {
                    font-size: 0.75em;
                    font-weight: normal;
                    color: #999;
                    margin-top: 5px;
                }

                .popup {
                    display: none;
                    position: absolute;
                    background: white;
                    padding: 20px;
                    border: 1px solid #ccc;
                    box-shadow: 2px 2px 12px rgba(0, 0, 0, 0.3);
                    z-index: 1000;
                }

                .popup button {
                    margin-top: 10px;
                    padding: 5px 10px;
                }

            }


            @media all and (min-width: 1050px) {

                table {
                    font-size: 1em !important;
                }

                .task-time {
                    background-color: #DCEFFF;
                    color: #003366;
                }

                .task-duration {
                    background-color: #b4995e;
                    color: #42371b;
                }

                .task-meeting {
                    background-color: #EAF8E6;
                    color: #1F5D30;
                }

                .task-leave {
                    background-color: #FDECEC;
                    color: #991F1F;
                }

                .task-complete {
                    background-color: #E6F4EA;
                    color: #2D5F3B;
                    border-bottom-left-radius: 5px;
                }

                .task-overdue {
                    background-color: #ffcccc;
                    color: #B30000;
                    /* border: 1px dashed #B30000; */
                }

                .time_section {
                    width: 20%;
                    padding-right: 1.15vw;
                    margin: 4px;
                    padding-left: 0.15vw;
                    display: flex;
                    flex-direction: row;
                    align-content: center;
                    justify-content: center;
                    align-items: center;
                    border-right: 1px solid black;
                }

                .data_section {
                    display: flex;
                    width: 80%;
                    padding-left: 10px;
                    flex-direction: row;
                    flex-wrap: wrap;
                    align-content: center;
                    justify-content: flex-start;
                    align-items: center;
                }

                .task_inter_data_div {
                    display: flex;
                    flex-direction: row;
                    align-content: center;
                    align-items: center;
                }

                body {
                    font-family: Arial, sans-serif;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    flex-direction: column;
                    gap: 20px;
                }

                .calendar {
                    border: 1px solid #ccc;
                    background-color: white;
                    padding: 10px;
                    border-radius: 8px;
                    box-shadow: 2px 2px 12px rgba(0, 0, 0, 0.1);
                    text-align: center;
                    width: 90%;
                    overflow: auto;
                }

                table {
                    width: 100%;
                    border-collapse: collapse;
                    font-size: 2em;
                }


                th,
                td {
                    width:
                        <?php echo $displayWeekends ? '14%' : '20%'; ?>
                    ;
                    height: 100px;
                    overflow: hidden;
                    text-align: center;
                    border: 1px solid #ddd;
                    vertical-align: top;
                }

                th {
                    background-color: #f3f3f3;
                }

                .day {
                    font-weight: bold;
                }

                .task {
                    padding: 2px;
                    /* border: 3px solid black; */
                    margin-top: 5px;
                    display: flex;
                    /* border-radius: 5px; */
                    font-size: 0.65em;
                    cursor: pointer;
                    box-shadow: 3px 2px 5px 0px rgba(0, 0, 0, 0.2);
                    flex-direction: row;
                    width: 79%;
                    margin-left: auto;
                    margin-right: auto;
                    overflow: hidden;
                    flex-wrap: wrap;
                    align-content: center;
                }


                .daily_task {
                    max-width: 80%;
                    padding: 8px;
                    /* border: 3px solid black; */
                    box-shadow: 3px 2px 5px 0px rgba(0, 0, 0, 0.2);
                    margin-top: 5px;
                    font-size: 0.65em;
                    margin-left: -3%;
                    cursor: pointer;

                }

                .past-day {
                    background-color: #f0f0f0;
                    color: #aaa;
                }

                .current-day {
                    background-color: rgba(151, 229, 243, 0.3);
                    /* border-bottom: #01b9f5 solid 5px; */
                    font-weight: bold;
                }

                .past-task {
                    background-color: #ff4d4d;
                }

                .holiday-label {
                    font-size: 0.75em;
                    font-weight: normal;
                    color: #999;
                    margin-top: 5px;
                }

                .popup {
                    display: none;
                    position: absolute;
                    background: white;
                    padding: 20px;
                    border: 1px solid #ccc;
                    box-shadow: 2px 2px 12px rgba(0, 0, 0, 0.3);
                    z-index: 1000;
                }

                .popup button {
                    margin-top: 10px;
                    padding: 5px 10px;
                }

            }
        </style>

        <?php
    }
}

class root_styles
{
    function __destruct()
    {
        ?>
        <style>
            @media all and (max-width: 650px) {

                body {
                    margin: 0;
                    background: linear-gradient(90deg, #464646, #b1b1b1);
                    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%;
                    }
                }

                /* Popup background */
                .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: 84vw;
                    height: 58vw;
                    /* 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: 1px solid #004aad;
                    /* border-bottom: 5px solid; */
                    border-radius: 2vw;
                    padding-left: 17px;
                    background: white;
                    outline: none;
                    /* font-size: 4vw; */
                    /* height: 11vw; */
                    font-size: 2em;
                    height: 15vw;
                    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: 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: 1em;
                    margin: 1vw auto;
                    cursor: pointer;
                    border: 3px solid #b36534;
                    background: white;
                    width: 18vw;
                    height: 6vh;
                    color: black;
                    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: #b36534;
                    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: 2em;
                    overflow: hidden;
                    /* border-radius: 1vw; */
                    /* margin: 3vw auto; */
                    /* margin: 2vw auto; */
                    /* cursor: pointer; */
                    border: 3px solid white;
                    background-color: #004aad;
                    background-size: 400% 400%;
                    animation: gradient 15s ease infinite;
                    width: 90%;
                    color: white;
                    height: auto;
                    padding: 3vw;
                    border-radius: 1.8vw;
                    z-index: 2;
                    animation-direction: alternate;

                    @keyframes gradient {
                        0% {
                            background-position: 0% 50%;
                        }

                        50% {
                            background-position: 100% 50%;
                        }

                        100% {
                            background-position: 0% 50%;
                        }
                    }
                }

                .login_btn:hover {
                    /* scale: 1; */
                    transition: all 0.5s ease-in-out;
                    background-color: navy;
                }

                .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: 0vw;
                    width: 60%;
                    cursor: pointer;
                    background-color: white;
                }

                .dropdown {
                    display: none;
                    flex-direction: column;
                    background-color: darkgrey;
                    /* background-color: #145693; */
                    border: 3px solid white;
                    border-top: none;
                    width: 16.5vw;
                    /* margin-left: 3vw; */
                    margin-top: -2vw;
                    position: relative;
                    /* bottom: 14px; */
                    z-index: 1;
                    padding: 0.5vw 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 white;
                    font-size: 1em;
                    color: black;
                    margin-bottom: 1vh;

                }


                .mini_btn {
                    margin: 1vw auto 0vw auto;
                    cursor: pointer;
                    border: 3px solid #80808000;
                    background: white;
                    width: 91%;
                    color: black;
                    overflow: hidden;
                    border-radius: 15px;
                    font-size: 0.8em;
                    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: #b36534;
                }

                .mini_btn:not(:hover) {
                    transition: all 0.5s ease-in-out;
                }

                .frame {
                    height: 99.5%;
                    float: right;
                    width: 75.5%;
                    position: absolute;
                    right: 0;
                    top: 0;
                    overflow: hidden;
                    border: none;
                }

            }

            @media all and (min-width: 651px) and (max-width: 1050px) {

                body {
                    margin: 0;
                    background: linear-gradient(90deg, #464646, #b1b1b1);
                    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%;
                    }
                }

                /* 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: 84vw;
                    height: 58vw;
                    /* 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: 1px solid #004aad;
                    /* border-bottom: 5px solid; */
                    border-radius: 2vw;
                    padding-left: 17px;
                    background: white;
                    outline: none;
                    /* font-size: 4vw; */
                    /* height: 11vw; */
                    font-size: 2em;
                    height: 15vw;
                    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: 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: 1.85em;
                    margin: 1vw auto;
                    cursor: pointer;
                    border: 3px solid #b36534;
                    background: white;
                    width: 18vw;
                    height: 6vh;
                    color: black;
                    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: #b36534;
                    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: 2em;
                    overflow: hidden;
                    /* border-radius: 1vw; */
                    /* margin: 3vw auto; */
                    /* margin: 2vw auto; */
                    /* cursor: pointer; */
                    border: 3px solid white;
                    background-color: #004aad;
                    background-size: 400% 400%;
                    animation: gradient 15s ease infinite;
                    width: 90%;
                    color: white;
                    height: auto;
                    padding: 3vw;
                    border-radius: 1.8vw;
                    z-index: 2;
                    animation-direction: alternate;

                    @keyframes gradient {
                        0% {
                            background-position: 0% 50%;
                        }

                        50% {
                            background-position: 100% 50%;
                        }

                        100% {
                            background-position: 0% 50%;
                        }
                    }
                }

                .login_btn:hover {
                    /* scale: 1; */
                    background-color: navy;
                    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: 0vw;
                    width: 60%;
                    cursor: pointer;
                    background-color: white;
                }

                .dropdown {
                    display: none;
                    flex-direction: column;
                    background-color: darkgrey;
                    /* background-color: #145693; */
                    border: 3px solid white;
                    border-top: none;
                    width: 16.5vw;
                    /* margin-left: 3vw; */
                    margin-top: -2vw;
                    position: relative;
                    /* bottom: 14px; */
                    z-index: 1;
                    padding: 0.5vw 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.8em;
                    color: black;
                    margin-bottom: 1vh;

                }


                .mini_btn {
                    margin: 1vw auto 0vw auto;
                    cursor: pointer;
                    border: 3px solid #80808000;
                    background: white;
                    width: 91%;
                    color: black;
                    overflow: hidden;
                    border-radius: 15px;
                    font-size: 1.65em;
                    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: #b36534;
                }

                .mini_btn:not(:hover) {
                    transition: all 0.5s ease-in-out;
                }

                .frame {
                    height: 99.5%;
                    float: right;
                    width: 75.5%;
                    position: absolute;
                    right: 0;
                    top: 0;
                    overflow: hidden;
                    border: none;
                }

            }

            @media all and (min-width: 1050px) {

                body {
                    margin: 0;
                    background: linear-gradient(90deg, #464646, #b1b1b1);
                    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%;
                    }
                }

                /* 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: 50vw;
                    height: 30vw;
                    /* 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: 1px solid #004aad;
                    /* border-bottom: 5px solid; */
                    border-radius: 2vw;
                    padding-left: 17px;
                    background: white;
                    outline: none;
                    /* font-size: 4vw; */
                    /* height: 11vw; */
                    font-size: 1em;
                    height: 4vh;
                    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: 100%;
                    background: #004aad;
                    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: 1em;
                    margin: 1vw auto;
                    cursor: pointer;
                    border: 3px solid #b36534;
                    background: white;
                    width: 18vw;
                    height: 6vh;
                    color: black;
                    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: #b36534;
                    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: 2em;
                    overflow: hidden;
                    /* border-radius: 1vw; */
                    /* margin: 3vw auto; */
                    /* margin: 2vw auto; */
                    /* cursor: pointer; */
                    border: 3px solid white;
                    background-color: #004aad;
                    background-size: 400% 400%;
                    animation: gradient 15s ease infinite;
                    width: 90%;
                    color: white;
                    height: auto;
                    padding: 3vw;
                    border-radius: 1.8vw;
                    z-index: 2;
                    animation-direction: alternate;

                    @keyframes gradient {
                        0% {
                            background-position: 0% 50%;
                        }

                        50% {
                            background-position: 100% 50%;
                        }

                        100% {
                            background-position: 0% 50%;
                        }
                    }
                }

                .login_btn:hover {
                    /* scale: 1; */
                    background-color: navy;
                    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: 0vw;
                    width: 60%;
                    cursor: pointer;
                    background-color: white;
                }

                .dropdown {
                    display: none;
                    flex-direction: column;
                    background-color: darkgrey;
                    /* background-color: #145693; */
                    border: 3px solid white;
                    border-top: none;
                    width: 16.5vw;
                    /* margin-left: 3vw; */
                    margin-top: -2vw;
                    position: relative;
                    /* bottom: 14px; */
                    z-index: 1;
                    padding: 0.5vw 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 white;
                    font-size: 1em;
                    color: black;
                    margin-bottom: 1vh;

                }


                .mini_btn {
                    margin: 1vw auto 0vw auto;
                    cursor: pointer;
                    border: 3px solid #80808000;
                    background: white;
                    width: 91%;
                    color: black;
                    overflow: hidden;
                    border-radius: 15px;
                    font-size: 1em;
                    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: #b36534;
                }

                .mini_btn:not(:hover) {
                    transition: all 0.5s ease-in-out;
                }

                .frame {
                    height: 99.5%;
                    float: right;
                    width: 75.5%;
                    position: absolute;
                    right: 0;
                    top: 0;
                    overflow: hidden;
                    border: none;
                }

            }
        </style>

        <?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);
                // check_Supplier();
            }

            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()
    {
        ?>
                    <br>
                    <img src="icons/test.svg" alt="Logo" onclick="change_to('home.php')" class="logo" style="margin: auto;">
                    <br>
                    <?php

    }

    /**
     * Adds a menu item to the sidebar
     * A Icon for the mobile view  
     */
    function add_mobile_icon($name, $icon)
    {
        ?>
                    <img src="icons/<?php echo $icon; ?>.svg" alt="<?php echo $name; ?>"
                        onclick="dropdown('<?php echo $name; ?>')" class="mobile_icon">
                    <div class="dropdown" id="<?php echo $name; ?>">
                        <?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

    }

    function add_mobile_logout($name, $icon)
    {
        ?>
                            <img src="icons/<?php echo $icon; ?>.svg" alt="<?php echo $name; ?>" onclick="logout()"
                                class="mobile_icon">
                            <?php
    }

    function add_mobile_dev_mode($name, $icon)
    {
        ?>
                            <div id='dev_mode'
                                style="width:100%; height:100%;z-index:9999999;background-color: blue;display:none;top:0;left:0; color:white;">

                            </div>
                            <img src="icons/<?php echo $icon; ?>.svg" alt="<?php echo $name; ?>" onclick="toggle_dev_mode()"
                                class="mobile_icon">
                            <?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 datalist
{
    private $attributes = [];

    private $value;

    private $datalist_options = [];

    // Set the input to use a datalist (assumes 'id' is set already)
    function new_datalist()
    {
        if (isset($this->attributes['id'])) {
            $this->addAttribute('list', $this->attributes['id'] . '_list');
        }
    }

    // Provide datalist options
    function setDatalistOptions(array $options)
    {
        $this->datalist_options = $options;
    }

    /**
     * Populates datalist options from a database table.
     *
     * @param string $table      The name of the database table.
     * @param string $value_col  The column to be used as the option value.
     * @param string|null $label_col (optional) The column to be used as the label for the option (can be the same as $value_col).
     * @param string|null $where (optional) Optional WHERE clause without the 'WHERE' keyword.
     */
    function setDatalistFromDB($table, $value_col, $label_col = null, $where = null)
    {
        $db = new db_safeguard();

        $label_col = $label_col ?? $value_col;

        $sql = "SELECT `$value_col`, `$label_col` FROM `$table`";
        if ($where) {
            $sql .= " WHERE $where";
        }

        $res = $db->query($table, $sql);
        if ($res) {
            while ($row = $res->fetch_assoc()) {
                $value = htmlspecialchars($row[$value_col], ENT_QUOTES);
                $label = htmlspecialchars($row[$label_col], ENT_QUOTES);
                $this->datalist_options[$value] = $label;
            }
        }
    }

    /**
     * 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 hidden()
    {
        $this->addAttribute('hidden', 'hidden');
    }
    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 value_return()
    {
        return $this->value;
    }

    function style($style)
    {
        $this->addAttribute('style', $style);
    }

    function class($class = "inputs")
    {
        $this->addAttribute('class', $class);
    }

    function add()
    {
        echo "<input list='" . $this->attributes['list'] . "'" . "class='" . $this->attributes['class'] . "'" . " name='" . $this->attributes['name'] . "'" . " id='" . $this->attributes['id'] . "'" . " value='" . $this->value . "'/>";

        if (!empty($this->datalist_options) && isset($this->attributes['list'])) {
            $list_id = $this->attributes['list'];
            echo "<datalist id='$list_id'>";
            foreach ($this->datalist_options as $value => $label) {
                if ($value === $label) {
                    echo "<option value=\"$value\">";
                } else {
                    echo "<option value=\"$value\">$label</option>";
                }
            }
            echo "</datalist>";
        }
    }
}

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 hidden()
    {
        $this->addAttribute('hidden', 'hidden');
    }
    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 value_return()
    {
        return $this->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 textarea
{
    private $attributes = [];

    private $value;

    function name($name)
    {
        $this->addAttribute('name', $name);
    }

    function id($id)
    {
        $this->addAttribute('id', $id);
    }

    function rows($rows)
    {
        $this->addAttribute('rows', $rows);
    }

    function cols($cols)
    {
        $this->addAttribute('cols', $cols);
    }

    function addAttribute($name, $value)
    {
        $this->attributes[$name] = $value;
    }

    function class($class = "inputs")
    {
        $this->addAttribute('class', $class);
    }

    function placeholder($placeholder)
    {
        $this->addAttribute('placeholder', $placeholder);
    }

    function readonly($readonly)
    {
        $this->addAttribute('readonly', $readonly);
    }

    function style($style)
    {
        $this->addAttribute('style', $style);
    }

    function value($value)
    {
        $this->value = $value;
    }

    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 add()
    {
        if (!array_key_exists('class', $this->attributes)) {
            $this->class();
        }

        $textarea = "<textarea";
        foreach ($this->attributes as $key => $value) {
            $textarea .= " $key='$value'";
        }
        $textarea .= ">{$this->value}</textarea>";
        echo $textarea;
    }

}

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 style($style)
    {
        $this->addAttribute('style', "$style");
    }

    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(approvals, 1000);
                    function closePopup() {
                        document.getElementById('loginPopup').style.display = 'none';
                    }


                    function showPopup() {
                        document.getElementById('loginPopup').style.display = 'flex';
                    }


                </script>

                <?php
    }


    public function __destruct()
    {
        // session_destroy();
    }
}

class file_upload
{
    public $id_;
    public $name_;
    public $file_save_path_;
    public $file_type_;
    public $required_ = 0;
    public $class_;
    public $style_;
    public $value_;

    function id($id)
    {
        $this->id_ = $id;
    }

    function name($name)
    {
        $this->name_ = $name;
    }

    function file_save_path($file_save_path)
    {
        $this->file_save_path_ = $file_save_path;
    }
    function file_type($file_type)
    {
        $this->file_type_ = $file_type;
    }
    function required()
    {
        $this->required_ = 1;
    }
    function class($class = "submit_btn")
    {
        $this->class_ = $class;
    }
    function style($style)
    {
        $this->style_ = $style;
    }
    function value($value)
    {
        $this->value_ = $value;
    }
    function add()
    {
        if ($this->required_ == 1) {
            echo '<input type="file" name="' . $this->name_ . '" id="' . $this->id_ . '" class="' . $this->class_ . '" required value="' . $this->value_ . '" style="' . $this->style_ . '">';
        } else {
            echo '<input type="file" name="' . $this->name_ . '" id="' . $this->id_ . '" value="' . $this->value_ . '" class="' . $this->class_ . '" style="' . $this->style_ . '">';
        }

        ?>
                <script>
                    (function () {
                        var fileInput<?php echo $this->id_; ?> = document.querySelector('#<?php echo $this->id_; ?>');

                        fileInput<?php echo $this->id_; ?>.addEventListener("change", function () {
                            var file = this.files[0]; // Use 'this' to refer to the current input element
                            var formData = new FormData();
                            formData.append('fileToUpload', file);
                            formData.append('ajax_type', "file_upload");
                            formData.append('file_save_path', "<?php echo $this->file_save_path_; ?>");
                            var xhr = new XMLHttpRequest();
                            xhr.onreadystatechange = function () {
                                if (xhr.readyState === XMLHttpRequest.DONE) {
                                    if (xhr.responseText == "1"
                                    ) {
                                        console.log(xhr.responseText + "_____________________________________________"); // Handle response from server
                                        alert("Uploaded for <?php echo $this->name_; ?>");
                                    } else {
                                        console.log(xhr.responseText + "_____________________________________________"); // Handle response from server
                                        alert("Error for <?php echo $this->name_; ?>");
                                    }
                                }
                            };
                            xhr.open("POST", "/root.class.php", true);
                            xhr.send(formData);
                        });
                    })();
                </script>
                <?php
    }
}

class test_file
{

    public $attributes;

    public $value;

    function name($name)
    {
        $this->addAttribute('name', $name);
    }

    function id($id)
    {
        $this->addAttribute('id', $id);
    }

    function type($type = "file")
    {
        $this->addAttribute('type', $type);
    }

    function class($class = "inputs")
    {
        $this->addAttribute('class', $class);
    }

    function file_save_path($file_save_path)
    {
        $this->addAttribute('file_save_path', $file_save_path);
    }

    function send_file_path($send_file_path)
    {
        $this->addAttribute('send_file_path', $send_file_path);
    }

    function file_type($file_type)
    {
        $this->addAttribute('file_type', $file_type);
    }

    function add()
    {
        if (!array_key_exists('class', $this->attributes)) {
            $this->class();
        }

        $input = "<input ";
        foreach ($this->attributes as $key => $value) {
            $input .= $key . "='" . $value . "' ";
        }
        $input .= ">";
        echo $input;
    }

    function __destruct()
    {
        ?>
                <script>
                    var <?php echo $this->attributes['name']; ?>_file = document.getElementById('<?php echo $this->attributes['name']; ?>');

                                                                    //create a onchage function that send the file to a separate page
                                                            <?php echo $this->attributes['name']; ?>_file.addEventListener("change", function () {
                        var file = this.files[0]; // Use 'this' to refer to the current input element
                        var formData = new FormData();
                        formData.append('fileToUpload', file);
                        formData.append('ajax_type', "file_upload");
                        formData.append('file_save_path', "<?php echo $this->attributes['file_save_path']; ?>");
                        var xhr = new XMLHttpRequest();
                        xhr.onreadystatechange = function () {
                            if (xhr.readyState === XMLHttpRequest.DONE) {
                                if (xhr.responseText == "1"
                                ) {
                                    console.log(xhr.responseText + "_____________________________________________"); // Handle response from server
                                    alert("Uploaded for <?php echo $this->attributes['name']; ?>");
                                } else {
                                    console.log(xhr.responseText + "_____________________________________________"); // Handle response from server
                                    alert("Error for <?php echo $this->attributes['name']; ?>");
                                }
                            }
                        };
                        xhr.open("POST", "<?php echo $this->attributes['send_file_path']; ?>", true);
                        xhr.send(formData);
                    });

                </script>

                <?php
    }
}

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;
    public $email_address_array;
    public $subject;
    public $body;
    public $selected_div = ".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";
    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 selected_div($selected_div)
    {
        $this->selected_div = $selected_div;
    }
    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 send_email_on_success(string $email_address_array, string $subject, string $body)
    {
        $this->email_address_array = $email_address_array;
        $this->subject = $subject;
        $this->body = $body;
    }

    function run_on_load()
    {
        $this->run_on_load = 1;
    }
    function __destruct()
    {
        if (!isset($this->selected_div)) {
            self::selected_div();
        }
        ?>
                <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("<?php echo $this->selected_div; ?>");
                            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("<?php echo $this->selected_div; ?>");
                        inputs.forEach(function (input) {
                            if (input.type === "file") {
                                if (input.files.length > 0) {
                                    data[input.id] = input.files[0].name;
                                }
                            } else 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; ?>";
                        data["email_address_array"] = "<?php echo $this->email_address_array; ?>";
                        data["subject"] = "<?php echo $this->subject; ?>";
                        data["body"] = "<?php echo $this->body; ?>";




                        <?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 __construct()
    {
        echo '<head><meta name="viewport" content="width=device-width, initial-scale=1.0"></head>';
    }
    function open_new_window($function_name, $url, $window_name, $width = "1200", $height = "800", $favicon = "")
    {
        ?>
                <script>
                    function <?php echo $function_name; ?>() {
                        url = "<?php echo $url; ?>";

                        var myWindow = window.open(url, "<?php echo $window_name; ?>", "width=<?php echo $width; ?>,height=<?php echo $height; ?>");
                        if (myWindow) {
                            myWindow.focus(); // Bring the new window to the front
                            myWindow.document.head.innerHTML += '<link rel="shortcut icon" href="<?php echo $favicon; ?>" type="image/x-icon">';
                        } else {
                            alert("Please allow popups for this site.");
                        }
                    }
                </script>
                <?php

    }
    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>
                        <button onclick="insertCheckbox_<?php echo $content_id_html_tag; ?>()">Checkbox</button>
                    </div>
                </div>



                <script>
                    // Format the text (bold, italic, underline, headings)
                    function formatText_<?php echo $content_id_html_tag; ?>(command, value = null) {
                        document.execCommand(command, false, value); // Used for headings (e.g., h1, h2, h3) or normal font
                    }

                    // Insert a checkbox at the current cursor position
                    function insertCheckbox_<?php echo $content_id_html_tag; ?>() {
                        const checkbox = document.createElement('input');
                        checkbox.type = 'checkbox';

                        const selection = window.getSelection();
                        if (selection.rangeCount > 0) {
                            const range = selection.getRangeAt(0);
                            range.deleteContents(); // Remove any selected text
                            range.insertNode(checkbox);
                            range.collapse(false); // Move cursor to *after* the checkbox.  Important!
                        }
                    }
                </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 = "ewg.dedicated.co.za", $user = 'elegaysv_Code2', $password = 'EWG2Cod!@#', $dbname = 'elegaysv_lowveld_nuts')
    {
        $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((String) @$_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["user_type"] = $row["user_type"];
            $_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);
    }

    //Create a function to add to the database
    public function insert($Query = '')
    {

        $this->connection->query($Query);

        return $this->connection->insert_id;

    }

    //update function
    public function Update($tableName, $columns = [], $values = [], $where = '1', $devmode = False)
    {

        $this->table = $tableName;

        if (count($columns) == count($values)) {


            $queryDatabase[] = "UPDATE $this->table_name SET ";
            $i = 0;
            foreach ($columns as $colls) {

                $queryDatabaseCols[] = "`$colls` = '$values[$i]'";

                $i++;

            }
            $queryDatabase[] = implode(',', $queryDatabaseCols);

            $queryDatabase[] = " WHERE $where";

            if ($devmode == True) {

                echo implode('', $queryDatabase);

            } else {

                // echo implode('',$queryDatabase);

                return $this->connection->query(implode('', $queryDatabase));
            }


        } else {
            return "values and columns not same length";
        }
    }
}

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']);
        unset($_POST['']);

        if (isset($_POST['email_address_array'])) {
            $email = new email();
            $_POST['email_address_array'] = explode(',', $_POST['email_address_array']);
            foreach ($_POST['email_address_array'] as $email_address) {
                if (strlen($email_address) > 0) {

                    $email->add_address($email_address, $email_address);
                }
            }
            $email->subject($_POST['subject']);
            $email->body($_POST['body']);


        }
        unset($_POST['email_address_array']);
        unset($_POST['subject']);
        unset($_POST['body']);

        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) {
            $email->send();
            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']);
        }

        if (isset($_POST['email_address_array'])) {
            $email = new email();
            $_POST['email_address_array'] = explode(',', $_POST['email_address_array']);
            foreach ($_POST['email_address_array'] as $email_address) {
                if (strlen($email_address) > 0) {

                    $email->add_address($email_address, $email_address);
                }
            }
            $email->subject($_POST['subject']);
            $email->body($_POST['body']);


        }
        unset($_POST['email_address_array']);
        unset($_POST['subject']);
        unset($_POST['body']);
        $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) {
            $email->send();
            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 = "no-reply@elegantwork.co.za";
        $this->mail->Password = "XR26ooQ;Pk3.";
        $this->mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $this->mail->Port = 465;
        $this->mail->SMTPDebug = 0;
        $this->mail->isHTML(true);
        $this->mail->setFrom('no-reply@elegantwork.co.za', 'No-Reply@EWG');


    }
    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();
        }
    }
}

//create a class for signatures
class signature
{

    private $attributes = [];

    private $value;


    function __construct()
    {
        ?>
                <script src="https://cdn.jsdelivr.net/npm/signature_pad@2.3.2/dist/signature_pad.min.js">
                </script>
                <?php
    }
    function addAttribute($name, $value)
    {
        $this->attributes[$name] = $value;
    }

    function name($name)
    {
        $this->addAttribute('name', $name);
    }

    function id($id)
    {
        $this->addAttribute('id', $id);
    }

    function style($style)
    {
        $this->addAttribute('style', $style);
    }

    function class($class = "signature")
    {
        $this->addAttribute('class', $class);
    }

    function send_file_path($path)
    {
        $this->addAttribute('send_file_path', $path);
    }

    function submit_btn_id($submit_btn_id)
    {
        $this->addAttribute('submit_btn_id', $submit_btn_id);
    }

    function add()
    {

        if (!array_key_exists('class', $this->attributes)) {
            $this->class();
        }

        $signature = "<canvas";
        foreach ($this->attributes as $key => $value) {
            $signature .= " $key=\"$value\"";
        }
        $signature .= "></canvas>";
        echo $signature;
    }

    function __destruct()
    {
        ?>

                <script>

                    var <?php echo $this->attributes['name']; ?>_canvas = document.getElementById('<?php echo $this->attributes['name']; ?>');
                    var <?php echo $this->attributes['name']; ?>_pad = new SignaturePad(<?php echo $this->attributes['name']; ?>_canvas);

                    document.getElementById('<?php echo $this->attributes['submit_btn_id']; ?>').addEventListener('click', function () {
                        if (<?php echo $this->attributes['name']; ?>_pad.isEmpty()) {
                        alert("Please provide signature");
                    } else {
                        var dataURL = <?php echo $this->attributes['name']; ?>_pad.toDataURL('image/png');
                        var blob = dataURLToBlob(dataURL);
                        var formData = new FormData();
                        formData.append('file', blob, 'signature.png');
                        formData.append('type', '<?php echo $this->attributes['name']; ?>');

                        var xhr = new XMLHttpRequest();
                        xhr.open("POST", "<?php echo $this->attributes['send_file_path']; ?>", true);
                        xhr.onreadystatechange = function () {
                            if (xhr.readyState === 4 && xhr.status === 200) {
                                alert(xhr.responseText); // Handle the server response
                                if (xhr.responseText.indexOf("OK") > 1) {
                                    // repload page
                                    // location.reload();
                                    console.log("Signature saved successfully.");

                                } else {
                                    // alert(xhr.responseText);
                                }
                            }
                        };
                        xhr.send(formData);
                    }
                                                                            });

                    function dataURLToBlob(dataURL) {
                        var binary = atob(dataURL.split(',')[1]);
                        var array = [];
                        for (var i = 0; i < binary.length; i++) {
                            array.push(binary.charCodeAt(i));
                        }
                        return new Blob([new Uint8Array(array)], {
                            type: dataURL.split(',')[0].split(':')[1].split(';')[0]
                        });
                    }

                </script>
                <?php
    }
}

// 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'];
    }
    if ($_POST['ajax_type'] == "file_upload") {
        $file_save_path = $_POST['file_save_path'];

        $target_dir = $file_save_path;
        $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
        $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
            return 1;
        } else {
            return 0;
        }
    }
}


$func = new func();
?>