<?php
session_start();
require_once "classes/PHPMailer.php";
require_once "classes/SMTP.php";
require_once "classes/Exception.php";
require_once "functions.class.php";
// $dashboard = new dashboard();

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;




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:1em;'><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: 1em;
                }

                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: 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: 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: 1em;
                }


                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: 1em;
                }


                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(45deg, rgb(0, 195, 255), rgb(5, 41, 109), rgb(141, 224, 255), rgb(0, 0, 0));
                    background-color: #4a90e2;
                    background-size: 400% 400%;
                    animation: gradient 20s ease infinite;
                    display: flex;
                    flex-direction: row;
                    flex-wrap: wrap;
                    align-content: space-around;
                    justify-content: center;
                    overflow: hidden;
                    /* Prevents overflow */
                    position: relative;
                }

                /* Gradient Animation */
                @keyframes gradient {
                    0% {
                        background-position: 0% 50%;
                    }

                    50% {
                        background-position: 100% 50%;
                    }

                    100% {
                        background-position: 0% 50%;
                    }
                }

                /* Particle Base */
                .particle {
                    position: absolute;
                    opacity: 0.8;
                    animation: floatParticles linear infinite;
                    z-index: 1;

                }

                /* Circle Shape */
                .circle {
                    width: 12px;
                    height: 12px;
                    border-radius: 50%;
                    background-color: rgba(255, 255, 255, 0.6);
                    animation-duration: 14s;
                    z-index: 1;

                }

                /* Hexagon Shape */
                .hexagon {
                    width: 10px;
                    height: 10px;
                    background-color: rgba(255, 255, 255, 0.6);
                    clip-path: polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%);
                    animation-duration: 16s;
                    z-index: 1;

                }

                /* Diamond Shape */
                .diamond {
                    width: 10px;
                    height: 10px;
                    background-color: rgba(255, 255, 255, 0.6);
                    transform: rotate(45deg);
                    animation-duration: 18s;
                    z-index: 1;

                }

                /* Floating Animation */
                /* @keyframes floatParticles {
                                                                                                                                                                                                                                                                                                                                                                                                            0% {
                                                                                                                                                                                                                                                                                                                                                                                                                transform: translateY(100vh) translateX(0) scale(1);
                                                                                                                                                                                                                                                                                                                                                                                                                opacity: 0.5;
                                                                                                                                                                                                                                                                                                                                                                                                            }

                                                                                                                                                                                                                                                                                                                                                                                                            50% {
                                                                                                                                                                                                                                                                                                                                                                                                                opacity: 1;
                                                                                                                                                                                                                                                                                                                                                                                                            }

                                                                                                                                                                                                                                                                                                                                                                                                            100% {
                                                                                                                                                                                                                                                                                                                                                                                                                transform: translateY(-10vh) translateX(30px) scale(1.2);
                                                                                                                                                                                                                                                                                                                                                                                                                opacity: 0;
                                                                                                                                                                                                                                                                                                                                                                                                            }
                                                                                                                                                                                                                                                                                                                                                                                                        } */

                /* Popup container */
                .popup {
                    position: fixed;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    background: rgba(0, 0, 0, 0.5);
                    display: none;
                    justify-content: center;
                    align-items: center;
                    z-index: 10;
                    backdrop-filter: blur(10px);
                }

                /* Popup content */
                .popup-content {
                    background: rgba(255, 255, 255);
                    padding: 2vw;
                    border-radius: 10px;
                    width: 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: 1em;
                    color: black;
                    margin: 0vw 0vw 2vw 0vw;
                }

                .login_inputs {
                    border: 1px solid rgb(5, 41, 109);
                    /* border-bottom: 5px solid; */
                    border-radius: 2vw;
                    padding-left: 17px;
                    background: #4a90e2;
                    outline: none;
                    /* font-size: 4vw; */
                    /* height: 11vw; */
                    font-size: 2.5em;
                    height: 15vw;
                    color: black;
                    margin: 0vw 0vw 2vw 0vw;
                }

                .header {
                    /* font-size: 11vw; */
                    font-size: 4em;
                    color: black;
                    margin: 2vw 0vw;

                }

                .submit_btn {
                    font-size: 1em;
                    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: 1em;
                    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 #01b9f5;
                    background: white;
                    width: 18vw;
                    height: 6vh;
                    color: #145693;
                    border-radius: 0.8vw;
                    overflow: auto;
                    z-index: 2;
                    text-transform: uppercase;
                }

                button:hover {
                    /* scale: 1.1; */
                    transition: all 0.5s ease-in-out;
                    /* box-shadow: 0px 15px 10px rgba(0, 0, 0, 1); */
                    background: #145693;
                    color: white;
                    border: 3px solid white;
                }

                /* button:not(:hover) {
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    scale: 1;
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    transition: all 0.5s ease-in-out;
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                } */

                .login_btn {
                    /* font-size: 3.25vw; */
                    font-size: 1em;
                    overflow: hidden;
                    /* border-radius: 1vw; */
                    /* margin: 3vw auto; */
                    /* margin: 2vw auto; */
                    /* cursor: pointer; */
                    border: 3px solid white;
                    background: linear-gradient(45deg, rgb(0, 195, 255), rgb(5, 41, 109), rgb(141, 224, 255), rgb(0, 0, 0));
                    background-size: 400% 400%;
                    animation: gradient 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;
                }

                .login_btn:not(:hover) {
                    /* scale: 1; */
                    transition: all 0.5s ease-in-out;
                }

                .text {
                    font-size: 1em;
                    color: white;
                }

                .text1 {
                    font-size: 1em;
                    color: Black;
                }

                .logo {
                    margin: 1vw;
                    width: 100%;
                    cursor: pointer;
                }

                .dropdown {
                    display: none;
                    flex-direction: column;
                    background-color: darkgrey;
                    /* background-color: #145693; */
                    border: 3px solid white;
                    border-top: none;
                    width: 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: 1em;
                    color: white;
                    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: #145693;
                }

                .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-color: #4a90e2;
                    background: linear-gradient(45deg, rgb(0, 195, 255), rgb(5, 41, 109), rgb(141, 224, 255), rgb(0, 0, 0));
                    background-size: 400% 400%;
                    animation: gradient 20s ease infinite;
                    display: flex;
                    flex-direction: row;
                    flex-wrap: wrap;
                    align-content: space-around;
                    justify-content: center;
                    overflow: hidden;
                    /* Prevents overflow */
                    position: relative;
                }

                /* Gradient Animation */
                @keyframes gradient {
                    0% {
                        background-position: 0% 50%;
                    }

                    50% {
                        background-position: 100% 50%;
                    }

                    100% {
                        background-position: 0% 50%;
                    }
                }

                /* Particle Base */
                .particle {
                    position: absolute;
                    opacity: 0.8;
                    animation: floatParticles linear infinite;
                    z-index: 1;

                }

                /* Circle Shape */
                .circle {
                    width: 12px;
                    height: 12px;
                    border-radius: 50%;
                    background-color: rgba(255, 255, 255, 0.6);
                    animation-duration: 14s;
                    z-index: 1;

                }

                /* Hexagon Shape */
                .hexagon {
                    width: 10px;
                    height: 10px;
                    background-color: rgba(255, 255, 255, 0.6);
                    clip-path: polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%);
                    animation-duration: 16s;
                    z-index: 1;

                }

                /* Diamond Shape */
                .diamond {
                    width: 10px;
                    height: 10px;
                    background-color: rgba(255, 255, 255, 0.6);
                    transform: rotate(45deg);
                    animation-duration: 18s;
                    z-index: 1;

                }

                /* Floating Animation */
                /* @keyframes floatParticles {
                                                                                                                                                                                                                                                                                                                                                                                                            0% {
                                                                                                                                                                                                                                                                                                                                                                                                                transform: translateY(100vh) translateX(0) scale(1);
                                                                                                                                                                                                                                                                                                                                                                                                                opacity: 0.5;
                                                                                                                                                                                                                                                                                                                                                                                                            }

                                                                                                                                                                                                                                                                                                                                                                                                            50% {
                                                                                                                                                                                                                                                                                                                                                                                                                opacity: 1;
                                                                                                                                                                                                                                                                                                                                                                                                            }

                                                                                                                                                                                                                                                                                                                                                                                                            100% {
                                                                                                                                                                                                                                                                                                                                                                                                                transform: translateY(-10vh) translateX(30px) scale(1.2);
                                                                                                                                                                                                                                                                                                                                                                                                                opacity: 0;
                                                                                                                                                                                                                                                                                                                                                                                                            }
                                                                                                                                                                                                                                                                                                                                                                                                        } */

                /* Popup container */
                .popup {
                    position: fixed;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    background: rgba(0, 0, 0, 0.5);
                    display: none;
                    justify-content: center;
                    align-items: center;
                    z-index: 10;
                    backdrop-filter: blur(10px);
                }

                /* Popup content */
                .popup-content {
                    background: rgba(255, 255, 255);
                    padding: 2vw;
                    border-radius: 10px;
                    width: 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: 1em;
                    color: black;
                    margin: 0vw 0vw 2vw 0vw;
                }

                .login_inputs {
                    border: 1px solid rgb(5, 41, 109);
                    /* border-bottom: 5px solid; */
                    border-radius: 2vw;
                    padding-left: 17px;
                    background: #4a90e2;
                    outline: none;
                    /* font-size: 4vw; */
                    /* height: 11vw; */
                    font-size: 2.5em;
                    height: 15vw;
                    color: black;
                    margin: 0vw 0vw 2vw 0vw;
                }

                .header {
                    /* font-size: 11vw; */
                    font-size: 4em;
                    color: black;
                    margin: 2vw 0vw;

                }

                .submit_btn {
                    font-size: 1em;
                    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: 30.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: 1em;
                    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: 3em;
                    margin: 5vw 0vw 4vw 0vw;
                    cursor: pointer;
                    border: 3px solid #01b9f5;
                    background: white;
                    width: 29vw;
                    padding: 0.5em;
                    height: auto;
                    color: #145693;
                    border-radius: 0.8vw;
                    overflow: auto;
                    z-index: 2;
                    text-transform: uppercase;
                }

                button:hover {
                    /* scale: 1.1; */
                    transition: all 0.5s ease-in-out;
                    /* box-shadow: 0px 15px 10px rgba(0, 0, 0, 1); */
                    background: #145693;
                    color: white;
                    border: 3px solid white;
                }

                /* button:not(:hover) {
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    scale: 1;
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    transition: all 0.5s ease-in-out;
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                } */

                .login_btn {
                    /* font-size: 3.25vw; */
                    font-size: 1em;
                    overflow: hidden;
                    /* border-radius: 1vw; */
                    /* margin: 3vw auto; */
                    /* margin: 2vw auto; */
                    /* cursor: pointer; */
                    border: 3px solid white;
                    background: linear-gradient(45deg, rgb(0, 195, 255), rgb(5, 41, 109), rgb(141, 224, 255), rgb(0, 0, 0));
                    background-size: 400% 400%;
                    animation: gradient 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;
                }

                .login_btn:not(:hover) {
                    /* scale: 1; */
                    transition: all 0.5s ease-in-out;
                }

                .text {
                    font-size: 1em;
                    color: white;
                }

                .text1 {
                    font-size: 1em;
                    color: Black;
                }

                .logo {
                    margin: 1vw;
                    width: 100%;
                    cursor: pointer;
                }

                .dropdown {
                    display: none;
                    flex-direction: column;
                    background-color: darkgrey;
                    /* background-color: #145693; */
                    border: 3px solid white;
                    border-top: none;
                    width: 28vw;
                    /* margin-left: 3vw; */
                    margin-top: -4vw;
                    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: 1em;
                    color: white;
                    margin-bottom: 1vh;

                }


                .mini_btn {
                    margin: 2vw auto 2vw auto;
                    cursor: pointer;
                    border: 3px solid #80808000;
                    background: white;
                    width: 91%;
                    color: black;
                    padding: 0.5em;
                    height: auto;
                    overflow: hidden;
                    border-radius: 15px;
                    font-size: 3.2em;
                    box-shadow: -4px 4px 9px rgba(0, 0, 0, 1);
                    text-transform: uppercase;
                    overflow: hidden;
                }


                .frame {
                    height: 99.5%;
                    float: right;
                    width: 65.5%;
                    position: absolute;
                    right: 0;
                    top: 0;
                    overflow: hidden;
                    border: none;
                }

            }

            .mini_btn:hover {
                transition: all 0.5s ease-in-out;
                box-shadow: 0px 10px 10px rgba(0, 0, 0, 1);
                background: white;
                color: #145693;
            }

            .mini_btn:not(:hover) {
                transition: all 0.5s ease-in-out;
            }

            @media all and (min-width: 1050px) {

                body {
                    margin: 0;
                    background: linear-gradient(45deg, rgb(0, 195, 255), rgb(5, 41, 109), rgb(141, 224, 255), rgb(0, 0, 0));
                    background-size: 400% 400%;
                    animation: gradient 20s ease infinite;
                    display: flex;
                    flex-direction: row;
                    flex-wrap: wrap;
                    align-content: space-around;
                    justify-content: center;
                    overflow: hidden;
                    /* Prevents overflow */
                    position: relative;
                }

                /* Gradient Animation */
                @keyframes gradient {
                    0% {
                        background-position: 0% 50%;
                    }

                    50% {
                        background-position: 100% 50%;
                    }

                    100% {
                        background-position: 0% 50%;
                    }
                }

                /* Particle Base */
                .particle {
                    position: absolute;
                    opacity: 0.8;
                    animation: floatParticles linear infinite;
                    z-index: 1;

                }

                /* Circle Shape */
                .circle {
                    width: 12px;
                    height: 12px;
                    border-radius: 50%;
                    background-color: rgba(255, 255, 255, 0.6);
                    animation-duration: 14s;
                    z-index: 1;

                }

                /* Hexagon Shape */
                .hexagon {
                    width: 10px;
                    height: 10px;
                    background-color: rgba(255, 255, 255, 0.6);
                    clip-path: polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%);
                    animation-duration: 16s;
                    z-index: 1;

                }

                /* Diamond Shape */
                .diamond {
                    width: 10px;
                    height: 10px;
                    background-color: rgba(255, 255, 255, 0.6);
                    transform: rotate(45deg);
                    animation-duration: 18s;
                    z-index: 1;

                }

                /* Floating Animation */
                @keyframes floatParticles {
                    0% {
                        transform: translateY(100vh) translateX(0) scale(1);
                        opacity: 0.5;
                    }

                    50% {
                        opacity: 1;
                    }

                    100% {
                        transform: translateY(-10vh) translateX(30px) scale(1.2);
                        opacity: 0;
                    }
                }

                /* Popup container */
                .popup {
                    position: fixed;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    background: rgba(0, 0, 0, 0.5);
                    display: none;
                    justify-content: center;
                    align-items: center;
                    z-index: 10;
                    backdrop-filter: blur(10px);
                }

                /* Popup content */
                .popup-content {
                    background: rgba(255, 255, 255);
                    padding: 2vw;
                    border-radius: 10px;
                    width: 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: 1em;
                    color: black;
                    margin: 0vw 0vw 2vw 0vw;
                }

                .login_inputs {
                    border: 1px solid rgb(5, 41, 109);
                    /* border-bottom: 5px solid; */
                    border-radius: 2vw;
                    padding-left: 17px;
                    background: #4a90e2;
                    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: 2em;
                    color: black;
                    margin: 2vw 0vw;

                }

                .submit_btn {
                    font-size: 1em;
                    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: 1em;
                    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 #01b9f5;
                    background: white;
                    width: 18vw;
                    height: 6vh;
                    color: #145693;
                    border-radius: 0.8vw;
                    overflow: auto;
                    z-index: 2;
                    text-transform: uppercase;
                }

                button:hover {
                    /* scale: 1.1; */
                    transition: all 0.5s ease-in-out;
                    /* box-shadow: 0px 15px 10px rgba(0, 0, 0, 1); */
                    background: #145693;
                    color: white;
                    border: 3px solid white;
                }

                /* button:not(:hover) {
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    scale: 1;
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    transition: all 0.5s ease-in-out;
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                } */

                .login_btn {
                    /* font-size: 3.25vw; */
                    font-size: 1em;
                    overflow: hidden;
                    /* border-radius: 1vw; */
                    /* margin: 3vw auto; */
                    /* margin: 2vw auto; */
                    /* cursor: pointer; */
                    border: 3px solid white;
                    background: linear-gradient(45deg, rgb(0, 195, 255), rgb(5, 41, 109), rgb(141, 224, 255), rgb(0, 0, 0));
                    background-size: 400% 400%;
                    animation: gradient 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;
                }

                .login_btn:not(:hover) {
                    /* scale: 1; */
                    transition: all 0.5s ease-in-out;
                }

                .text {
                    font-size: 1em;
                    color: white;
                }

                .text1 {
                    font-size: 1em;
                    color: Black;
                }

                .logo {
                    margin: 1vw;
                    width: 100%;
                    cursor: pointer;
                }

                .dropdown {
                    display: none;
                    flex-direction: column;
                    background-color: darkgrey;
                    /* background-color: #145693; */
                    border: 3px solid white;
                    border-top: none;
                    width: 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: 1em;
                    color: white;
                    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: #145693;
                }

                .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>

        <script>
            document.addEventListener("DOMContentLoaded", function () {
                const particleCount = 25; // Adjust number of particles
                const shapes = ["particle", "circle", "hexagon", "diamond"];
                const body = document.body;

                for (let i = 0; i < particleCount; i++) {
                    let particle = document.createElement("div");
                    let shape = shapes[Math.floor(Math.random() * shapes.length)];
                    particle.classList.add("particle", shape);
                    // Randomize position, animation duration, and speed
                    particle.style.left = Math.random() * 100 + "vw";
                    particle.style.animationDuration = Math.random() * 10 + 10 + "s"; // Between 10-20s
                    particle.style.animationDelay = Math.random() * 10 + "s"; // Staggered animation start
                    particle.style.width = Math.random() * 5 + 2 + "vw";
                    particle.style.height = particle.style.width;
                    particle.style.opacity = 0;

                    // Randomize animation speed
                    particle.style.animationTimingFunction = `cubic-bezier(${Math.random() * 0.1 + 0.05}, ${Math.random() * 0.9 + 0.05}, ${Math.random() * 0.1 + 0.05}, ${Math.random() * 0.9 + 0.05})`;

                    body.appendChild(particle);
                }
            });

        </script>

        <?php
    }
}

