<?php
session_start();
require_once "PHPMailer.php";
require_once "SMTP.php";
require_once "Exception.php";
require_once "dashboard_class.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)
    {
        $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"
        ];


        $durationTasks = [];
        $tasks = []; // Initialize early so it's available for all sections

        ?>

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                    foreach ($tasks[$dateKey] as $task) {
                        if ($isHoliday && $task['public_holiday'] != '1')
                            continue;
                        $hidden_completed = ($task['completed'] == 1) ? "display: none" : "";
                        $completed_width_change = ($task['completed'] == 1) ? "width: 70%; height: 8%; 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) {
                h2 {
                    font-size: 0.4em;
                }

                table {
                    font-size: 0.4em !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: 3.15vw;
                    margin: 4px;
                    padding-left: 0.85vw;
                    display: flex;
                    flex-direction: row;
                    align-content: center;
                    justify-content: center;
                    align-items: center;
                    border-right: 1px solid black;
                }

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

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

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

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

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

                th {
                    background-color: #f3f3f3;
                }

                .day {
                    font-weight: bold;
                }

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


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

                }

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

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

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

                .holiday-label {
                    font-size: 0.4em;
                    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) {
                h2 {
                    font-size: 0.4em;
                }

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

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

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

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

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

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

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

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

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

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

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

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

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


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

                th {
                    background-color: #f3f3f3;
                }

                .day {
                    font-weight: bold;
                }

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

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

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

                }

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

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

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

                .holiday-label {
                    font-size: 0.4em;
                    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) {

                h2 {
                    font-size: 0.4em;
                }

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

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

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

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

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

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

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

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

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

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

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

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

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


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

                th {
                    background-color: #f3f3f3;
                }

                .day {
                    font-weight: bold;
                }

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


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

                }

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

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

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

                .holiday-label {
                    font-size: 0.4em;
                    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 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; }
            .dashboard-block {
                background: white;
                border-radius: 20px;
                box-shadow: 0 4px 20px rgba(0,0,0,0.05);
                padding: 20px;
                margin: 15px;
                display: flex;
                flex-direction: column;
                justify-content: center;
                overflow: auto;
            }
            .dashboard-title {
                font-size: 1.2rem;
                font-weight: 600;
                margin-bottom: 15px;
                color: #333;
                text-align: center;
            }
            .chart-container {
                width: 100%;
                height: 100%;
            }
            .dashboard-table {
                width: 100%;
                border-collapse: collapse;
                font-size: 0.95rem;
                color: #333;
            }
            .dashboard-table th {
                background: #007bff;
                color: white;
                padding: 10px;
                text-align: left;
            }
            .dashboard-table td {
                padding: 10px;
                border-bottom: 1px solid #eee;
            }
            .dashboard-button {
                padding: 6px 12px;
                background-color: #007bff;
                color: white;
                border: none;
                border-radius: 6px;
                text-decoration: none;
                transition: 0.3s;
            }
            .dashboard-button:hover {
                background-color: #0056b3;
            }
        </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 = '30vw', $height = '35vh')
    {
        $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_styles
{
    function __destruct()
    {
        ?>
        <style>
            @media all and (max-width: 650px) {

                body {
                    margin: 0;
                    background: linear-gradient(45deg, rgb(0 149 218), rgb(92 27 19), rgb(214 61 39), rgb(15 46 61));
                    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: 2vw;
                    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: 2em;
                    height: 15vw;
                    color: black;
                    margin: 0vw 0vw 2vw 0vw;
                }

                .header {
                    /* font-size: 11vw; */
                    font-size: 5vw;
                    color: black;
                    margin: 2vw 0vw;

                }

                .submit_btn {
                    font-size: 2vw;
                    color: white;
                    cursor: pointer;
                    background: transparent;
                    border: 3px solid;
                    border-radius: 15px;
                    outline: none;
                    width: 80%;
                    margin: 0vw auto;
                }

                .submit_btn:hover {
                    scale: 1.1;
                    transition: all 0.5s ease-in-out;
                    box-shadow: 0px 15px 10px rgba(0, 0, 0, 1);
                }

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

                .container {
                    display: flex;
                    flex: 1 1 auto;
                    z-index: 2;
                    height: 100%;

                }

                img {
                    width: 50px;
                    margin: 10px 0;
                }

                .sidebar {
                    width: 20.8%;
                    height: 100%;
                    background: black;
                    padding: 10px;
                    float: left;
                    position: absolute;
                    top: 0;
                    left: 0;
                    overflow-y: scroll;
                }

                .sidebar a {
                    text-decoration: none;
                    color: white;
                    font-size: 2vw;
                    margin: 10px 0;
                }

                .sidebar::-webkit-scrollbar {
                    width: 1em;
                }

                .sidebar::-webkit-scrollbar-track {
                    /* box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3); */
                    background-color: transparent;
                }

                .sidebar::-webkit-scrollbar-thumb {
                    background-image: url(images/scroll_icon.png);
                    background-size: 20px 100%;
                    background-repeat: no-repeat;
                }

                iframe {
                    width: 80vw;
                    /* Adjust size as needed */
                    height: 80vh;
                    border: none;
                    /* Removes default border */
                    background: transparent;
                }

                .transparent-iframe {
                    position: relative;
                    z-index: 10;
                    /* Ensures it stays above the background */
                    /* backdrop-filter: blur(10px); */
                    /* Adds a blur effect */
                }

                button {
                    font-size: 1em;
                    margin: 1vw auto;
                    cursor: pointer;
                    border: 3px solid #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: 2em;
                    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: 2vw;
                    color: white;
                }

                .text1 {
                    font-size: 2vw;
                    color: Black;
                }

                .logo {
                    margin: 1vw;
                    width: 100%;
                    cursor: pointer;
                }

                .dropdown {
                    display: none;
                    flex-direction: column;
                    background-color: darkgrey;
                    /* background-color: #145693; */
                    border: 3px solid white;
                    border-top: none;
                    width: 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: linear-gradient(45deg, rgb(0 149 218), rgb(92 27 19), rgb(214 61 39), rgb(15 46 61));
                    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: 2vw;
                    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: 2em;
                    height: 15vw;
                    color: black;
                    margin: 0vw 0vw 2vw 0vw;
                }

                .header {
                    /* font-size: 11vw; */
                    font-size: 5vw;
                    color: black;
                    margin: 2vw 0vw;

                }

                .submit_btn {
                    font-size: 2vw;
                    color: white;
                    cursor: pointer;
                    background: transparent;
                    border: 3px solid;
                    border-radius: 15px;
                    outline: none;
                    width: 80%;
                    margin: 0vw auto;
                }

                .submit_btn:hover {
                    scale: 1.1;
                    transition: all 0.5s ease-in-out;
                    box-shadow: 0px 15px 10px rgba(0, 0, 0, 1);
                }

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

                .container {
                    display: flex;
                    flex: 1 1 auto;
                    z-index: 2;
                    height: 100%;

                }

                img {
                    width: 50px;
                    margin: 10px 0;
                }

                .sidebar {
                    width: 20.8%;
                    height: 100%;
                    background: black;
                    padding: 10px;
                    float: left;
                    position: absolute;
                    top: 0;
                    left: 0;
                    overflow-y: scroll;
                }

                .sidebar a {
                    text-decoration: none;
                    color: white;
                    font-size: 2vw;
                    margin: 10px 0;
                }

                .sidebar::-webkit-scrollbar {
                    width: 1em;
                }

                .sidebar::-webkit-scrollbar-track {
                    /* box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3); */
                    background-color: transparent;
                }

                .sidebar::-webkit-scrollbar-thumb {
                    background-image: url(images/scroll_icon.png);
                    background-size: 20px 100%;
                    background-repeat: no-repeat;
                }

                iframe {
                    width: 80vw;
                    /* Adjust size as needed */
                    height: 80vh;
                    border: none;
                    /* Removes default border */
                    background: transparent;
                }

                .transparent-iframe {
                    position: relative;
                    z-index: 10;
                    /* Ensures it stays above the background */
                    /* backdrop-filter: blur(10px); */
                    /* Adds a blur effect */
                }

                button {
                    font-size: 1em;
                    margin: 1vw auto;
                    cursor: pointer;
                    border: 3px solid #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: 2em;
                    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: 2vw;
                    color: white;
                }

                .text1 {
                    font-size: 2vw;
                    color: Black;
                }

                .logo {
                    margin: 1vw;
                    width: 100%;
                    cursor: pointer;
                }

                .dropdown {
                    display: none;
                    flex-direction: column;
                    background-color: darkgrey;
                    /* background-color: #145693; */
                    border: 3px solid white;
                    border-top: none;
                    width: 16.5vw;
                    /* margin-left: 3vw; */
                    margin-top: -2vw;
                    position: relative;
                    /* bottom: 14px; */
                    z-index: 1;
                    padding: 0.5vw 0vw;
                    border-bottom-left-radius: 10px;
                    border-bottom-right-radius: 10px;
                    animation: dropdown 0.8s ease-in-out;
                }

                @keyframes dropdown {
                    from {
                        opacity: 0;
                        transform: translateY(-20px);
                    }

                    to {
                        opacity: 1;
                        transform: translateY(0);
                    }
                }

                .sub_2 {
                    text-align: center;
                    border-bottom: 1px solid #145693;
                    font-size: 1.8em;
                    color: 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;
                }

            }

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

                body {
                    margin: 0;
                    background: linear-gradient(45deg, rgb(0 149 218), rgb(92 27 19), rgb(214 61 39), rgb(15 46 61));
                    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: 2vw;
                    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: 5vw;
                    color: black;
                    margin: 2vw 0vw;

                }

                .submit_btn {
                    font-size: 2vw;
                    color: white;
                    cursor: pointer;
                    background: transparent;
                    border: 3px solid;
                    border-radius: 15px;
                    outline: none;
                    width: 80%;
                    margin: 0vw auto;
                }

                .submit_btn:hover {
                    scale: 1.1;
                    transition: all 0.5s ease-in-out;
                    box-shadow: 0px 15px 10px rgba(0, 0, 0, 1);
                }

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

                .container {
                    display: flex;
                    flex: 1 1 auto;
                    z-index: 2;
                    height: 100%;

                }

                img {
                    width: 50px;
                    margin: 10px 0;
                }

                .sidebar {
                    width: 20.8%;
                    height: 100%;
                    background: black;
                    padding: 10px;
                    float: left;
                    position: absolute;
                    top: 0;
                    left: 0;
                    overflow-y: scroll;
                }

                .sidebar a {
                    text-decoration: none;
                    color: white;
                    font-size: 2vw;
                    margin: 10px 0;
                }

                .sidebar::-webkit-scrollbar {
                    width: 1em;
                }

                .sidebar::-webkit-scrollbar-track {
                    /* box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3); */
                    background-color: transparent;
                }

                .sidebar::-webkit-scrollbar-thumb {
                    background-image: url(images/scroll_icon.png);
                    background-size: 20px 100%;
                    background-repeat: no-repeat;
                }

                iframe {
                    width: 80vw;
                    /* Adjust size as needed */
                    height: 80vh;
                    border: none;
                    /* Removes default border */
                    background: transparent;
                }

                .transparent-iframe {
                    position: relative;
                    z-index: 10;
                    /* Ensures it stays above the background */
                    /* backdrop-filter: blur(10px); */
                    /* Adds a blur effect */
                }

                button {
                    font-size: 1em;
                    margin: 1vw auto;
                    cursor: pointer;
                    border: 3px solid #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: 2em;
                    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: 2vw;
                    color: white;
                }

                .text1 {
                    font-size: 2vw;
                    color: Black;
                }

                .logo {
                    margin: 1vw;
                    width: 100%;
                    cursor: pointer;
                }

                .dropdown {
                    display: none;
                    flex-direction: column;
                    background-color: darkgrey;
                    /* background-color: #145693; */
                    border: 3px solid white;
                    border-top: none;
                    width: 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: 77.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 vehicle_lisence_scanner
{
    function __construct($id_to_give_data_to)
    {
        ?>
        <style>
            body {
                font-family: Arial, sans-serif;
                background: #f4f4f4;
                display: flex;
                flex-direction: column;
                align-items: center;
                padding: 20px;
            }

            .scanner-container {
                position: relative;
                width: 40vw;
                height: 20vh;
            }

            video {
                width: 100%;
                height: 100%;
                border: 4px solid #ccc;
                border-radius: 8px;
                object-fit: cover;
            }

            .overlay-box {
                position: absolute;
                top: 25%;
                left: 10%;
                width: 80%;
                height: 50%;
                border: 3px dashed red;
                border-radius: 5px;
                pointer-events: none;
                transition: border-color 0.3s;
            }

            .overlay-box.success {
                border-color: limegreen;
            }

            #output {
                margin-top: 15px;
                font-size: 1.1em;
                color: #333;
                text-align: center;
                white-space: pre-wrap;
                min-height: 100px;
                max-width: 400px;
            }

            .controls {
                margin-top: 15px;
                width: 400px;
                display: flex;
                justify-content: space-around;
                gap: 20px;
            }

            .control-group {
                display: flex;
                flex-direction: column;
                align-items: center;
            }

            .control-group label {
                font-weight: bold;
                margin-bottom: 8px;
            }

            .btn-group {
                display: flex;
                gap: 10px;
            }

            button {
                font-size: 1.5rem;
                width: 18vw;
                height: 6vw;
                border: none;
                border-radius: 5px;
                cursor: pointer;
                background-color: #007bff;
                color: white;
                user-select: none;
                transition: background-color 0.3s;
            }

            button:disabled {
                background-color: #999;
                cursor: not-allowed;
            }

            button:hover:not(:disabled) {
                background-color: #0056b3;
            }
        </style>
        </head>

        <body>
            <h2>Scan Your Vehicle Licence Disc</h2>
            <div class="scanner-container">
                <video id="video" autoplay muted playsinline></video>
                <div id="overlay" class="overlay-box"></div>
            </div>

            <div class="controls">
                <div class="control-group" id="zoomControl">
                    <label>Zoom</label>
                    <div class="btn-group">
                        <button id="zoomMinus" title="Zoom Out" disabled>−</button>
                        <button id="zoomPlus" title="Zoom In" disabled>+</button>
                    </div>
                </div>



            </div>

            <button id="focusMinus" title="Focus Near" disabled hidden>−</button>
            <button id="focusPlus" title="Focus Far" disabled hidden>+</button>
            <p id="output">📷 Align your disc within the box</p>

            <script type="module">
                import { BrowserPDF417Reader } from 'https://cdn.jsdelivr.net/npm/@zxing/browser@0.0.9/+esm';

                const videoElement = document.getElementById('video');
                const output = document.getElementById('output');
                const overlay = document.getElementById('overlay');

                // Zoom buttons
                const zoomMinusBtn = document.getElementById('zoomMinus');
                const zoomPlusBtn = document.getElementById('zoomPlus');

                // Focus buttons
                const focusMinusBtn = document.getElementById('focusMinus');
                const focusPlusBtn = document.getElementById('focusPlus');

                const codeReader = new BrowserPDF417Reader();
                let stream = null;
                let videoTrack = null;
                let lastResult = "";
                let lastSuccessTime = 0;
                let decoding = false;

                // Zoom levels in device zoom units, will map % to zoom capabilities later
                // These will be percentages as decimal, e.g. 0.15 means 15%
                // We'll find the closest available zoom level supported by the camera and map these.
                // But for now, store as an array and map to capabilities later
                const zoomLevelsPercent = [0.15, 0.50, 1.1]; // 15% to 110%
                let zoomIndex = 0;

                // Focus values as before (incremental steps)
                let focusValue = 0;
                let focusStep = 1;
                let focusMin = 0;
                let focusMax = 0;
                let focusSupported = false;

                function formatScannedData(rawText) {
                    const parts = rawText.split('%').filter(Boolean);
                    const labels = [
                        "Document Code",
                        "Code 2",
                        "Code 3",
                        "Code 4",
                        "Code 5",
                        "Registration Number",
                        "Code 7",
                        "Code 8",
                        "Vehicle Type",
                        "Make",
                        "Model",
                        "Color",
                        "VIN",
                        "Plate Number",
                        "Expiry Date"
                    ];

                    return parts.map((part, i) => {
                        const label = labels[i] || `Field ${i + 1}`;
                        return `${label}: ${part}`;
                    }).join("\n");
                }

                async function applySettings() {
                    if (!videoTrack) return;

                    const constraints = {};

                    // For zoom: map percent zoom to device zoom range
                    if (videoTrack.getCapabilities().zoom) {
                        const caps = videoTrack.getCapabilities();
                        const min = caps.zoom.min;
                        const max = caps.zoom.max;

                        // Map zoomLevelsPercent[zoomIndex] (like 0.15 to 1.1) linearly into [min,max]
                        // If max < 1.1, scale down accordingly
                        let targetZoom = zoomLevelsPercent[zoomIndex];
                        // Clamp targetZoom to [0,1]
                        targetZoom = Math.min(Math.max(targetZoom, 0), 1.1);

                        // Let's map 0 to min, 1.1 to max linearly
                        // Actually, we want to treat zoomLevelsPercent as relative values on max-min range
                        // The safest way is to scale targetZoom from 0.15-1.1 to min-max:

                        // Normalize zoomLevelsPercent array between its min and max
                        const zMinPercent = zoomLevelsPercent[0];
                        const zMaxPercent = zoomLevelsPercent[zoomLevelsPercent.length - 1];

                        // Map current zoomPercent to zoom value in [min, max]
                        let zoomValueMapped =
                            min + ((targetZoom - zMinPercent) / (zMaxPercent - zMinPercent)) * (max - min);

                        // Clamp zoomValueMapped
                        zoomValueMapped = Math.min(Math.max(zoomValueMapped, min), max);

                        constraints.zoom = zoomValueMapped;
                    }

                    if (focusSupported) {
                        constraints.focusDistance = focusValue;
                    }

                    try {
                        await videoTrack.applyConstraints(constraints);
                    } catch (e) {
                        console.warn('Failed to apply constraints:', e);
                    }
                }

                // Update button states (disable if at min/max)
                function updateButtonStates() {
                    zoomMinusBtn.disabled = zoomIndex <= 0;
                    zoomPlusBtn.disabled = zoomIndex >= zoomLevelsPercent.length - 1;

                    if (focusSupported) {
                        focusMinusBtn.disabled = focusValue <= focusMin;
                        focusPlusBtn.disabled = focusValue >= focusMax;
                    }
                }

                zoomMinusBtn.addEventListener('click', async () => {
                    if (zoomIndex > 0) {
                        zoomIndex--;
                        await applySettings();
                        updateButtonStates();
                    }
                });

                zoomPlusBtn.addEventListener('click', async () => {
                    if (zoomIndex < zoomLevelsPercent.length - 1) {
                        zoomIndex++;
                        await applySettings();
                        updateButtonStates();
                    }
                });

                focusMinusBtn.addEventListener('click', async () => {
                    focusValue = Math.max(focusMin, focusValue - focusStep);
                    await applySettings();
                    updateButtonStates();
                });

                focusPlusBtn.addEventListener('click', async () => {
                    focusValue = Math.min(focusMax, focusValue + focusStep);
                    await applySettings();
                    updateButtonStates();
                });

                async function startCamera() {
                    try {
                        stream = await navigator.mediaDevices.getUserMedia({
                            video: {
                                facingMode: 'environment',
                                width: { ideal: 1270 },
                                height: { ideal: 720 }
                            }
                        });
                        videoElement.srcObject = stream;
                        videoTrack = stream.getVideoTracks()[0];

                        const capabilities = videoTrack.getCapabilities();

                        // Setup zoom controls
                        if (capabilities.zoom) {
                            // Ensure zoomLevelsPercent values are reasonable for device min/max
                            // If device max < 1.1, clamp zoomLevelsPercent max accordingly
                            const maxZoom = capabilities.zoom.max;
                            const minZoom = capabilities.zoom.min;

                            // Adjust zoomLevelsPercent array so max doesn't exceed device max zoom
                            for (let i = 0; i < zoomLevelsPercent.length; i++) {
                                if (zoomLevelsPercent[i] * maxZoom > maxZoom) {
                                    zoomLevelsPercent[i] = maxZoom;
                                }
                            }

                            zoomIndex = 0;
                            zoomMinusBtn.disabled = false;
                            zoomPlusBtn.disabled = false;
                        } else {
                            zoomMinusBtn.disabled = true;
                            zoomPlusBtn.disabled = true;
                        }

                        // Setup focus controls
                        if (capabilities.focusDistance) {
                            focusSupported = true;
                            focusMin = capabilities.focusDistance.min;
                            focusMax = capabilities.focusDistance.max;
                            focusStep = capabilities.focusDistance.step || 1;
                            focusValue = focusMin;

                            focusMinusBtn.disabled = false;
                            focusPlusBtn.disabled = false;
                        } else if (capabilities.focusMode && capabilities.focusMode.includes('manual')) {
                            focusSupported = true;
                            focusMin = 0;
                            focusMax = 100;
                            focusStep = 1;
                            focusValue = 0;

                            focusMinusBtn.disabled = false;
                            focusPlusBtn.disabled = false;
                        } else {
                            focusSupported = false;
                            focusMinusBtn.disabled = true;
                            focusPlusBtn.disabled = true;
                        }

                        await applySettings();
                        updateButtonStates();

                        // Start decoding loop
                        decodeLoop();

                    } catch (err) {
                        output.textContent = `Error starting video stream: ${err.message}`;
                    }
                }

                async function decodeLoop() {
                    if (!stream) return;

                    if (decoding) {
                        requestAnimationFrame(decodeLoop);
                        return;
                    }
                    decoding = true;

                    try {
                        const result = await codeReader.decodeOnceFromVideoElement(videoElement);
                        if (result && result.text && result.text !== lastResult) {
                            lastResult = result.text;
                            lastSuccessTime = Date.now();

                            overlay.classList.add('success');
                            output.textContent = formatScannedData(lastResult);
                        }
                    } catch (err) {
                        // No code found in this frame; keep scanning.
                        overlay.classList.remove('success');
                    } finally {
                        decoding = false;
                        requestAnimationFrame(decodeLoop);
                    }
                }

                startCamera();
            </script>
            <?php
    }
}
class login_system
{

    /**
     * This is the destructor of the class login_system.
     * It will display a login form as a popup to the user if the user is not logged in.
     * It will also submit the login form if the user is logged in.
     * It will also check the login status of the user every second and log the user out if the user is not logged in.
     */
    public function __destruct()
    {
        ?>
            <div id="loginPopup" class="popup">
                <div class="popup-content">
                    <h2 class="header">Login</h2>
                    <form id="loginForm" style="display: flex; flex-direction: column;">
                        <input type="text" id="username" name="username" placeholder="Username" class="login_inputs" required>
                        <input type="password" id="password" name="password" placeholder="Password" class="login_inputs"
                            required>

                        <button type="button" id="submit_btn" class="login_btn" onclick="submitLogin()">Submit</button>
                    </form>
                </div>
            </div>



            <script>
                first_load();
                function showPopup() {
                    document.getElementById('loginPopup').style.display = 'flex';
                }
                function first_load() {
                    check_login_status();
                    setInterval(check_login_status, 1000);
                }

                function logout() {
                    window.location.href = 'logout.php';
                }

                function check_login_status() {
                    var xhr = new XMLHttpRequest();
                    xhr.open("POST", "login.php", true);
                    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                    xhr.onreadystatechange = function () {
                        console.log(xhr.responseText); // Handle response from server
                        if (xhr.responseText == "0") {
                            showPopup();
                        }
                    };
                    xhr.send("login_check");
                }

                function submitLogin() {
                    var username = document.getElementById('username').value;
                    var password = document.getElementById('password').value;

                    var xhr = new XMLHttpRequest();
                    xhr.open("POST", "login.php", true);
                    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                    xhr.onreadystatechange = function () {
                        if (xhr.readyState === 4 && xhr.status === 200) {
                            // alert(xhr.responseText); // Handle response from server
                            if (xhr.responseText == 1) {
                                document.getElementById('loginPopup').style.display = 'none';
                                document.getElementById('username').value = "";
                                document.getElementById('password').value = "";
                                window.location.href = 'index.php';
                            } else {
                                alert("LOGIN FAILED PLEASE CHECH CREDENTIALS");
                            }
                        }
                    };
                    xhr.send("username=" + encodeURIComponent(username) + "&password=" + encodeURIComponent(password));
                }
            </script>
            <?php
    }
}

class online_check
{
    function __destruct()
    {
        ?>

            <div id="noInternetPopup" class="popup">
                <div class="popup-content">
                    <h2 class="header">You are offline</h2>
                    <p class="text1">Internet connection lost. <br>Please check your internet connection and Please try again.
                    </p>
                </div>
            </div>
            <script>
                function checkInternetConnection() {
                    if (navigator.onLine) {
                        console.log("The browser is online.");
                        document.getElementById('noInternetPopup').style.display = 'none';

                        return 1;
                    } else {
                        console.log("The browser is offline.");
                        document.getElementById('noInternetPopup').style.display = 'flex';

                        return 0;
                    }
                }

                setInterval(checkInternetConnection, 1000);
            </script>
            <?php
    }
}

class navbar
{

    /**
     * Generates the basic HTML structure for the sidebar
     * 
     * This function is the constructor for the navbar class and is called when an object of the class is created.
     * It creates the basic HTML structure for the sidebar, which includes a container div and a sidebar div.
     * The container div contains the sidebar div, which contains the logo and the navigation menu.
     * The navigation menu is created by calling the add_menu_item method.
     * The logo is added by calling the add_logo method.
     */
    function __construct()
    {
        ?>
            <div class="container">
                <div class="sidebar">
                    <div style="display: flex; flex-direction: column; align-items: center;">
                        <?php
    }

    /**
     * Adds the logo to the sidebar
     * 
     * This function adds the logo to the sidebar. The logo is a clickable image that redirects the user to the home page.
     */
    function add_logo($file_path = "icons/logo.svg", $link = "")
    {
        ?>
                        <img src="<?php echo $file_path; ?>" alt="Logo" onclick="change_to('<?php echo $link; ?>');"
                            class="logo">
                        <?php

    }

    /**
     * Opens a group of menu items in the sidebar
     * 
     * This function creates a button with the name of the group, and a dropdown div with the same name.
     * When the button is clicked, the dropdown is shown or hidden.
     * The dropdown div contains the menu items for the group, which are added by calling the add_button method.
     * @param string $name The name of the group
     */
    function open_group($name)
    {
        ?>
                        <button onclick="dropdown('<?php echo $name; ?>')"><?php echo $name; ?></button>
                        <div class="dropdown" id="<?php echo $name; ?>">
                            <?php
    }

    /**
     * Adds a heading to the sidebar
     * 
     * This function outputs an HTML heading element with the specified name.
     * The heading is styled with the class "sub_2".
     * 
     * @param string $name The text to be displayed as the heading
     */

    function add_heading($name)
    {

        ?>
                            <h2 class="sub_2"><?php echo $name; ?>
                            </h2>
                            <?php
    }
    /**
     * Adds a button to the sidebar
     * 
     * This function adds a button to the sidebar with the specified name and ID.
     * The button is styled with the class "mini_btn".
     * When the button is clicked, the page is redirected to the URL specified in the $page_path parameter.
     * If the $button_text parameter is not empty, the button text is set to that value, otherwise the button text is set to the $name parameter.
     * @param string $name The name of the button
     * @param string $page_path The URL to redirect to when the button is clicked
     * @param string $button_html_id The ID of the button
     * @param string $button_text The text to be displayed on the button, if not empty
     */
    function add_button($name, $page_path, $button_html_id, $button_text = "")
    {
        ?>

                            <button onclick="change_to('<?php echo $page_path; ?>')" class="mini_btn"
                                id="<?php echo $button_html_id; ?>"><?php echo $button_text; ?></button>
                            <?php
    }

    /**
     * Adds a logout button to the sidebar
     * 
     * This function adds a button to the sidebar with the text "LOG OUT" and the class "mini_btn".
     * When the button is clicked, the logout function is called, which redirects the user to the logout page.
     */
    function add_logout_button()
    {
        ?>
                            <button onclick="logout()" class="mini_btn">LOG OUT</button>
                            <?php

    }

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

                            </div>
                            <button onclick="toggle_dev_mode()" class="mini_btn">DEV MODE</button>
                            <?php

    }

    /**
     * Closes the group div and dropdown div that were opened by open_group.
     * This function should be called after all the buttons for the group have been added.
     * It is called automatically by the destructor of this class.
     */
    function end_group()
    {
        ?>
                        </div>
                        <?php
    }

    function navbar_end()
    {
        ?>
                    </div>
                </div>
                <script>
                    function change_to(url) {
                        document.getElementById("app_frame").src = url;
                    }
                    var set = 0;
                    var input_n = document.getElementById("username");
                    var input_p = document.getElementById("password");

                    function dropdown(id) {
                        var dropdowns = document.querySelectorAll(".dropdown");
                        dropdowns.forEach(function (el) {
                            if (el.id != id) {
                                el.style.transition = "all 0.5s ease-in-out";
                                setTimeout(function () {
                                    el.style.display = "none";
                                }, 500);
                            }
                        });
                        document.getElementById(id).style.display = document.getElementById(id).style.display == "flex" ? "none" : "flex";
                    }


                    // setInterval(get_dev_console, 1000);
                    // function get_dev_console() {
                    //     console.log("get_dev_console");
                    //     var xhr = new XMLHttpRequest();
                    //     xhr.open("POST", "root.class.php", true);
                    //     xhr.onload = function () {
                    //         if (xhr.status === 200) {
                    //             document.getElementById('dev_mode').innerHTML = xhr.responseText;
                    //             console.log(xhr.responseText);

                    //         } else {
                    //             console.error("Error:", xhr.statusText);
                    //         }
                    //     };
                    //     xhr.send("ajax_type=dev_mode_check");
                    // }
                    // function toggle_dev_mode() {
                    //     document.getElementById('dev_mode').style.display = document.getElementById('dev_mode').style.display == "none" ? "block" : "none";
                    // }
                </script>
                <?php
    }

}

class select
{
    private $attributes = [];
    private $option = ["" => ""];

    private $value;

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

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

    function add_option($value, $label)
    {
        $this->option[$value] = $label;
    }

    function onchange($onchange)
    {
        $this->addAttribute('onchange', $onchange);
    }
    function onclick($onclick)
    {
        $this->addAttribute('onclick', $onclick);
    }
    function oninput($oninput)
    {
        $this->addAttribute('oninput', $oninput);
    }
    function required()
    {
        $this->addAttribute('required', 'required');
    }
    function disabled()
    {
        $this->addAttribute('disabled', 'disabled');

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

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

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

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

    function fill_from_db($table_name, $column_for_value, $column_for_label, $where_clause = ' 1 ')
    {
        $db = new db_safeguard();
        $query = "SELECT $column_for_value, $column_for_label FROM $table_name WHERE $where_clause ORDER BY $column_for_label ASC";
        $result = $db->query($table_name, $query);
        while ($row = $result->fetch_assoc()) {
            $this->option[$row[$column_for_value]] = $row[$column_for_label];
        }
    }

    function value_from_db($table_name, $value_column, $where_clause)
    {
        $db = new db_safeguard();
        $res = $db->query($table_name, "SELECT $value_column FROM $table_name WHERE $where_clause");
        $row = $res->fetch_assoc();
        $this->value = $row[$value_column];

    }
    function add()
    {
        if (!array_key_exists('class', $this->attributes)) {
            $this->class();
        }
        $select = "<select";
        foreach ($this->attributes as $key => $value) {
            $select .= " $key='$value'";
        }
        $select .= ">";

        foreach ($this->option as $value => $label) {
            $select .= "<option value='$value'>$label</option>";
        }

        $select .= "</select>";

        $select .= "<script>document.getElementById('" . $this->attributes['id'] . "').value = '" . $this->value . "';</script>";
        echo $select;
    }

}

class label
{
    private $attributes = [];

    private $value;

    function addAttribute($name, $value)
    {
        $this->attributes[$name] = $value;
    }
    function for($for)
    {
        $this->addAttribute('for', $for);
    }
    function value($text)
    {
        $this->value = $text;
    }
    function class($class = "labels")
    {
        $this->addAttribute('class', $class);
    }
    function add()
    {

        if (!array_key_exists('class', $this->attributes)) {
            $this->class();
        }
        $label = "<label";
        foreach ($this->attributes as $key => $value) {
            $label .= " $key='$value'";
        }
        $label .= ">" . $this->value;
        $label .= "</label>";
        echo $label;
    }

}

class input
{
    private $attributes = [];

    private $value;

    /**
     * Adds an attribute to the input element.
     * This function adds a single attribute to the input element. The attribute is
     * specified by the name and value parameters.
     * @param string $name The name of the attribute.
     * @param string $value The value of the attribute.
     */
    function addAttribute($name, $value)
    {
        $this->attributes[$name] = $value;
    }
    /**
     * Sets the name attribute for the input element.
     *
     * This function assigns a name attribute to the input element, which is used
     * to identify the input when the form is submitted. The name is specified by
     * the $name parameter.
     *
     * @param string $name The name of the input element.
     */

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

    function datalist($datalist_id)
    {
        $this->addAttribute('list', $datalist_id);
    }

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

    function onchange($onchange)
    {
        $this->addAttribute('onchange', $onchange);
    }
    function onkeyup($onchange)
    {
        $this->addAttribute('onkeyup', $onchange);
    }
    function onclick($onclick)
    {
        $this->addAttribute('onclick', $onclick);
    }
    function oninput($oninput)
    {
        $this->addAttribute('oninput', $oninput);
    }
    function required()
    {
        $this->addAttribute('required', 'required');
    }
    function disabled()
    {
        $this->addAttribute('disabled', 'disabled');

    }
    function readonly()
    {
        $this->addAttribute('readonly', 'readonly');
    }
    function autofocus()
    {
        $this->addAttribute('autofocus', 'autofocus');
    }
    function min($min)
    {
        $this->addAttribute('min', $min);
    }
    function max($max)
    {
        $this->addAttribute('max', $max);
    }
    function step($step)
    {
        $this->addAttribute('step', $step);
    }
    /**
     * Sets the pattern attribute for the input element.
     *
     * This function assigns a pattern attribute to the input element, which is
     * used to validate the input when the form is submitted. The pattern is
     * specified by the $pattern parameter.
     *
     * @param string $pattern The pattern to be used for validation.
     */
    function pattern($pattern)
    {
        $this->addAttribute('pattern', $pattern);
    }
    function placeholder($placeholder)
    {
        $this->addAttribute('placeholder', $placeholder);
    }

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


    }

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

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

    function value_from_db($table_name, $value_column, $where_clause)
    {
        $db = new db_safeguard();
        $res = $db->query($table_name, "SELECT $value_column FROM $table_name WHERE $where_clause");
        $row = $res->fetch_assoc();

        if (isset($this->attributes['id']) && $this->attributes['id'] == 'password') {
            $auth = new authentication();
            $this->value = $auth->decrypt_password($row[$value_column]);
        } else {
            $this->value = $row[$value_column];
        }

    }
    function type($type = "text")
    {
        $knownTypes = ['text', 'password', 'email', 'number', 'url', 'tel', 'search', 'color', 'date', 'datetime-local', 'month', 'week', 'time', 'checkbox', 'radio', 'file', 'hidden', 'image', 'button', 'reset', 'submit', 'range'];
        if (in_array($type, $knownTypes)) {
            $this->addAttribute('type', $type);
        } else {
            $this->value = "[HTML ERROR] - Unknown type: " . $type . " expected one of: " . implode(", ", $knownTypes);
            ;
        }
    }
    function add()
    {
        if (!array_key_exists('class', $this->attributes)) {
            $this->class();
        }

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

}

class button
{
    private $attributes = [];

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

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

    function onchange($onchange)
    {
        $this->addAttribute('onchange', $onchange);
    }
    function onclick($onclick)
    {
        $this->addAttribute('onclick', $onclick);
    }
    function oninput($oninput)
    {
        $this->addAttribute('oninput', $oninput);
    }
    function required()
    {
        $this->addAttribute('required', 'required');
    }
    function disabled()
    {
        $this->addAttribute('disabled', 'disabled');

    }

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

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

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

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

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

    function add()
    {
        if (!array_key_exists('id', $this->attributes)) {
            $this->id();
        }
        if (!array_key_exists('class', $this->attributes)) {
            $this->class();
        }
        $button = "<button";
        foreach ($this->attributes as $key => $value) {
            $button .= " $key='$value' ";
        }
        $button .= ">" . $this->value . "</button>";
        echo $button;
    }
}

class root
{

    /*************  ✨ Codeium Command 🌟  *************/
    public function Main_iframe($main_page = "")
    {
        // 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="<?php echo $main_page; ?>" id="app_frame" class="frame transparent-iframe">

                </iframe>
                <?php
    }
    /******  4b74866a-5ec7-44a1-8dcc-03aef436633f  *******/

    public function OnPageScripts()
    {
        ?>


                <script>
                </script>

                <?php
    }


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

class js_ajax
{

    private $table_name;
    private $type;
    private $redirect;
    private $excloded_colum_names;
    private $add_column_and_value;
    private $function_name;
    private $submit_btn_id;
    private $list_of_ids_for_text_formators;
    private $dev_mode = 0;
    private $return_columns;
    private $on_success;
    private $run_on_load = 0;
    function dev_mode()
    {
        $this->dev_mode = 1;
    }
    function on_success($message)
    {
        $this->on_success = $message;
    }
    // submit button handler to prevent double clicking and multiple form submission
    function function_name($function_name)
    {
        $this->function_name = $function_name;

    }

    function submit_btn_id($submit_btn_id)
    {

        $this->submit_btn_id = $submit_btn_id;
    }

    function select($table_name)
    {
        $this->table_name = $table_name;
        $this->type = "SELECT";

    }

    function insert($table_name)
    {
        $this->table_name = $table_name;
        $this->type = "INSERT";

    }

    function update($table_name)
    {
        $this->table_name = $table_name;
        $this->type = "UPDATE";

    }

    function delete($table_name)
    {
        $this->table_name = $table_name;
        $this->type = "DELETE";

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

    function exclude_inputs($excloded_colum_names)
    {
        $this->excloded_colum_names = $excloded_colum_names;
    }

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

    function text_formaters($list_of_ids_for_text_formators)
    {
        $this->list_of_ids_for_text_formators = $list_of_ids_for_text_formators;
    }

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

    function run_on_load()
    {
        $this->run_on_load = 1;
    }
    function __destruct()
    {
        ?>
                <script>

                    <?php if ($this->run_on_load == 1) {
                        echo $this->function_name . "();";
                    } ?>
                    document.addEventListener('DOMContentLoaded', function () {
                        var button = document.getElementById('<?php echo $this->submit_btn_id; ?>');
                        if (button) {

                            button.addEventListener('click', function () {
                                console.log('test ----------------------------------');
                                button.disabled = true;
                                var originalText = button.textContent;
                                button.textContent = 'Loading...';
                                setTimeout(function () {
                                    button.disabled = false;
                                    button.textContent = originalText;
                                }, 5000);
                            });
                        }
                    });
                    function <?php echo $this->function_name; ?>() {

                        <?php if ($this->type == "INSERT" || $this->type == "UPDATE") { ?>
                            var requiredInputs = document.querySelectorAll(".form_down input[required], .form_down select[required], .form_down textarea[required], .search_form_top input[required], .search_form_top select[required], .search_form_top textarea[required], .search_form input[required], .search_form select[required], .search_form textarea[required]");
                            var isAllFilled = true;
                            requiredInputs.forEach(function (input) {
                                if (input.value == "") {
                                    isAllFilled = false;
                                    input.style.backgroundColor = "red";
                                    input.focus();
                                } else {
                                    input.style.backgroundColor = "";
                                }
                            });
                            if (!isAllFilled) {
                                return;
                            }
                        <?php } ?>

                        var data = {};
                        var inputs = document.querySelectorAll(".form_down input, .form_down select, .form_down textarea, .search_form_top input, .search_form_top select, .search_form_top textarea, .search_form input, .search_form select, .search_form textarea");
                        inputs.forEach(function (input) {
                            if (input.value != "") {
                                if (input.id.includes("date_time")) {
                                    data[input.id] = input.value.replace("T", " ");
                                } else {
                                    data[input.id] = input.value;
                                }
                            }
                        });
                        data["ajax_type"] = "<?php echo $this->type; ?>";
                        data["table_name"] = "<?php echo $this->table_name; ?>";
                        data["edit_file_name"] = "<?php echo $this->redirect; ?>";
                        data["excloded_colum_names"] = "<?php echo $this->excloded_colum_names; ?>";
                        data["add_column_and_value"] = "<?php echo $this->add_column_and_value; ?>";


                        <?php
                        if (is_array($this->list_of_ids_for_text_formators) && count($this->list_of_ids_for_text_formators) > 0) {
                            foreach ($this->list_of_ids_for_text_formators as $list_of_id) {
                                ?> data["<?php echo $list_of_id; ?>"] = document.getElementById("<?php echo $list_of_id; ?>").innerHTML;

                                data = Object.keys(data).filter(key => !key.startsWith('imageInput_<?php echo $list_of_id; ?>')).reduce((obj, key) => {
                                    obj[key] = data[key];
                                    return obj;
                                }, {});
                                <?php
                            }
                        }

                        ?>

                        function popup(message) {
                            var popup = document.createElement('div');
                            popup.classList.add('popup');
                            popup.innerHTML = '<h2>' + message + '</h2><button class="submit_btn">OKAY</button>';
                            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);
                            document.body.appendChild(popup);
                            var closePopup = popup.querySelector('.submit_btn');
                            console.log("POPUP ADDED");
                            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 background1 = document.createElement('div');
                            background1.classList.add('background1');
                            background1.style.position = "fixed";
                            background1.style.top = "50%";
                            background1.style.left = "50%";
                            background1.style.transform = "translate(-50%, -50%)";
                            background1.style.width = "20%";
                            background1.style.height = "20%";
                            background1.style.background = "rgba(255, 255, 255, 0.8)";
                            background1.style.borderRadius = "10px";
                            background1.style.border = "2px solid #000"
                            background1.style.display = "flex";
                            background1.style.justifyContent = "center";
                            background1.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";
                            background1.appendChild(shape);
                            document.body.appendChild(background1);
                        };
                        xhr.onload = function () {
                            var background1 = document.querySelector('.background1');
                            background1.remove();
                            if (xhr.status === 200) {
                                if (xhr.responseText == "1" || xhr.responseText == 1) {
                                    <?php if ($this->dev_mode == true) { ?>
                                        popup(xhr.responseText);
                                        // alert(xhr.responseText); 
                                        console.log(xhr.responseText);
                                    <?php } else { ?>
                                        popup("<?php echo $this->on_success; ?>");
                                    <?php } ?>
                                } else {
                                    <?php if ($this->type == "SELECT") { ?>

                                        document.getElementById("ajax_response").innerHTML = xhr.responseText;
                                        document.getElementById("ajax_response").style.display = "flex";

                                    <?php } else { ?>

                                        popup(xhr.responseText);

                                    <?php } ?>

                                }
                            } else {
                                popup('Request failed.  Returned status of ' + xhr.status);
                            }
                        };

                        <?php if (is_array($this->return_columns) && count($this->return_columns) > 0) { ?>
                            data["return_columns"] = "<?php echo implode(",", $this->return_columns); ?>";
                        <?php } ?>
                        // Send the data as a URL-encoded string
                        xhr.send(Object.keys(data).map(function (key) {
                            return encodeURIComponent(key) + "=" + encodeURIComponent(data[key]);
                        }).join("&"));
                    }
                </script>

                <div id='ajax_response'
                    style="display: flex;flex-direction: row;flex-wrap: wrap;justify-content: space-around;align-content: space-around;">
                </div>
                <?php
    }



}

class html
{
    public $idTag;

    function __construct()
    {
        echo '<head><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"></head>';
    }
    public function prevent_enter_script()
    {
        ?>
                <script>
                    window.addEventListener('keydown', function (event) {
                        if (event.key === "Enter") {
                            event.preventDefault();
                        }
                    });
                </script>

                <?php
    }
    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 QRCodeScanner($qrCodeInputId, $index = 0)
    {
        $qrCodeInputId = htmlspecialchars($qrCodeInputId, ENT_QUOTES, 'UTF-8');

        $uniqueId = 'qrcode-scan-zone-' . $index;
        $activateButtonId = 'qrcode-activate-button-' . $index;
        $videoDisplayId = 'qrcode-video-display-' . $index;
        $videoStreamId = 'qrcode-video-streamer-' . $index;

        ?>
                <div id="<?php echo $uniqueId; ?>">
                    <button id="<?php echo $activateButtonId; ?>" class="submit_btn"
                        onclick="startQRCodeScanner(<?php echo $index; ?>)">SCAN QRCODE</button>
                    <div id="<?php echo $videoDisplayId; ?>" style="width: 300px; height: 300px; display: none;">
                        <video id="<?php echo $videoStreamId; ?>" 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>
                    function startQRCodeScanner(index) {
                        const displayArea = document.getElementById('qrcode-video-display-' + index);
                        const videoElement = document.getElementById('qrcode-video-streamer-' + index);
                        const activateButton = document.getElementById('qrcode-activate-button-' + index);
                        const targetInputId = '<?php echo $qrCodeInputId; ?>'; // Store input ID

                        displayArea.style.display = 'block';

                        navigator.mediaDevices.getUserMedia({ video: { facingMode: "environment" } })
                            .then((stream) => {
                                videoElement.srcObject = stream;
                                videoElement.play();

                                videoElement.onplay = function () {
                                    readQRCode(videoElement, targetInputId, activateButton, displayArea); // Pass more arguments
                                };
                            })
                            .catch((error) => {
                                console.error("Error accessing webcam:", error);
                                displayArea.style.display = 'none'; // Hide on error
                            });


                    }

                    function readQRCode(video, targetInputId, activateButton, displayArea) {
                        const canvasElement = document.createElement("canvas");
                        const canvasContext = canvasElement.getContext("2d");

                        canvasElement.width = video.width;
                        canvasElement.height = video.height;

                        function processVideoFrame() {
                            canvasContext.drawImage(video, 0, 0, canvasElement.width, canvasElement.height);
                            const imageData = canvasContext.getImageData(0, 0, canvasElement.width, canvasElement.height);
                            invertImageDataColors(imageData); // Keep the invert function
                            const qrResult = jsQR(imageData.data, canvasElement.width, canvasElement.height);

                            if (qrResult) {
                                document.getElementById(targetInputId).value = qrResult.data; // Use stored ID
                                activateButton.innerHTML = qrResult.data; // Update button
                                //alert("Scanned Code: " + qrResult.data); // Optional alert
                                video.srcObject.getTracks().forEach(track => track.stop());
                                displayArea.style.display = 'none';
                            } else {
                                requestAnimationFrame(processVideoFrame);
                            }
                        }
                        processVideoFrame();
                    }

                    function invertImageDataColors(imageData) { // Keep this function
                        const data = imageData.data;
                        for (let i = 0; i < data.length; i += 4) {
                            data[i] = 255 - data[i];
                            data[i + 1] = 255 - data[i + 1];
                            data[i + 2] = 255 - data[i + 2];
                        }
                        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 = "
        <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 = "<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 = "<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 = "<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 = "<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) {
                            ?>
                            var text = document.getElementById("<?php echo $list_of_id; ?>").innerHTML.replace(/(\s)\1+/g, '$1');
                            data["<?php echo $list_of_id; ?>"] = text.trim();

                            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="width: 100%;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 {

                        font-size: 1em;
                        border: 1px solid #ddd;
                        border-radius: 4px;
                        cursor: pointer;
                        width: 25%;
                        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: 400px;
                        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: 90vw;
                        width: 90%;
                        margin: 20px auto;
                        padding: 20px;
                        background-color: #fff;
                        border-radius: 6px;
                        box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);
                    }

                    .controls button,
                    .controls input {
                        margin-right: 10px;
                    }

                    .controls input[type="file"] {
                        display: none;
                    }
                </style>

                <div class="content">
                    <div id="<?php echo $content_id_html_tag; ?>" contenteditable="true">
                    </div>
                    <div class="controls">
                        <button onclick="formatText_<?php echo $content_id_html_tag; ?>('bold')">Bold</button>
                        <button onclick="formatText_<?php echo $content_id_html_tag; ?>('italic')">Italic</button>
                        <button onclick="formatText_<?php echo $content_id_html_tag; ?>('underline')">Underline</button>
                        <button onclick="formatText_<?php echo $content_id_html_tag; ?>('formatBlock', 'h1')">Heading 1</button>
                        <button onclick="formatText_<?php echo $content_id_html_tag; ?>('formatBlock', 'h2')">Heading 2</button>
                        <button onclick="formatText_<?php echo $content_id_html_tag; ?>('formatBlock', 'h3')">Heading 3</button>
                        <button onclick="formatText_<?php echo $content_id_html_tag; ?>('formatBlock', 'p')">Normal
                            Font</button>
                    </div>
                </div>


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

    }

    function image($content_id_html_tag = '')
    {
        ?>

                <style>
                    h1 {
                        margin: 0;
                    }

                    .controls {
                        background-color: #fff;
                        padding: 10px 20px;
                        border-bottom: 1px solid #ddd;
                        display: flex;
                        justify-content: flex-start;
                        align-items: center;
                        gap: 10px;
                        flex-wrap: wrap;
                    }

                    .controls button,
                    .controls input {
                        padding: 8px 15px;
                        font-size: 16px;
                        border: 1px solid #ddd;
                        border-radius: 4px;
                        cursor: pointer;
                        background-color: #f4f7fa;
                    }

                    .controls button:hover,
                    .controls input:hover {
                        background-color: #e0e0e0;
                    }

                    <?php echo "#" . $content_id_html_tag; ?>
                        {
                        background-color: #fff;
                        border: 1px solid #ddd;
                        padding: 20px;
                        margin: 20px 0;
                        min-height: 200px;
                        box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
                        border-radius: 4px;
                    }

                    <?php echo "#" . $content_id_html_tag; ?>
                    img {
                        max-width: 100%;
                        height: auto;
                        border-radius: 4px;
                    }

                    .content {
                        border: 3px solid grey;
                        /* max-width: 90%; */
                        width: 80%;
                        height: fit-content;
                        margin: 20px auto;
                        padding: 20px;
                        background-color: #fff;
                        border-radius: 1vw;
                        box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);
                    }

                    .controls input[type="file"] {
                        display: none;
                    }
                </style>

                <div class="content">
                    <div id="<?php echo $content_id_html_tag; ?>" style="display:none;" contenteditable="true"></div>
                    <div class="controls">
                        <input type="file" id="imageInput_<?php echo $content_id_html_tag; ?>" accept="image/*"
                            onchange="compressAndInsertImage_<?php echo $content_id_html_tag; ?>()" hidden>
                        <button
                            onclick="document.getElementById('<?php echo $content_id_html_tag; ?>').style.display = 'block';document.getElementById('imageInput_<?php echo $content_id_html_tag; ?>').click();">Add
                            Image</button>
                    </div>
                </div>

                <script>
                    async function compressBase64Image(base64Data, quality = 0.7, maxWidth = 800, maxHeight = 800) {
                        return new Promise((resolve, reject) => {
                            const img = new Image();
                            img.src = base64Data;

                            img.onload = () => {
                                let width = img.width;
                                let height = img.height;

                                if (width > maxWidth || height > maxHeight) {
                                    const aspectRatio = width / height;
                                    if (width > height) {
                                        width = maxWidth;
                                        height = Math.round(maxWidth / aspectRatio);
                                    } else {
                                        height = maxHeight;
                                        width = Math.round(maxHeight * aspectRatio);
                                    }
                                }

                                const canvas = document.createElement("canvas");
                                canvas.width = width;
                                canvas.height = height;
                                const ctx = canvas.getContext("2d");

                                ctx.drawImage(img, 0, 0, width, height);

                                const compressedBase64 = canvas.toDataURL("image/jpeg", quality);
                                resolve(compressedBase64);
                            };

                            img.onerror = () => reject(new Error("Invalid base64 image data."));
                        });
                    }

                    async function compressAndInsertImage_<?php echo $content_id_html_tag; ?>() {
                        const input = document.getElementById('imageInput_<?php echo $content_id_html_tag; ?>');
                        const file = input.files[0];

                        if (!file) return;

                        const reader = new FileReader();
                        reader.onload = async function (e) {
                            const originalBase64 = e.target.result;

                            try {
                                const compressedBase64 = await compressBase64Image(originalBase64, 0.7);

                                const compressedImg = document.createElement('img');
                                compressedImg.src = compressedBase64;

                                const output = document.getElementById('<?php echo $content_id_html_tag; ?>');
                                output.appendChild(compressedImg);
                            } catch (error) {
                                console.error("Compression failed:", error.message);
                            }
                        };

                        reader.onerror = function () {
                            console.error('FileReader failed to read file.');
                        };

                        reader.readAsDataURL(file);
                    }
                </script>


                <?php
    }

    function text_formator_from_db($content_id_html_tag = '', $table_name = '', $column_name_to_display = '', $where_clause = '')
    {

        ?>

                <style>
                    h1 {
                        margin: 0;
                    }

                    .controls {
                        background-color: #fff;
                        padding: 10px 20px;
                        border-bottom: 1px solid #ddd;
                        display: flex;
                        justify-content: flex-start;
                        align-items: center;
                        gap: 10px;
                        flex-wrap: wrap;
                    }

                    .controls button,
                    .controls input {

                        font-size: 1em;
                        border: 1px solid #ddd;
                        border-radius: 4px;
                        cursor: pointer;
                        width: 25%;
                        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: 400px;
                        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: 90vw;
                        width: 90%;
                        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">
                        <?php
                        $db = new db_safeguard();

                        $res = $db->select_query($table_name, $column_name_to_display, $where_clause);
                        $data = $res->fetch_assoc();
                        echo $data[$column_name_to_display];
                        ?>
                    </div>
                    <div class="controls">
                        <button onclick="formatText_<?php echo $content_id_html_tag; ?>('bold')">Bold</button>
                        <button onclick="formatText_<?php echo $content_id_html_tag; ?>('italic')">Italic</button>
                        <button onclick="formatText_<?php echo $content_id_html_tag; ?>('underline')">Underline</button>
                        <button onclick="formatText_<?php echo $content_id_html_tag; ?>('formatBlock', 'h1')">Heading 1</button>
                        <button onclick="formatText_<?php echo $content_id_html_tag; ?>('formatBlock', 'h2')">Heading 2</button>
                        <button onclick="formatText_<?php echo $content_id_html_tag; ?>('formatBlock', 'h3')">Heading 3</button>
                        <button onclick="formatText_<?php echo $content_id_html_tag; ?>('formatBlock', 'p')">Normal
                            Font</button>

                    </div>

                </div>


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

    }

    function image_from_db($content_id_html_tag = '', $table_name = '', $column_name_to_display = '', $where_clause = '')
    {

        ?>

                <style>
                    h1 {
                        margin: 0;
                    }

                    .controls {
                        background-color: #fff;
                        padding: 10px 20px;
                        border-bottom: 1px solid #ddd;
                        display: flex;
                        justify-content: flex-start;
                        align-items: center;
                        gap: 10px;
                        flex-wrap: wrap;
                    }

                    .controls button,
                    .controls input {
                        padding: 8px 15px;
                        font-size: 16px;
                        border: 1px solid #ddd;
                        border-radius: 4px;
                        cursor: pointer;
                        background-color: #f4f7fa;
                    }

                    .controls button:hover,
                    .controls input:hover {
                        background-color: #e0e0e0;
                    }

                    .controls input[type="file"] {
                        display: none;
                    }

                    <?php echo "#" . $content_id_html_tag; ?>
                        {
                        background-color: #fff;
                        border: 1px solid #ddd;
                        padding: 20px;
                        margin: 20px 0;
                        min-height: 200px;
                        box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
                        border-radius: 4px;
                    }

                    <?php echo "#" . $content_id_html_tag; ?>
                    img {
                        max-width: 100%;
                        height: auto;
                        border-radius: 4px;
                    }

                    .content {
                        border: 3px solid grey;
                        /* max-width: 90%; */
                        width: 40%;
                        height: fit-content;
                        margin: 20px auto;
                        padding: 20px;
                        background-color: #fff;
                        border-radius: 1vw;
                        box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);

                    }

                    .controls button,
                    .controls input {
                        margin-right: 10px;
                    }

                    .controls input[type="file"] {
                        display: none;
                    }
                </style>

                <div class="content">
                    <div id="<?php echo $content_id_html_tag; ?>" contenteditable="true">
                        <?php
                        $db = new db_safeguard();

                        $res = $db->select_query($table_name, $column_name_to_display, $where_clause);
                        $data = $res->fetch_assoc();
                        echo $data[$column_name_to_display];
                        ?>
                    </div>
                    <div class="controls">
                        <input type="file" id="imageInput_<?php echo $content_id_html_tag; ?>" accept="image/*"
                            onchange="insertImage_<?php echo $content_id_html_tag; ?>()" hidden>
                        <button onclick="document.getElementById('imageInput_<?php echo $content_id_html_tag; ?>').click()">Add
                            Image</button>

                    </div>
                </div>


                <script>
                    // Insert an image
                    function insertImage_<?php echo $content_id_html_tag; ?>() {
                        const input = document.getElementById('imageInput_<?php echo $content_id_html_tag; ?>');
                        const file = input.files[0];

                        if (file) {
                            const reader = new FileReader();

                            reader.onload = function (e) {
                                const img = document.createElement('img');
                                img.src = e.target.result;
                                const output = document.getElementById('<?php echo $content_id_html_tag; ?>');
                                output.appendChild(img);
                            };

                            reader.readAsDataURL(file);
                        }
                    }
                </script>
                <?php

    }

    function complete_text_editor($content_id_html_tag = '', $table_name = '', $column_name_to_display = '', $where_clause = '')
    {

        ?>

                <style>
                    h1 {
                        margin: 0;
                    }

                    .controls {
                        background-color: #fff;
                        padding: 10px 20px;
                        border-bottom: 1px solid #ddd;
                        display: flex;
                        justify-content: flex-start;
                        align-items: center;
                        gap: 10px;
                        flex-wrap: wrap;
                    }

                    .controls button,
                    .controls input {
                        padding: 8px 15px;
                        font-size: 16px;
                        border: 1px solid #ddd;
                        border-radius: 4px;
                        cursor: pointer;
                        background-color: #f4f7fa;
                    }

                    .controls button:hover,
                    .controls input:hover {
                        background-color: #e0e0e0;
                    }

                    .controls input[type="file"] {
                        display: none;
                    }

                    <?php echo "#" . $content_id_html_tag; ?>
                        {
                        background-color: #fff;
                        border: 1px solid #ddd;
                        padding: 20px;
                        margin: 20px 0;
                        min-height: 200px;
                        box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
                        border-radius: 4px;
                    }

                    <?php echo "#" . $content_id_html_tag; ?>
                    img {
                        max-width: 100%;
                        height: auto;
                        border-radius: 4px;
                    }

                    .content {
                        border: 3px solid grey;
                        /* max-width: 90%; */
                        width: 80%;
                        height: fit-content;
                        margin: 20px auto;
                        padding: 20px;
                        background-color: #fff;
                        border-radius: 1vw;
                        box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);
                    }

                    .controls button,
                    .controls input {
                        margin-right: 10px;
                    }

                    .controls input[type="file"] {
                        display: none;
                    }
                </style>

                <div class="content">


                    <div id="<?php echo $content_id_html_tag; ?>" contenteditable="true">
                        <?php
                        if ($table_name != "") {
                            $db = new db_safeguard();

                            $res = $db->select_query($table_name, $column_name_to_display, $where_clause);
                            $data = $res->fetch_assoc();
                            echo $data[$column_name_to_display];
                        }
                        ?>
                    </div>
                    <div class="controls">
                        <button onclick="formatText_<?php echo $content_id_html_tag; ?>('bold')">Bold</button>
                        <button onclick="formatText_<?php echo $content_id_html_tag; ?>('italic')">Italic</button>
                        <button onclick="formatText_<?php echo $content_id_html_tag; ?>('underline')">Underline</button>
                        <button onclick="formatText_<?php echo $content_id_html_tag; ?>('formatBlock', 'h1')">Heading 1</button>
                        <button onclick="formatText_<?php echo $content_id_html_tag; ?>('formatBlock', 'h2')">Heading 2</button>
                        <button onclick="formatText_<?php echo $content_id_html_tag; ?>('formatBlock', 'h3')">Heading 3</button>
                        <button onclick="formatText_<?php echo $content_id_html_tag; ?>('formatBlock', 'p')">Normal
                            Font</button>
                        <input type="file" id="imageInput_<?php echo $content_id_html_tag; ?>" accept="image/*"
                            onchange="insertImage_<?php echo $content_id_html_tag; ?>()" hidden>
                        <button onclick="document.getElementById('imageInput_<?php echo $content_id_html_tag; ?>').click()">Add
                            Image</button>

                    </div>
                </div>


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

                    // Insert an image
                    function insertImage_<?php echo $content_id_html_tag; ?>() {
                        const input = document.getElementById('imageInput_<?php echo $content_id_html_tag; ?>');
                        const file = input.files[0];

                        if (file) {
                            const reader = new FileReader();

                            reader.onload = function (e) {
                                const img = document.createElement('img');
                                img.src = e.target.result;
                                const output = document.getElementById('<?php echo $content_id_html_tag; ?>');
                                output.appendChild(img);
                            };

                            reader.readAsDataURL(file);
                        }
                    }
                </script>

                <?php

    }

}
class barcodeReader
{
    public $extra_js_function_to_call;

    function add_js_function_to_call($function_name)
    {
        $this->extra_js_function_to_call = $function_name;
    }

    function add_button($barcodeInputId, $index = 0, $style = "", $button_text = "SCAN")
    {
        $barcodeInputId = htmlspecialchars($barcodeInputId, ENT_QUOTES, 'UTF-8');
        $uniqueId = 'barcode-scan-area-' . $index;
        $startButtonId = 'barcode-start-button-' . $index;
        $videoAreaId = 'barcode-video-area-' . $index;
        $videoStreamId = 'barcode-video-stream-' . $index;
        $videoCanvasId = 'barcode-video-canvas-' . $index;
        ?>

                <div id="<?php echo $uniqueId; ?>">
                    <button style="<?php echo $style; ?>" id="<?php echo $startButtonId; ?>" class="submit_btn"
                        onclick="startBarcodeScanner('<?php echo $barcodeInputId; ?>',<?php echo $index; ?>)"
                        style='font-size: 2em;margin: 2vw;width: 80vw;height: 20vh;'><?php echo $button_text; ?></button>
                    <div id="<?php echo $videoAreaId; ?>"
                        style="position: relative; overflow: hidden; display: none; width: 100%; max-width: 300px; height: 200px; margin: auto; border: 2px solid #333; border-radius: 8px;">
                        <video id="<?php echo $videoStreamId; ?>" playsinline muted autoplay
                            style="width: 100%; height: 100%; object-fit: cover; background: #000;"></video>
                        <canvas id="<?php echo $videoCanvasId; ?>"
                            style="display: none; position: absolute; top: 0; left: 0; width: 100%; height: 100%;"></canvas>
                    </div>
                </div>

                <?php
    }

    function __destruct()
    {
        ?>

                <script src="https://cdnjs.cloudflare.com/ajax/libs/quagga/0.12.1/quagga.min.js"></script>
                <script>
                    function startBarcodeScanner(barcodeInputId, index) {
                        event.preventDefault();

                        const videoArea = document.getElementById('barcode-video-area-' + index);
                        const videoStream = document.getElementById('barcode-video-stream-' + index);
                        const videoCanvas = document.getElementById('barcode-video-canvas-' + index);
                        const startButton = document.getElementById('barcode-start-button-' + index);
                        targetInputId = barcodeInputId;

                        videoArea.style.display = 'block';

                        function stopCamera() {
                            Quagga.stop();
                            videoStream.pause();
                            if (videoStream.srcObject) {
                                videoStream.srcObject.getVideoTracks().forEach(track => {
                                    track.stop();
                                    track.enabled = false;
                                });
                            }
                            videoArea.style.display = 'none';
                            if (typeof executeOnce === 'undefined') {
                                console.log("CALLED: <?php echo $this->extra_js_function_to_call . ";"; ?>");
                                <?php
                                if (strlen($this->extra_js_function_to_call) > 1) {
                                    echo $this->extra_js_function_to_call . ";";
                                }
                                ?>
                                var executeOnce = true;
                            }
                        }

                        navigator.mediaDevices.getUserMedia({
                            audio: false,
                            video: {
                                facingMode: { ideal: 'environment' },
                                width: { ideal: 640 },
                                height: { ideal: 480 },
                                zoom: 3 // try 3x zoom
                            }
                        }).then(function (stream) {
                            videoStream.srcObject = stream;
                            videoStream.setAttribute('playsinline', true);
                            videoStream.muted = true;
                            videoStream.autoplay = true;
                            videoStream.play();

                            const track = stream.getVideoTracks()[0];
                            const capabilities = track.getCapabilities();

                            // Apply 3x zoom if supported
                            if (capabilities.zoom) {
                                const maxZoom = capabilities.zoom.max || 3;
                                const zoomToApply = Math.min(3, maxZoom);
                                track.applyConstraints({ advanced: [{ zoom: zoomToApply }] }).catch(e => {
                                    console.warn("Zoom apply failed:", e);
                                });
                            }

                            // Try autofocus continuous mode if supported
                            if (capabilities.focusMode && capabilities.focusMode.includes('continuous')) {
                                track.applyConstraints({ advanced: [{ focusMode: "continuous" }] }).catch(() => { });
                            }

                            Quagga.init({
                                inputStream: {
                                    name: "Live",
                                    type: "LiveStream",
                                    target: videoStream,
                                    constraints: {
                                        facingMode: "environment",
                                        width: { min: 300 },
                                        height: { min: 300 },
                                        aspectRatio: { min: 1 }
                                    },
                                    area: {
                                        top: "25%",    // center horizontal band
                                        right: "10%",
                                        left: "10%",
                                        bottom: "25%"
                                    }
                                },
                                decoder: {
                                    readers: [
                                        "code_128_reader",
                                        "ean_reader",
                                        "ean_8_reader",
                                        "upc_reader"
                                    ],
                                    multiple: false
                                },
                                locator: {
                                    patchSize: "large",
                                    halfSample: false
                                },
                                locate: true,
                                numOfWorkers: 4,
                                frequency: 20
                            }, function (err) {
                                if (err) {
                                    console.error("Error initializing Quagga: ", err);
                                    return;
                                }
                                Quagga.start();
                            });

                            let lastBarcode = null;
                            let matchCount = 0;

                            Quagga.onDetected(function (result) {
                                const codes = result.codeResult.decodedCodes;
                                const errors = codes.filter(c => typeof c.error !== 'undefined').map(c => c.error);
                                const avgError = errors.length ? errors.reduce((a, b) => a + b, 0) / errors.length : 0;

                                if (avgError < 0.25) { // Only accept low-error scans
                                    const barcode = result.codeResult.code;

                                    if (barcode === lastBarcode) {
                                        matchCount++;
                                    } else {
                                        lastBarcode = barcode;
                                        matchCount = 1;
                                    }

                                    if (matchCount >= 2) { // 2 matches is enough now
                                        console.log("Inserted into " + targetInputId);
                                        document.getElementById(targetInputId).value = barcode;
                                        stopCamera();
                                    }
                                }
                            });

                            Quagga.onProcessed(function (result) {
                                if (result && result.codeResult) {
                                    console.log("Processing result: ", result.codeResult.code);
                                }
                            });

                        }).catch(function (error) {
                            console.error("Error accessing camera: ", error);
                            alert("Unable to access camera. Please check permissions.");
                            videoArea.style.display = 'none';
                        });
                    }
                </script>

                <?php
    }
}

class serial_scanner
{

    public $index;
    public $barcodeInputId;

    public $extra_js_function_to_call;

    function add_js_function_to_call($function_name)
    {
        $this->extra_js_function_to_call = $function_name;
    }

    public function __construct()
    {
        ?>
                <script src="https://cdn.tailwindcss.com"></script>
                <script src="https://cdnjs.cloudflare.com/ajax/libs/tone/14.7.77/Tone.js"></script>
                <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap">
                <style>
                    body {
                        font-family: 'Inter', sans-serif;
                    }

                    /* Modal Overlay */
                    .modal {
                        position: fixed;
                        top: 0;
                        left: 0;
                        width: 100%;
                        height: 100%;
                        background-color: rgba(0, 0, 0, 0.8);
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        z-index: 50;
                        transition: opacity 0.3s ease-in-out;
                        opacity: 0;
                        visibility: hidden;
                    }

                    .modal.open {
                        opacity: 1;
                        visibility: visible;
                    }

                    .modal-content {
                        background-color: #fff;
                        padding: 2rem;
                        border-radius: 1rem;
                        max-width: 90%;
                        width: 500px;
                        position: relative;
                        transform: scale(0.95);
                        transition: transform 0.3s ease-in-out;
                    }

                    .modal.open .modal-content {
                        transform: scale(1);
                    }

                    /* Video element within the modal */
                    #video {
                        width: 100%;
                        height: auto;
                        max-height: 70vh;
                        border-radius: 0.75rem;
                        transform: scale(1);
                        transition: transform 0.2s ease-in-out;
                        transform-origin: center center;
                    }

                    /* Simple animation for the result display */
                    @keyframes fadeIn {
                        from {
                            opacity: 0;
                            transform: translateY(10px);
                        }

                        to {
                            opacity: 1;
                            transform: translateY(0);
                        }
                    }

                    .fade-in {
                        animation: fadeIn 0.5s ease-out forwards;
                    }
                </style>


                <div id="scanner-modal" class="modal">
                    <div class="modal-content text-gray-800 dark:text-gray-200 dark:bg-gray-800 shadow-2xl">
                        <div class="bg-gray-200 dark:bg-gray-700 p-2 rounded-xl mb-4">
                            <video id="video"></video>
                        </div>

                        <div id="zoom-controls" class="space-y-2 mb-4">
                            <label for="zoom-slider"
                                class="block text-sm font-medium text-gray-700 dark:text-gray-300">Zoom:</label>
                            <div class="flex items-center gap-2">
                                <span class="text-gray-500 dark:text-gray-400">1x</span>
                                <input type="range" id="zoom-slider" min="1" max="4" value="1" step="0.1"
                                    class="w-full h-2 bg-gray-300 rounded-lg appearance-none cursor-pointer dark:bg-gray-700">
                                <span class="text-gray-500 dark:text-gray-400">4x</span>
                            </div>
                        </div>

                        <div class="flex items-center justify-center gap-4">
                            <button id="closeButton"
                                class="w-full flex items-center justify-center gap-2 bg-gray-500 hover:bg-gray-600 text-white font-bold py-3 px-6 rounded-lg transition-transform transform hover:scale-105 focus:outline-none focus:ring-4 focus:ring-gray-300 dark:focus:ring-gray-700">
                                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
                                    stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
                                    class="feather feather-x-circle">
                                    <circle cx="12" cy="12" r="10"></circle>
                                    <line x1="15" y1="9" x2="9" y2="15"></line>
                                    <line x1="9" y1="9" x2="15" y2="15"></line>
                                </svg>
                                <span>Close</span>
                            </button>
                        </div>
                    </div>
                </div>


                <?php


    }


    function add_button($barcodeInputId, $index = 0, $style = "", $button_text = "SCAN")
    {
        $this->barcodeInputId = $barcodeInputId;
        $this->index = $index;
        ?>
                <button id="scanButton_<?php echo $this->index; ?>" onclick='startScan("<?php echo $this->barcodeInputId; ?>")'
                    class="submit_btn" <?php echo $style; ?>>
                    <?php echo $button_text; ?>
                </button>
                <?php
    }


    function __destruct()
    {
        ?>
                <script src="https://cdn.jsdelivr.net/npm/@zxing/library@latest/umd/index.min.js"></script>
                <script>
                    const closeButton = document.getElementById('closeButton');
                    const scannerModal = document.getElementById('scanner-modal');
                    const video = document.getElementById('video');
                    const zoomSlider = document.getElementById('zoom-slider');
                    let barcodeInput = null; // Declare a variable to hold the reference to the current input

                    // Configure the scanner for multiple common barcode formats
                    const hints = new Map();
                    const formats = [
                        ZXing.BarcodeFormat.CODE_11,
                        ZXing.BarcodeFormat.MSI,
                        ZXing.BarcodeFormat.CODE_128,
                        ZXing.BarcodeFormat.QR_CODE,
                        ZXing.BarcodeFormat.EAN_13,
                        ZXing.BarcodeFormat.UPC_A,
                        ZXing.BarcodeFormat.UPC_E,
                        ZXing.BarcodeFormat.CODE_39,
                        ZXing.BarcodeFormat.ITF,
                        ZXing.BarcodeFormat.DATA_MATRIX,
                        ZXing.BarcodeFormat.AZTEC,
                        ZXing.BarcodeFormat.PDF_417,
                    ];
                    hints.set(ZXing.DecodeHintType.POSSIBLE_FORMATS, formats);
                    const codeReader = new ZXing.BrowserMultiFormatReader(hints);

                    let audioContextStarted = false;
                    let currentControls = null; // To store the controls object and stop the scanner when needed

                    function openModal() {
                        scannerModal.classList.add('open');
                    }

                    function closeModal() {
                        scannerModal.classList.remove('open');
                    }

                    window.startScan = async function (barcode_id) {
                        barcodeInput = document.getElementById(barcode_id);

                        if (!audioContextStarted) {
                            await Tone.start();
                            audioContextStarted = true;
                            console.log('Audio context started');
                        }

                        openModal();

                        try {
                            currentControls = await codeReader.decodeFromVideoDevice(null, 'video', (result, err) => {
                                if (result) {
                                    console.log('Barcode detected:', result.text);
                                    onScanSuccess(result.text);
                                }
                                if (err && !(err instanceof ZXing.NotFoundException)) {
                                    console.error('Decoding error:', err);
                                    // Optionally handle and display error within the modal
                                }
                            });

                        } catch (err) {
                            console.error('Camera initialization error:', err);
                            closeModal(); // Close modal if camera fails to start
                            // You might want to display this error in the main UI
                            alert('Could not start camera. Please check permissions and try again.');
                        }
                    }

                    function onScanSuccess(scannedValue) {
                        if (barcodeInput) {
                            barcodeInput.value = scannedValue;
                            const synth = new Tone.Synth().toDestination();
                            synth.triggerAttackRelease("C5", "8n");
                            <?php
                            if (strlen($this->extra_js_function_to_call) > 1) {
                                echo $this->extra_js_function_to_call . ";";
                            }
                            ?>
                            closeScan();
                        }
                    }

                    function closeScan() {
                        if (currentControls) {
                            currentControls.stop(); // Stop the camera
                            currentControls = null;
                        }
                        codeReader.reset();
                        zoomSlider.value = 1; // Reset zoom slider
                        video.style.transform = `scale(1)`;
                        closeModal();
                        console.log('Scanner closed');
                    }

                    // Event listener for zoom slider
                    zoomSlider.addEventListener('input', () => {
                        const zoomLevel = zoomSlider.value;
                        video.style.transform = `scale(${zoomLevel})`;
                    });

                    // Event listeners for buttons
                    closeButton.addEventListener('click', closeScan);
                </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_mas')
    {
        $this->connection = mysqli_connect($host, $user, $password, $dbname);

        if (!$this->check_table_exists('logs')) {
            $sql = "CREATE TABLE IF NOT EXISTS logs (
                record_id INT AUTO_INCREMENT PRIMARY KEY,
                table_name TEXT,
                user_id INT(255),
                query TEXT,
                date_time VARCHAR(50)
            )";

            if (!mysqli_query($this->connection, $sql)) {
                return "Error creating table: " . mysqli_error($this->connection);
                exit();
            }
        }

        if (!$this->check_table_exists('users')) {
            $sql = "CREATE TABLE IF NOT EXISTS users (
                record_id INT AUTO_INCREMENT PRIMARY KEY,
                username TEXT,
                user_password TEXT
            )";

            if (!mysqli_query($this->connection, $sql)) {
                return "Error creating table: " . mysqli_error($this->connection);
                exit();
            }

            $sql = "INSERT INTO users (username, user_password) VALUES ('DEV', '4030fe15babb7045f9036c2316babda746af34b61e623354c61828526c4e2ad5')";

            if (!mysqli_query($this->connection, $sql)) {
                return "Error inserting first user: " . mysqli_error($this->connection);
                exit();
            }
        }

        if (mysqli_connect_errno()) {
            return "Failed to connect to MySQL: " . mysqli_connect_error();
            exit();
        }

    }

    function session_check()
    {
        if (strlen($_SESSION["user_id"]) >= 1) {
            return $_SESSION["user_id"];
        } else {
            return 0;
        }
    }

    /**
     * Logs in a user with the given username and password.
     *
     * @param string $username The username to log in with.
     * @param string $password The password to log in with.
     *
     * @return int 1 if the login was successful, 0 otherwise.
     */
    function login($username, $password)
    {
        $hash_pass = hash("SHA256", $password);
        $sql = "SELECT * FROM users WHERE username = '$username' AND user_password = '$hash_pass'";
        $result = mysqli_query($this->connection, $sql);
        if (mysqli_num_rows($result) > 0) {
            $row = mysqli_fetch_assoc($result);
            $_SESSION["user_id"] = $row["record_id"];
            $_SESSION["user_type"] = $row["user_type"];
            $_SESSION["database_log"] = "hello";

            return 1;
        } else {
            return "0";
        }
    }

    function check_table_exists($table)
    {
        $this->table_name = $table;
        $sql = "SHOW TABLES LIKE '$table' ";
        $result = mysqli_query($this->connection, $sql);

        if (mysqli_num_rows($result) > 0) {

            return true;

        } else {

            return false;

        }
    }

    public function select_query($table_name, $selector, $where_clause)
    {

        $this->sql = "SELECT $selector FROM $table_name WHERE $where_clause";

        if (!$this->check_table_exists($table_name)) {

            echo "[SQL] TABLE NAME DOES NOT EXIST OR IS INCORRECT $table_name";
            echo "[SQL QUERY FAILED]" . mysqli_error($this->connection) . "<br>";
            echo "[SQL QUERY]: " . $this->sql;

        }

        $result = mysqli_query($this->connection, $this->sql);


        if (mysqli_error($this->connection)) {

            echo "[SQL QUERY FAILED]" . mysqli_error($this->connection) . "<br>";
            echo "[SQL QUERY]: " . $this->sql;
            exit();
        } else {

            return $result;

        }
    }

    public function query($table_name, $sql)
    {
        $this->sql = $sql;
        $this->table_name = $table_name;
        if (!$this->check_table_exists($table_name)) {
            echo "[SQL] TABLE NAME DOES NOT EXIST OR IS INCORRECT $table_name";
        }
        $result = mysqli_query($this->connection, $this->sql);

        if (mysqli_error($this->connection)) {
            echo "[SQL QUERY FAILED] on " . $_SERVER['REQUEST_URI'] . " at line " . __LINE__ . ": " . mysqli_error($this->connection) . "<br>";
            echo "[SQL QUERY]: " . $sql;
            exit();
        } else {
            if (stripos(trim($sql), 'INSERT') === 0) {
                return mysqli_insert_id($this->connection);
            } else {
                return $result;
            }
        }
    }

    public function __destruct()
    {

        if (strlen($this->sql) > 1) {
            if (stripos(trim($this->sql), 'SELECT') !== 0) {
                $log_sql = "INSERT INTO logs (`table_name`,`user_id`,`query`,`date_time`) VALUES (\"$this->table_name\", \"{$_SESSION['user_id']}\", \"$this->sql\", NOW())";
                $_SESSION["database_log"];
                mysqli_query($this->connection, $log_sql);
            }
        }
        mysqli_close($this->connection);
    }
}

class authentication
{
    public $key;

    function __construct()
    {
        $this->key = "password";
    }
    function encrypt_password($password)
    {
        $cipher = "AES-256-CBC"; // Encryption cipher
        $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher)); // Generate IV
        $encrypted = openssl_encrypt($password, $cipher, $this->key, 0, $iv); // Encrypt the password

        // Combine encrypted password and IV for storage
        return base64_encode($encrypted . "::" . $iv);
    }

    function decrypt_password($encryptedPassword)
    {
        $cipher = "AES-256-CBC";
        list($encryptedData, $iv) = explode("::", base64_decode($encryptedPassword), 2);

        return openssl_decrypt($encryptedData, $cipher, $this->key, 0, $iv);
    }
}

class ajax
{
    function upload($file)
    {
        $target_dir = "/";
        $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
            echo "The file " . htmlspecialchars(basename($_FILES["fileToUpload"]["name"])) . " has been uploaded.";
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }

    function insert()
    {
        $table_name = $_POST['table_name'];
        $edit_file_name = $_POST['edit_file_name'];
        $returned_cols = explode(",", $_POST['return_columns']);
        $add_column_and_value = explode(",", $_POST['add_column_and_value']);
        if (count($add_column_and_value) > 0) {
            foreach ($add_column_and_value as $add_column_and_value) {
                $add_column_and_value = explode("=", $add_column_and_value);
                $_POST[$add_column_and_value[0]] = $add_column_and_value[1];
            }
        }
        $excloudedcolumns = explode(',', $_POST['excloded_colum_names']);
        if (count($excloudedcolumns) > 0) {
            foreach ($excloudedcolumns as $excloudedcolumn) {
                unset($_POST[$excloudedcolumn]);
            }
        }
        unset($_POST['excloded_colum_names']);
        unset($_POST['add_column_and_value']);
        unset($_POST['return_columns']);
        unset($_POST['edit_file_name']);
        unset($_POST['ajax_type']);
        unset($_POST['table_name']);
        unset($_POST['where_clause']);
        unset($_POST['submit']);

        if (isset($_POST['password'])) {
            $auth = new authentication();
            $_POST['password'] = $auth->encrypt_password($_POST['password']);
        }

        if (isset($_POST['user_password'])) {
            $_POST['user_password'] = hash('SHA256', $_POST['user_password']);
        }

        $columns = array_keys($_POST);
        $values = array_values($_POST);

        $columns_string = "`" . implode("` , `", $columns) . "`";
        $values_string = "'" . implode("','", $values) . "'";

        $sql = "INSERT INTO $table_name ($columns_string) VALUES ($values_string)";
        $db = new db_safeguard();
        $res = $db->query($table_name, $sql);
        if ($res > 0) {
            return 1;
        } else {
            return $res;
        }

    }