class login_system
{

    /**
     * This is the destructor of the class login_system.
     * It will display a login form as a popup to the user if the user is not logged in.
     * It will also submit the login form if the user is logged in.
     * It will also check the login status of the user every second and log the user out if the user is not logged in.
     */
    public function __destruct()
    {
        ?>
        <div id="loginPopup" class="popup">
            <div class="popup-content">
                <h2 class="header">Login</h2>
                <form id="loginForm" style="display: flex; flex-direction: column;">
                    <input type="text" id="username" name="username" placeholder="Username" class="login_inputs" required>
                    <input type="password" id="password" name="password" placeholder="Password" class="login_inputs" required>

                    <button type="button" id="submit_btn" class="login_btn" onclick="submitLogin()">Submit</button>
                </form>
            </div>
        </div>


        <script>
            function checkLoginPopupExists() {
                return document.getElementById('loginPopup') !== null;
            }

            setInterval(function () {
                if (!checkLoginPopupExists()) {
                    window.location.reload();
                }
            }, 100);

            first_load();

            function first_load() {
                check_login_status();
                setInterval(check_login_status, 1000);
            }

            function logout() {
                window.location.href = 'logout.php';
            }

            function check_login_status() {
                var xhr = new XMLHttpRequest();
                xhr.open("POST", "login.php", true);
                xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                xhr.onreadystatechange = function () {
                    console.log(xhr.responseText); // Handle response from server
                    if (xhr.responseText == "0") {
                        showPopup();
                    }
                };
                xhr.send("login_check");
            }

            function submitLogin() {
                var username = document.getElementById('username').value;
                var password = document.getElementById('password').value;

                var xhr = new XMLHttpRequest();
                xhr.open("POST", "login.php", true);
                xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        // alert(xhr.responseText); // Handle response from server
                        if (xhr.responseText == 1) {
                            document.getElementById('loginPopup').style.display = 'none';
                            document.getElementById('username').value = "";
                            document.getElementById('password').value = "";
                            window.location.href = 'index.php';
                        } else {
                            alert("LOGIN FAILED PLEASE CHECH CREDENTIALS");
                        }
                    }
                };
                xhr.send("username=" + encodeURIComponent(username) + "&password=" + encodeURIComponent(password));
            }
        </script>
        <?php
    }
}

class online_check
{
    function __destruct()
    {
        ?>

        <div id="noInternetPopup" class="popup">
            <div class="popup-content">
                <h2 class="header">You are offline</h2>
                <p class="text1">Internet connection lost. <br>Please check your internet connection and Please try again.</p>
            </div>
        </div>
        <script>
            function checkInternetConnection() {
                if (navigator.onLine) {
                    console.log("The browser is online.");
                    document.getElementById('noInternetPopup').style.display = 'none';

                    return 1;
                } else {
                    console.log("The browser is offline.");
                    document.getElementById('noInternetPopup').style.display = 'flex';

                    return 0;
                }
            }

            setInterval(checkInternetConnection, 1000);
        </script>
        <?php
    }
}

class DashboardWidget
{
    private static $chartCounter = 0;

    public static function includeAssets()
    {
        return '
        <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap" rel="stylesheet">
        <style>
            body { font-family: "Inter", sans-serif; margin: 0; background: #f5f7fa; }
        
        </style>
        <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
        ';
    }

    private static function wrapBlock($content, $width, $height)
    {
        return "<div class='dashboard-block' style='width:$width; height:$height;'>$content</div>";
    }
    public static function circleGraph($title, $min, $max, $current, $icon = '🛢️', $width = '', $height = '')
    {
        $id = 'circleChart_' . self::$chartCounter++;
        $percentage = round(($current - $min) / ($max - $min) * 100);
        $percentage = max(0, min($percentage, 100));
        $displayText = "$percentage%";

        $used = $percentage;
        $remaining = 100 - $percentage;

        $content = "
    <style>
        #container_$id {
            position: relative;
            width: 100%;
            max-width: 250px;
            max-height: 250px;
            margin: 0 auto;
            aspect-ratio: 1 / 1;
        }
        #container_$id canvas {
            width: 100% !important;
            height: 100% !important;
        }
        #percentageText_$id {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            font-family: 'Inter', sans-serif;
            font-weight: bold;
            font-size: 2.5em;
            color: #333;
            pointer-events: none;
        }
    </style>

    <div class='dashboard-title'>$icon $title</div>
    <div style='text-align: center; font-size: 0.9em; color: #666;'>$current / $max</div>
    <div id='container_$id'>
        <div id='percentageText_$id'>$displayText</div>
        <canvas id='$id'></canvas>
    </div>

    <script src='https://cdn.jsdelivr.net/npm/chart.js'></script>
    <script>
        new Chart(document.getElementById('$id'), {
            type: 'doughnut',
            data: {
                labels: ['Used', 'Remaining'],
                datasets: [{
                    data: [$used, $remaining],
                    backgroundColor: ['#00c853', '#e0e0e0'],
                    borderWidth: 0
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                cutout: '70%',
                plugins: {
                    legend: { display: false },
                    tooltip: { enabled: false },
                    title: { display: false }
                }
            }
        });
    </script>";

        return self::wrapBlock($content, $width, $height);
    }

    public static function columnGraph($title, $dataArray, $width = '45vw', $height = '40vh')
    {
        $id = 'barChart_' . self::$chartCounter++;
        $labels = [];
        $values = [];
        foreach ($dataArray as $entry) {
            $labels[] = $entry[1];  // DateTime
            $values[] = (int) filter_var($entry[0], FILTER_SANITIZE_NUMBER_INT);
        }
        $labelsJS = json_encode($labels);
        $valuesJS = json_encode($values);
        $content = "
            <div class='dashboard-title'>$title</div>
            <canvas id='$id'></canvas>
            <script>
                new Chart(document.getElementById('$id'), {
                    type: 'bar',
                    data: {
                        labels: $labelsJS,
                        datasets: [{
                            label: 'Liters',
                            data: $valuesJS,
                            backgroundColor: '#42a5f5',
                            borderRadius: 5
                        }]
                    },
                    options: {
                        scales: {
                            y: { beginAtZero: true }
                        }
                    }
                });
            </script>";
        return self::wrapBlock($content, $width, $height);
    }

    public static function tableBlock($title, $headers, $rows, $width = '60vw', $height = 'auto')
    {
        $tableHeadings = '';
        foreach ($headers as $heading) {
            $tableHeadings .= "<th>$heading</th>";
        }
        $tableBody = '';
        foreach ($rows as $row) {
            $link = array_pop($row);
            $tableBody .= '<tr>';
            foreach ($row as $col) {
                $tableBody .= "<td>$col</td>";
            }
            $tableBody .= "<td><a href='$link' class='dashboard-button'>View</a></td></tr>";
        }

        $content = "
            <div class='dashboard-title'>$title</div>
            <table class='dashboard-table'>
                <thead><tr>$tableHeadings<th>Action</th></tr></thead>
                <tbody>$tableBody</tbody>
            </table>";
        return self::wrapBlock($content, $width, $height);
    }

    public static function textBlock($title, $text, $fontSize = '1rem', $width = '30vw', $height = '20vh')
    {
        $content = "
            <div class='dashboard-title'>$title</div>
            <p style='font-size: $fontSize; text-align:center; color: #555;'>$text</p>";
        return self::wrapBlock($content, $width, $height);
    }

    public static function lineGraph($title, $labels, $dataPoints, $labelName = 'Value', $width = '45vw', $height = '40vh')
    {
        $id = 'lineChart_' . self::$chartCounter++;
        $labelsJS = json_encode($labels);
        $dataJS = json_encode($dataPoints);
        $content = "
            <div class='dashboard-title'>$title</div>
            <canvas id='$id'></canvas>
            <script>
                new Chart(document.getElementById('$id'), {
                    type: 'line',
                    data: {
                        labels: $labelsJS,
                        datasets: [{
                            label: '$labelName',
                            data: $dataJS,
                            borderColor: '#009688',
                            backgroundColor: 'rgba(0,150,136,0.1)',
                            fill: true,
                            tension: 0.3
                        }]
                    },
                    options: {
                        scales: {
                            y: { beginAtZero: true }
                        }
                    }
                });
            </script>";
        return self::wrapBlock($content, $width, $height);
    }
}

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>


            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 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;
    function dev_mode()
    {
        $this->dev_mode = 1;
    }
    function on_success($message)
    {
        $this->on_success = $message;
    }
    // submit button handler to prevent double clicking and multiple form submission
    function function_name($function_name)
    {
        $this->function_name = $function_name;

    }

    function submit_btn_id($submit_btn_id)
    {

        $this->submit_btn_id = $submit_btn_id;
    }

    function select($table_name)
    {
        $this->table_name = $table_name;
        $this->type = "SELECT";

    }

    function insert($table_name)
    {
        $this->table_name = $table_name;
        $this->type = "INSERT";

    }

    function update($table_name)
    {
        $this->table_name = $table_name;
        $this->type = "UPDATE";

    }

    function delete($table_name)
    {
        $this->table_name = $table_name;
        $this->type = "DELETE";

    }
    function redirect($file_path)
    {
        $this->redirect = $file_path;
    }

    function exclude_inputs($excloded_colum_names)
    {
        $this->excloded_colum_names = $excloded_colum_names;
    }

    function add_column_and_value($add_column_and_value)
    {
        $this->add_column_and_value = $add_column_and_value;
    }

    function text_formaters($list_of_ids_for_text_formators)
    {
        $this->list_of_ids_for_text_formators = $list_of_ids_for_text_formators;
    }

    function return_columns($return_columns)
    {
        $this->return_columns = $return_columns;
    }

    function 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()
    {
        ?>
        <script>

            <?php if ($this->run_on_load == 1) {
                echo $this->function_name . "();";
            } ?>
            document.addEventListener('DOMContentLoaded', function () {
                var button = document.getElementById('<?php echo $this->submit_btn_id; ?>');
                if (button) {

                    button.addEventListener('click', function () {
                        console.log('test ----------------------------------');
                        button.disabled = true;
                        var originalText = button.textContent;
                        button.textContent = 'Loading...';
                        setTimeout(function () {
                            button.disabled = false;
                            button.textContent = originalText;
                        }, 5000);
                    });
                }
            });
            function <?php echo $this->function_name; ?>() {

                <?php if ($this->type == "INSERT" || $this->type == "UPDATE") { ?>
                    var requiredInputs = document.querySelectorAll(".form_down input[required], .form_down select[required], .form_down textarea[required], .search_form_top input[required], .search_form_top select[required], .search_form_top textarea[required], .search_form input[required], .search_form select[required], .search_form textarea[required]");
                    var isAllFilled = true;
                    requiredInputs.forEach(function (input) {
                        if (input.value == "") {
                            isAllFilled = false;
                            input.style.backgroundColor = "red";
                            input.focus();
                        } else {
                            input.style.backgroundColor = "";
                        }
                    });
                    if (!isAllFilled) {
                        return;
                    }
                <?php } ?>

                var data = {};
                var inputs = document.querySelectorAll(".form_down input, .form_down select, .form_down textarea, .search_form_top input, .search_form_top select, .search_form_top textarea, .search_form input, .search_form select, .search_form textarea");
                inputs.forEach(function (input) {
                    if (input.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 htmla
{
    public $idTag;

    /*************  ✨ Windsurf Command ⭐  *************/
    /**
     * Class constructor
     *
     * Outputs the meta viewport tag that will let the page scale properly
     * on mobile devices.
     *
     * @return void
     */
    /*******  3db448a2-12ef-4300-bc89-16a13668c39d  *******/
    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: 1em;
                border: 1px solid #ddd;
                border-radius: 4px;
                cursor: pointer;
                background-color: #f4f7fa;
            }

            .controls button:hover,
            .controls input:hover {
                background-color: #e0e0e0;
            }

            .controls input[type="file"] {
                display: none;
            }

            <?php echo "#" . $content_id_html_tag; ?>
                {
                background-color: #fff;
                border: 1px solid #ddd;
                padding: 20px;
                margin: 20px 0;
                min-height: 200px;
                box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
                border-radius: 4px;
            }

            <?php echo "#" . $content_id_html_tag; ?>
            img {
                max-width: 100%;
                height: auto;
                border-radius: 4px;
            }

            .content {
                max-width: 900px;
                margin: 20px auto;
                padding: 20px;
                background-color: #fff;
                border-radius: 6px;
                box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);
            }

            .controls button,
            .controls input {
                margin-right: 10px;
            }

            .controls input[type="file"] {
                display: none;
            }
        </style>

        <div class="content">
            <div id="<?php echo $content_id_html_tag; ?>" contenteditable="true">
            </div>
            <div class="controls">
                <button onclick="formatText_<?php echo $content_id_html_tag; ?>('bold')">Bold</button>
                <button onclick="formatText_<?php echo $content_id_html_tag; ?>('italic')">Italic</button>
                <button onclick="formatText_<?php echo $content_id_html_tag; ?>('underline')">Underline</button>
                <button onclick="formatText_<?php echo $content_id_html_tag; ?>('formatBlock', 'h1')">Heading
                    1</button>
                <button onclick="formatText_<?php echo $content_id_html_tag; ?>('formatBlock', 'h2')">Heading
                    2</button>
                <button onclick="formatText_<?php echo $content_id_html_tag; ?>('formatBlock', 'h3')">Heading
                    3</button>
                <button onclick="formatText_<?php echo $content_id_html_tag; ?>('formatBlock', 'p')">Normal
                    Font</button>
            </div>
        </div>



        <script>
            // Format the text (bold, italic, underline, headings)
            function formatText_<?php echo $content_id_html_tag; ?>(command, value = null) {
                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: 1em;
                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: 1em;
                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: 1em;
                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: 1em;
                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>
            </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);
                }
            }
            // Insert a checkbox at the current cursor position
            function insertCheckbox_<?php echo $content_id_html_tag; ?>() {
                const checkbox = document.createElement('input');
                checkbox.type = 'checkbox';
                // Important:  Try to preserve the ID, if it exists.
                const selection = window.getSelection();
                if (selection.rangeCount > 0) {
                    const range = selection.getRangeAt(0);
                    range.deleteContents();
                    range.insertNode(checkbox);
                    range.collapse(false);
                }
            }

            function getEditorContent_<?php echo $content_id_html_tag; ?>() {
                const editorContent = document.getElementById("<?php echo $content_id_html_tag; ?>").innerHTML;
                return editorContent;
            }

            function setEditorContent_<?php echo $content_id_html_tag; ?>(content) {
                document.getElementById("<?php echo $content_id_html_tag; ?>").innerHTML = content;
            }
        </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_jev')
    {
        $this->connection = mysqli_connect($host, $user, $password, $dbname);

        if (!$this->check_table_exists('logs')) {
            $sql = "CREATE TABLE IF NOT EXISTS logs (
                record_id INT AUTO_INCREMENT PRIMARY KEY,
                table_name TEXT,
                user_id INT(255),
                query TEXT,
                date_time VARCHAR(50)
            )";

            if (!mysqli_query($this->connection, $sql)) {
                return "Error creating table: " . mysqli_error($this->connection);
                exit();
            }
        }

        if (!$this->check_table_exists('users')) {
            $sql = "CREATE TABLE IF NOT EXISTS users (
                record_id INT AUTO_INCREMENT PRIMARY KEY,
                username TEXT,
                user_password TEXT
            )";

            if (!mysqli_query($this->connection, $sql)) {
                return "Error creating table: " . mysqli_error($this->connection);
                exit();
            }

            $sql = "INSERT INTO users (username, user_password) VALUES ('DEV', '4030fe15babb7045f9036c2316babda746af34b61e623354c61828526c4e2ad5')";

            if (!mysqli_query($this->connection, $sql)) {
                return "Error inserting first user: " . mysqli_error($this->connection);
                exit();
            }
        }

        if (mysqli_connect_errno()) {
            return "Failed to connect to MySQL: " . mysqli_connect_error();
            exit();
        }

    }

    function session_check()
    {
        if (strlen($_SESSION["user_id"]) >= 1) {
            return $_SESSION["user_id"];
        } else {
            return 0;
        }
    }

    /**
     * Logs in a user with the given username and password.
     *
     * @param string $username The username to log in with.
     * @param string $password The password to log in with.
     *
     * @return int 1 if the login was successful, 0 otherwise.
     */
    function login($username, $password)
    {
        $hash_pass = hash("SHA256", $password);
        $sql = "SELECT * FROM users WHERE username = '$username' AND `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["username"] = $row["username"];
            $_SESSION["access_type"] = $row["access_type"];
            $_SESSION["status"] = $row["status"];
            $_SESSION["company_id"] = $row["company_id"];
            $_SESSION["database_log"] = "hello";
            if ($row["status"] == 0) {
                return "0";
            } else {
                return 1;
            }
        } else {
            return "0";
        }
    }

    function check_table_exists($table)
    {
        $this->table_name = $table;
        $sql = "SHOW TABLES LIKE '$table' ";
        $result = mysqli_query($this->connection, $sql);

        if (mysqli_num_rows($result) > 0) {

            return true;

        } else {

            return false;

        }
    }

    public function select_query($table_name, $selector, $where_clause)
    {

        $this->sql = "SELECT $selector FROM $table_name WHERE $where_clause";

        if (!$this->check_table_exists($table_name)) {

            echo "[SQL] TABLE NAME DOES NOT EXIST OR IS INCORRECT $table_name";
            echo "[SQL QUERY FAILED]" . mysqli_error($this->connection) . "<br>";
            echo "[SQL QUERY]: " . $this->sql;

        }

        $result = mysqli_query($this->connection, $this->sql);


        if (mysqli_error($this->connection)) {

            echo "[SQL QUERY FAILED]" . mysqli_error($this->connection) . "<br>";
            echo "[SQL QUERY]: " . $this->sql;
            exit();
        } else {

            return $result;

        }
    }

    public function query($table_name, $sql)
    {
        $this->sql = $sql;
        $this->table_name = $table_name;
        if (!$this->check_table_exists($table_name)) {
            echo "[SQL] TABLE NAME DOES NOT EXIST OR IS INCORRECT $table_name";
        }
        $result = mysqli_query($this->connection, $this->sql);

        if (mysqli_error($this->connection)) {
            echo "[SQL QUERY FAILED] on " . $_SERVER['REQUEST_URI'] . " at line " . __LINE__ . ": " . mysqli_error($this->connection) . "<br>";
            echo "[SQL QUERY]: " . $sql;
            exit();
        } else {
            if (stripos(trim($sql), 'INSERT') === 0) {
                return mysqli_insert_id($this->connection);
            } else {
                return $result;
            }
        }
    }

    public function __destruct()
    {

        if (strlen($this->sql) > 1) {
            if (stripos(trim($this->sql), 'SELECT') !== 0) {
                $log_sql = "INSERT INTO logs (`table_name`,`user_id`,`query`,`date_time`) VALUES (\"$this->table_name\", \"{$_SESSION['user_id']}\", \"$this->sql\", NOW())";
                $_SESSION["database_log"];
                mysqli_query($this->connection, $log_sql);
            }
        }
        mysqli_close($this->connection);
    }
}