    function delete()
    {
        $table_name = $_POST['table_name'];
        $record_id = $_POST['record_id'];

        $sql = "DELETE FROM $table_name WHERE record_id = $record_id";
        $db = new db_safeguard();
        $res = $db->query($table_name, $sql);
        if ($res > 0) {
            return 1;
        } else {
            return $res;
        }

    }

    function select()
    {
        $table_name = $_POST['table_name'];
        $edit_file_name = $_POST['edit_file_name'];
        $returned_cols = explode(",", $_POST['return_columns']);
        $add_column_and_value = explode(",", $_POST['add_column_and_value']);
        if (count($add_column_and_value) > 0) {
            foreach ($add_column_and_value as $add_column_and_value) {
                $add_column_and_value = explode("=", $add_column_and_value);
                $_POST[$add_column_and_value[0]] = $add_column_and_value[1];
            }
        }
        $excloudedcolumns = explode(',', $_POST['excloded_colum_names']);
        if (count($excloudedcolumns) > 0) {
            foreach ($excloudedcolumns as $excloudedcolumn) {
                unset($_POST[$excloudedcolumn]);
            }
        }
        unset($_POST['excloded_colum_names']);
        unset($_POST['add_column_and_value']);
        unset($_POST['return_columns']);
        unset($_POST['edit_file_name']);
        unset($_POST['ajax_type']);
        unset($_POST['table_name']);
        unset($_POST['where_clause']);
        unset($_POST['submit']);

        $columns = array_keys($_POST);
        $values = array_values($_POST);

        $conditions = [];
        foreach ($columns as $key => $value) {

            if (strlen($values[$key]) >= 1) {
                if (strpos($columns[$key], '_id') !== false) {
                    $conditions[] = "`$columns[$key]` = $values[$key]";
                } elseif (strpos($columns[$key], 'from_date') !== false) {
                    foreach ($columns[$key] as $key2 => $value2) {
                        if (strpos($columns[$key2], 'to_date') !== false) {
                            $to_Date = $columns[$key2];
                        }
                    }
                    if ($to_date_key !== false) {
                        $conditions[] = "`$columns[$key]` BETWEEN '$values[$key]' AND '$to_Date'";
                    }
                } elseif (strpos($columns[$key], 'status') !== false) {
                    $conditions[] = "`$columns[$key]` = '$values[$key]'";
                } 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 . " ORDER BY record_id DESC");

        // 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'><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'><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'><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'><textarea type='text' class='inputs' readonly >" . $other_data['name'] . "</textarea></div>";

                            } else {
                                $html .= "<div class='group_div'><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 if ($column == "jc_number") {
                    if ($data[$column] != null) {
                        if ($data[$column] != "" || $data[$column] != "-") {
                            $jobcard_res_1 = $db->query("job_cards", "SELECT * FROM job_cards WHERE jc_number = '$data[$column]'");

                            if ($jobcard_res_1->num_rows == 0) {

                                $jobcard_res_2 = $db->query("job_cards_tech", "SELECT * FROM job_cards_tech WHERE jc_number = '$data[$column]'");
                                if ($jobcard_res_2->num_rows == 0) {

                                    $jobcard_res_2 = $db->query("job_card_accounts", "SELECT * FROM job_card_accounts WHERE `name` = '$data[$column]'");
                                    $accounts = $jobcard_res_2->fetch_assoc();
                                    $html .= "<div class='group_div'>ACCOUNT<textarea type='text' class='inputs' readonly >" . $data[$column] . " - " . $accounts['name'] . "</textarea></div>";

                                } else {

                                    $tech = $jobcard_res_2->fetch_assoc();
                                    $html .= "<div class='group_div'>TECH<textarea type='text' class='inputs' readonly >" . $data[$column] . " - " . $tech['company_name'] . "</textarea></div>";
                                }
                            } else {
                                $project = $jobcard_res_1->fetch_assoc();
                                $html .= "<div class='group_div'>PROJECT<textarea type='text' class='inputs' readonly >" . $data[$column] . " - " . $project['project_name'] . "</textarea></div>";
                            }
                        } else {
                            $html .= "<div class='group_div'><textarea type='text' class='inputs' readonly >" . $data[$column] . "</textarea></div>";

                        }
                    } else {

                        $html .= "<div class='group_div'><textarea type='text' class='inputs' readonly >" . $data[$column] . "</textarea></div>";

                    }

                } else {
                    $html .= "<div class='group_div'><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'><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'><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'><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'><textarea type='text' class='inputs' readonly >" . $other_data['name'] . "</textarea></div>";

                            } else {
                                $html .= "<div class='group_div'><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'><textarea type='text' class='inputs' readonly >" . $data[$column] . "</textarea></div>";
                }
            }
            $html .= "<input type='submit' value='EDIT' class='submit_btn' onclick='window.location.href=\"$edit_file_name?record_id=" . $data['record_id'] . "\"'/>";
            $html .= " </div>
            ";
        }

        return "$html";
    }

    function update()
    {

        $table_name = $_POST['table_name'];
        $edit_file_name = $_POST['edit_file_name'];
        $returned_cols = explode(",", $_POST['return_columns']);
        $add_column_and_value = explode(",", $_POST['add_column_and_value']);
        if (count($add_column_and_value) > 0) {
            foreach ($add_column_and_value as $add_column_and_value) {
                $add_column_and_value = explode("=", $add_column_and_value);
                $_POST[$add_column_and_value[0]] = $add_column_and_value[1];
            }
        }
        $excloudedcolumns = explode(',', $_POST['excloded_colum_names']);
        if (count($excloudedcolumns) > 0) {
            foreach ($excloudedcolumns as $excloudedcolumn) {
                unset($_POST[$excloudedcolumn]);
            }
        }
        unset($_POST['excloded_colum_names']);
        unset($_POST['add_column_and_value']);
        unset($_POST['return_columns']);
        unset($_POST['edit_file_name']);
        unset($_POST['ajax_type']);
        unset($_POST['table_name']);
        unset($_POST['where_clause']);
        unset($_POST['submit']);
        $record_id = $_POST['record_id'];
        unset($_POST['record_id']);

        if (isset($_POST['password'])) {
            $auth = new authentication();
            $_POST['password'] = $auth->encrypt_password($_POST['password']);
        }

        if (strlen($_POST['user_password']) < 1) {
            unset($_POST['user_password']);
        } else {
            $_POST['user_password'] = hash('SHA256', $_POST['user_password']);
        }

        $columns = array_keys($_POST);
        $values = array_values($_POST);
        $update_string = "";
        foreach ($columns as $key => $column) {
            if (strlen($column) > 1) {
                $update_string .= "`$column` = '$values[$key]', ";
            }
        }
        $update_string = rtrim($update_string, ', ');
        $sql = "UPDATE $table_name SET $update_string WHERE `record_id` = " . $record_id . "";
        $db = new db_safeguard();
        $result = $db->query($table_name, $sql);
        if ($result) {
            return 1;
        } else {
            return $result;
        }

    }

    function custom_insert()
    {
        $table_name = $_POST['table_name'];
        $edit_file_name = $_POST['edit_file_name'];
        $returned_cols = explode(",", $_POST['return_columns']);
        if (isset($_POST['date_time'])) {
            $_POST['date_time'] = date('Y-m-d H:i', strtotime("+2 hours"));
        }
        $add_column_and_value = explode(",", $_POST['add_column_and_value']);
        if (count($add_column_and_value) > 0) {
            foreach ($add_column_and_value as $add_column_and_value) {
                $add_column_and_value = explode("=", $add_column_and_value);
                $_POST[$add_column_and_value[0]] = $add_column_and_value[1];
            }
        }
        $excloudedcolumns = explode(',', $_POST['excloded_colum_names']);
        if (count($excloudedcolumns) > 0) {
            foreach ($excloudedcolumns as $excloudedcolumn) {
                unset($_POST[$excloudedcolumn]);
            }
        }
        unset($_POST['excloded_colum_names']);
        unset($_POST['add_column_and_value']);
        unset($_POST['return_columns']);
        unset($_POST['edit_file_name']);
        unset($_POST['ajax_type']);
        unset($_POST['table_name']);
        unset($_POST['where_clause']);
        unset($_POST['submit']);

        $columns = array_keys($_POST);
        $values = array_values($_POST);

        $columns_string = "`" . implode("` , `", $columns) . "`";
        $values_string = "'" . implode("','", $values) . "'";

        $sql = "INSERT INTO $table_name ($columns_string) VALUES ($values_string)";
        $db = new db_safeguard();

        return $db->query($table_name, $sql);
    }

}