class authentication
{
    public $key;

    function __construct()
    {
        $this->key = "password";
    }
    function encrypt_password($password)
    {
        $cipher = "AES-256-CBC"; // Encryption cipher
        $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher)); // Generate IV
        $encrypted = openssl_encrypt($password, $cipher, $this->key, 0, $iv); // Encrypt the password

        // Combine encrypted password and IV for storage
        return base64_encode($encrypted . "::" . $iv);
    }

    function decrypt_password($encryptedPassword)
    {
        $cipher = "AES-256-CBC";
        list($encryptedData, $iv) = explode("::", base64_decode($encryptedPassword), 2);

        return openssl_decrypt($encryptedData, $cipher, $this->key, 0, $iv);
    }
}

class ajax
{
    function upload($file)
    {
        $target_dir = "/";
        $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
            echo "The file " . htmlspecialchars(basename($_FILES["fileToUpload"]["name"])) . " has been uploaded.";
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }

    function insert()
    {
        $table_name = $_POST['table_name'];
        $edit_file_name = $_POST['edit_file_name'];
        $returned_cols = explode(",", $_POST['return_columns']);
        $add_column_and_value = explode(",", $_POST['add_column_and_value']);
        if (count($add_column_and_value) > 0) {
            foreach ($add_column_and_value as $add_column_and_value) {
                $add_column_and_value = explode("=", $add_column_and_value);
                $_POST[$add_column_and_value[0]] = $add_column_and_value[1];
            }
        }
        $excloudedcolumns = explode(',', $_POST['excloded_colum_names']);
        if (count($excloudedcolumns) > 0) {
            foreach ($excloudedcolumns as $excloudedcolumn) {
                unset($_POST[$excloudedcolumn]);
            }
        }
        unset($_POST['excloded_colum_names']);
        unset($_POST['add_column_and_value']);
        unset($_POST['return_columns']);
        unset($_POST['edit_file_name']);
        unset($_POST['ajax_type']);
        unset($_POST['table_name']);
        unset($_POST['where_clause']);
        unset($_POST['submit']);
        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'])) {
            $_POST['password'] = hash('SHA256', $_POST['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'])) {
            $_POST['password'] = hash('SHA256', $_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();
        }
    }
}


// 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'] == "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;
        }
    }

}

?>