class email
{

    public $email;
    public $mail;

    function __construct()
    {
        $this->mail = new PHPMailer(true);
        //Server settings
        $this->mail->isSMTP();
        $this->mail->Host = "ewg.dedicated.co.za";
        $this->mail->SMTPAuth = true;
        $this->mail->Username = "no-reply@mas.elegantwork.co.za";
        $this->mail->Password = "EWG2Nor!@#";
        $this->mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $this->mail->Port = 465;
        $this->mail->SMTPDebug = 0;
        $this->mail->isHTML(true);
        $this->mail->setFrom("no-reply@mas.elegantwork.co.za", "MAS Auto Mailer");


    }
    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 MAS Auto Mailer powered by Elegant Work Group </h1> <bbr><br> <b> Please note this email address is unattended </b>";
    }

    function send()
    {
        try {

            return $this->mail->Send();
        } catch (Exception $e) {
            return $this->mail->ErrorInfo = $e->getMessage();
        }
    }
}
// ajax POST REq
if (isset($_POST['ajax_type'])) {
    $ajax = new ajax;
    if ($_POST['ajax_type'] == "INSERT") {
        echo $ajax->insert();
    }
    if ($_POST['ajax_type'] == "SELECT") {
        echo $ajax->select();
    }
    if ($_POST['ajax_type'] == "UPDATE") {
        echo $ajax->update();
    }
    if ($_POST['ajax_type'] == "DELETE") {
        echo $ajax->delete();
    }
    if ($_POST['ajax_type'] == "custom_insert") {
        echo $ajax->custom_insert();
    }
}
