<?php

class calendar
{
    function generateCalendar($monthOffset, $admin = false, $displayWeekends = true)
    {
        $dateStart = date('Y-m-d H:i', strtotime('-31 days'));
        $dateEnd = date('Y-m-d H:i', strtotime('+3 months'));
        $publicHolidays2025 = [
            "2025-01-01" => "New Year’s Day",
            "2025-03-21" => "Human Rights Day",
            "2025-04-18" => "Good Friday",
            "2025-04-21" => "Family Day",
            "2025-04-27" => "Freedom Day",
            "2025-04-28" => "Public holiday (Freedom Day observed)",
            "2025-05-01" => "Workers' Day",
            "2025-06-16" => "Youth Day",
            "2025-08-09" => "National Women’s Day",
            "2025-09-24" => "Heritage Day",
            "2025-12-16" => "Day of Reconciliation",
            "2025-12-25" => "Christmas Day",
            "2025-12-26" => "Day of Goodwill"
        ];

        $db = new db_safeguard();
        $durationTasks = [];
        $tasks = []; // Initialize early so it's available for all sections

        $user_data = $admin ? "" : " AND `user_id_assigned` = {$_SESSION['user_id']}";

        // Work Orders (Duration Tasks)
        $work_order_res = $db->query("work_orders", "SELECT * FROM `work_orders` WHERE `completed` = 0 AND `sent_for_review` = 0 AND `in_review` = 0 $user_data");

        if ($work_order_res->num_rows > 0) {
            while ($work_order = $work_order_res->fetch_assoc()) {
                $start_date = substr($work_order['action_date_time'], 0, 10);
                $end_date = substr($work_order['deadline_date_time'], 0, 10);
                $project_details = $db->query("projects", "SELECT * FROM projects WHERE record_id = {$work_order['project_id']}");
                $project_name = $project_details->fetch_assoc()['name'];
                $completed = $work_order['completed'];
                $class = ($end_date < date('Y-m-d H:i') && $completed != 1) ? "task task-overdue" : "task task-duration";
                $overdue = ($end_date < date('Y-m-d H:i') && $completed != 1) ? "(OVERDUE)" : "";

                if ($completed == 1) {
                    $class = "duration_task task-complete";

                }

                $durationTasks[] = [
                    'start' => "$start_date",
                    'end' => "$end_date",
                    'name' => htmlspecialchars(" {$work_order['name']} On Projcet: $project_name $overdue "),
                    'description' => "",
                    'link' => htmlspecialchars("/app/work_orders/work_order.php?record_id={$work_order['record_id']}"),
                    'class' => "$class",
                    "project" => "🗂️ " . "$project_name",
                    "public_holiday" => $work_order['public_holiday'] ?? '0'
                ];
            }
        }

        // Meetings
        $meetings_res = $db->query("meetings", "SELECT * FROM `meetings` WHERE date_time BETWEEN '$dateStart' AND '$dateEnd' AND (user_ids LIKE '%,{$_SESSION['user_id']},%' OR user_id = '{$_SESSION['user_id']}')");
        if ($meetings_res->num_rows > 0) {
            while ($meeting = $meetings_res->fetch_assoc()) {
                $date = substr($meeting['date_time'], 0, 10);
                $time = str_replace("T", "", substr($meeting['date_time'], 11));
                $user_res = $db->query("users", "SELECT * FROM users WHERE record_id = {$meeting['user_id']}");
                $username = $user_res->fetch_assoc()['username'];
                $class = ("$date $time" < date('Y-m-d H:i')) ? "daily_task task-overdue " : "daily_task task-meeting ";
                $overdue = ("$date $time" < date('Y-m-d H:i') && $meeting['status'] != 1) ? "(OVERDUE)" : "";
                $username = ($meeting['client_id'] > 0) ? $db->query("clients", "SELECT * FROM clients WHERE record_id = {$meeting['client_id']}")->fetch_assoc()['name'] : $username;
                if ($meeting['status'] == 1) {
                    $class = "daily_task task-complete";
                }
                if (strlen($meeting['client_visit']) > 1) {
                    $client_visit = " WITH {$meeting['client_visit']} ";
                } else {
                    $client_visit = " WITH $username ";
                }

                $tasks["$date"][] = [
                    'time' => "$time",
                    'icon' => "👥 <br> $username ({$meeting['duration']}) ",
                    'description' => "MEETING $client_visit FOR {$meeting['duration']} AT {$meeting['location']} $overdue",
                    'link' => "/app/meetings/meeting.php?record_id={$meeting['record_id']}",
                    'class' => "$class",
                    "user" => "$username",
                    "completed" => $meeting['status'],
                    "public_holiday" => $meeting['public_holiday'] ?? '0',
                    "meeting" => 1
                ];
            }
        }

        // Service Tickets
        $service_tickets_res = $db->query("service_tickets", "SELECT * FROM service_tickets WHERE action_date BETWEEN '$dateStart' AND '$dateEnd' $user_data");

        if ($service_tickets_res->num_rows > 0) {
            while ($service_ticket = $service_tickets_res->fetch_assoc()) {
                $date = substr($service_ticket['action_date'], 0, 10);
                $time = str_replace("T", "", substr($service_ticket['action_date'], 11));
                $client_res = $db->query("clients", "SELECT * FROM clients WHERE record_id = {$service_ticket['client_id']}");
                $client_name = $client_res->fetch_assoc()['name'];
                $class = ("$date $time" < date('Y-m-d H:i') && $service_ticket['completed'] != "COMPLETED") ? "daily_task task-overdue " : "daily_task task-time ";
                $overdue = ("$date $time" < date('Y-m-d H:i') && $service_ticket['completed'] != "COMPLETED") ? " OVERDUE" : "";
                if ($service_ticket['completed'] == "COMPLETED") {
                    $class = "task-complete";
                }

                if ($service_ticket['completed'] == "COMPLETED") {
                    $completed = 1;
                } else {
                    $completed = 0;
                }

                $tasks["$date"][] = [
                    'time' => "$time ",
                    'icon' => "📝 <br> $client_name",
                    'description' => "{$service_ticket['name']} FOR $client_name  $overdue",
                    'link' => "/app/service_tickets/complete_service_tickets.php?record_id={$service_ticket['record_id']}",
                    'class' => "$class",
                    "completed" => $completed,
                    "public_holiday" => $service_ticket['public_holiday'] ?? '0',
                    "service_ticket" => 1
                ];
            }
        }
        // var_dump($tasks);
        ?>

                <script>
                    function showPopup(event, name, description, link) {
                        var popup = document.getElementById('popup');
                        document.getElementById('popup-title').innerText = name;
                        document.getElementById('popup-description').innerText = description;
                        document.getElementById('popup-link').href = link;

                        popup.style.display = 'block';
                        popup.style.left = event.pageX + 'px';
                        popup.style.top = event.pageY + 'px';
                    }

                    function closePopup() {
                        document.getElementById('popup').style.display = 'none';
                    }
                </script>

                <div id="popup" class="popup">
                    <h3 id="popup-title"></h3>
                    <p id="popup-description"></p>
                    <a id="popup-link" href="#"><button class="submit_btn">Go To</button></a>
                    <button onclick="closePopup()" class="submit_btn">Close</button>
                </div>

                <?php
                $year = date('Y');
                $month = date('n') + $monthOffset;

                if ($month > 12) {
                    $month -= 12;
                    $year++;
                }

                $firstDayOfMonth = strtotime("$year-$month-01");
                $daysInMonth = date('t', $firstDayOfMonth);
                $monthName = date('F', $firstDayOfMonth);
                $startDay = date('N', $firstDayOfMonth); // 1 (for Monday) through 7 (for Sunday)
                $currentDateTime = date('Y-m-d H:i');

                echo "<div class='calendar'>";
                echo "<h2>$monthName $year</h2>";
                echo "<table><tr>";

                $daysOfWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'];
                if ($displayWeekends) {
                    $daysOfWeek = array_merge($daysOfWeek, ['Sat', 'Sun']);
                }

                foreach ($daysOfWeek as $dayOfWeek) {
                    echo "<th>$dayOfWeek</th>";
                }
                echo "</tr><tr>";

                $dayCounter = 1;
                for ($i = 1; $i < $startDay; $i++) {
                    if ($displayWeekends || ($i < 6)) {
                        echo "<td></td>";
                        $dayCounter++;
                    }
                }

                for ($day = 1; $day <= $daysInMonth; $day++) {
                    $dateKey = sprintf("%04d-%02d-%02d", $year, $month, $day);
                    $dayOfWeekNumber = date('N', strtotime($dateKey));

                    if ($displayWeekends || ($dayOfWeekNumber < 6)) {
                        $isHoliday = array_key_exists($dateKey, $publicHolidays2025);
                        $class = ($dateKey < substr($currentDateTime, 0, 10)) ? 'past-day' : (($dateKey == substr($currentDateTime, 0, 10)) ? 'current-day' : '');

                        echo "<td class='$class'><div class='day'>$day</div>";

                        if ($isHoliday) {
                            echo "<div class='holiday-label'>{$publicHolidays2025[$dateKey]}</div>";
                        }

                        foreach ($durationTasks as $task) {
                            if ($dateKey >= $task['start'] && $dateKey <= $task['end'] && date('N', strtotime($dateKey)) < 6) {
                                if ($isHoliday && $task['public_holiday'] != '1')
                                    continue;
                                $userDisplay = $admin ? "<span style='font-size:1em;'><u>" . $task['user'] . "</u></span> <br><br>" : "";
                                echo "
                        <div class=' task {$task['class']}' style='background-color: {$task['color']};color: {$task['font_color']};' onclick=\"showPopup(event, ' {$task['name']}', '{$task['description']}', '{$task['link']}')\">
                            <div> 
                                {$task['project']}  
                            </div> 
                        </div>";
                            }
                        }

                        if (isset($tasks[$dateKey])) {
                            usort($tasks[$dateKey], fn($a, $b) => strtotime($a['time']) - strtotime($b['time']));

                            foreach ($tasks[$dateKey] as $task) {
                                if ($isHoliday && $task['public_holiday'] != '1')
                                    continue;
                                $hidden_completed = ($task['completed'] == 1) ? "display: none" : "";
                                $completed_width_change = ($task['completed'] == 1) ? "width: 70%; padding: 0vh; padding-left: 0.75vh; margin-left: 35%;" : "";
                                if ($task['meeting'] == 1) {
                                    $completed_icon = ($task['completed'] == 1) ? "👥 ✅" : "";

                                }
                                if ($task['service_ticket'] == 1) {
                                    $completed_icon = ($task['completed'] == 1) ? "📝 ✅" : "";

                                }

                                echo "
                        <div class=' task {$task['class']}' style='$completed_width_change' 
                        
                        onclick=\"showPopup(event, '{$task['description']}', '{$task['description']}', '{$task['link']}')\">
                          <div class='task_inter_data_div'>
                           
                                <div class='time_section'> 
                                    {$task['time']} 
                                </div>
                                $completed_icon
                                <div class='data_section' style='$hidden_completed'> 
                                    {$task['icon']} 
                                </div>
                            </div>
                        </div>
                        ";
                            }
                        }

                        echo "</td>";
                        $dayCounter++;
                        if (($dayCounter - 1) % ($displayWeekends ? 7 : 5) == 0)
                            echo "</tr><tr>";
                    }
                }

                while (($dayCounter - 1) % ($displayWeekends ? 7 : 5) != 0 && ($displayWeekends || (($dayCounter - 1) % 7 < 5))) {
                    echo "<td></td>";
                    $dayCounter++;
                }

                echo "</tr></table></div>";

                ?>
                <style>
                    @media all and (max-width: 650px) {
                        .task-time {
                            background-color: #DCEFFF;
                            color: #003366;
                        }

                        .task-duration {
                            background-color: #b4995e;
                            color: #42371b;
                        }

                        .task-meeting {
                            background-color: #EAF8E6;
                            color: #1F5D30;
                        }

                        .task-leave {
                            background-color: #FDECEC;
                            color: #991F1F;
                        }

                        .task-complete {
                            background-color: #E6F4EA;
                            color: #2D5F3B;
                            border-bottom-left-radius: 5px;
                        }

                        .task-overdue {
                            background-color: #ffcccc;
                            color: #B30000;
                            /* border: 1px dashed #B30000; */
                        }

                        .time_section {
                            width: 20%;
                            padding-right: 3.15vw;
                            margin: 4px;
                            padding-left: 0.85vw;
                            display: flex;
                            flex-direction: row;
                            align-content: center;
                            justify-content: center;
                            align-items: center;
                            border-right: 1px solid black;
                        }

                        .data_section {
                            display: flex;
                            width: 80%;
                            padding-left: 10px;
                            flex-direction: row;
                            flex-wrap: wrap;
                            align-content: center;
                            justify-content: flex-start;
                            align-items: center;
                        }

                        .task_inter_data_div {
                            display: flex;
                            flex-direction: row;
                            align-content: center;
                            align-items: center;
                        }

                        .calendar {
                            border: 1px solid #ccc;
                            background-color: #ffffff;
                            padding: 3vw;
                            border-radius: 24px;
                            box-shadow: -2px 3px 20px 0px rgba(0, 0, 0, 255);
                            text-align: center;
                            width: 90%;
                            overflow: auto;
                        }

                        table {
                            width: 100%;
                            border-collapse: collapse;
                            font-size: 1em;
                        }

                        th,
                        td {
                            width:
                                <?php echo $displayWeekends ? '14%' : '20%'; ?>
                            ;
                            min-height: 100px;
                            overflow: hidden;
                            text-align: center;
                            border: 1px solid #494949;
                            vertical-align: top;
                        }

                        th {
                            background-color: #f3f3f3;
                        }

                        .day {
                            font-weight: bold;
                        }

                        .task {
                            padding: 2px;
                            /* border: 3px solid black; */
                            margin-top: 5px;
                            display: flex;
                            /* border-radius: 5px; */
                            font-size: 0.65em;
                            margin-top: 0.8vh;
                            cursor: pointer;
                            box-shadow: 3px 2px 5px 0px rgba(0, 0, 0, 0.2);
                            flex-direction: row;
                            width: 79%;
                            margin-left: auto;
                            margin-right: auto;
                            overflow: hidden;
                            flex-wrap: wrap;
                            align-content: center;
                        }


                        .daily_task {
                            max-width: 80%;
                            padding: 8px;
                            /* border: 3px solid black; */
                            box-shadow: 3px 2px 5px 0px rgba(0, 0, 0, 0.2);
                            margin-top: 0.8vh;
                            font-size: 0.65em;
                            margin-left: -3%;
                            cursor: pointer;

                        }

                        .past-day {
                            background-color: #f0f0f0;
                            color: #aaa;
                        }

                        .current-day {
                            background-color: rgba(151, 229, 243, 0.3);
                            /* border-bottom: #01b9f5 solid 5px; */
                            font-weight: bold;
                        }

                        .past-task {
                            background-color: #ff4d4d;
                        }

                        .holiday-label {
                            font-size: 0.75em;
                            font-weight: normal;
                            color: #999;
                            margin-top: 5px;
                        }

                        .popup {
                            display: none;
                            position: absolute;
                            background: white;
                            padding: 20px;
                            border: 1px solid #ccc;
                            box-shadow: 2px 2px 12px rgba(0, 0, 0, 0.3);
                            z-index: 1000;
                        }

                        .popup button {
                            margin-top: 10px;
                            padding: 5px 10px;
                        }


                    }

                    @media all and (min-width: 651px) and (max-width: 1059px) {

                        table {
                            font-size: 1em !important;
                        }

                        .task-time {
                            background-color: #DCEFFF;
                            color: #003366;
                        }

                        .task-duration {
                            background-color: #b4995e;
                            color: #42371b;
                        }

                        .task-meeting {
                            background-color: #EAF8E6;
                            color: #1F5D30;
                        }

                        .task-leave {
                            background-color: #FDECEC;
                            color: #991F1F;
                        }

                        .task-complete {
                            background-color: #E6F4EA;
                            color: #2D5F3B;
                            border-bottom-left-radius: 5px;
                        }

                        .task-overdue {
                            background-color: #ffcccc;
                            color: #B30000;
                            /* border: 1px dashed #B30000; */
                        }

                        .time_section {
                            width: 20%;
                            padding-right: 3vw;
                            margin: 4px;
                            padding-left: 0.15vw;
                            display: flex;
                            flex-direction: row;
                            align-content: center;
                            justify-content: center;
                            align-items: center;
                            border-right: 1px solid black;
                        }

                        .data_section {
                            display: flex;
                            width: 80%;
                            padding-left: 10px;
                            flex-direction: row;
                            flex-wrap: wrap;
                            align-content: center;
                            justify-content: flex-start;
                            align-items: center;
                        }

                        .task_inter_data_div {
                            display: flex;
                            flex-direction: row;
                            align-content: center;
                            align-items: center;
                        }

                        body {
                            font-family: Arial, sans-serif;
                            display: flex;
                            justify-content: center;
                            align-items: center;
                            flex-direction: column;
                            gap: 20px;
                        }

                        .calendar {
                            border: 1px solid #ccc;
                            background-color: white;
                            padding: 10px;
                            border-radius: 8px;
                            box-shadow: 2px 2px 12px rgba(0, 0, 0, 0.1);
                            text-align: center;
                            width: 90%;
                            overflow: auto;
                        }

                        table {
                            width: 100%;
                            border-collapse: collapse;
                            font-size: 1em;
                        }


                        th,
                        td {
                            width:
                                <?php echo $displayWeekends ? '14%' : '20%'; ?>
                            ;
                            height: 100px;
                            overflow: hidden;
                            text-align: center;
                            border: 1px solid #ddd;
                            vertical-align: top;
                        }

                        th {
                            background-color: #f3f3f3;
                        }

                        .day {
                            font-weight: bold;
                        }

                        .task {
                            padding: 2px;
                            /* border: 3px solid black; */
                            margin-top: 0.8vh;

                            display: flex;
                            /* border-radius: 5px; */
                            font-size: 0.65em;
                            cursor: pointer;
                            box-shadow: 3px 2px 5px 0px rgba(0, 0, 0, 0.2);
                            flex-direction: row;
                            width: 79%;
                            margin-left: auto;
                            margin-right: auto;
                            overflow: hidden;
                            flex-wrap: wrap;
                            align-content: center;
                        }

                        .daily_task {
                            max-width: 80%;
                            padding: 8px;
                            /* border: 3px solid black; */
                            box-shadow: 3px 2px 5px 0px rgba(0, 0, 0, 0.2);
                            /* margin-top: 0.8vh; */
                            /* font-size: 0.65em; */
                            margin-left: -3%;
                            cursor: pointer;

                        }

                        .past-day {
                            background-color: #f0f0f0;
                            color: #aaa;
                        }

                        .current-day {
                            background-color: rgba(151, 229, 243, 0.3);
                            /* border-bottom: #01b9f5 solid 5px; */
                            font-weight: bold;
                        }

                        .past-task {
                            background-color: #ff4d4d;
                        }

                        .holiday-label {
                            font-size: 0.75em;
                            font-weight: normal;
                            color: #999;
                            margin-top: 5px;
                        }

                        .popup {
                            display: none;
                            position: absolute;
                            background: white;
                            padding: 20px;
                            border: 1px solid #ccc;
                            box-shadow: 2px 2px 12px rgba(0, 0, 0, 0.3);
                            z-index: 1000;
                        }

                        .popup button {
                            margin-top: 10px;
                            padding: 5px 10px;
                        }

                    }


                    @media all and (min-width: 1050px) {

                        table {
                            font-size: 1em !important;
                        }

                        .task-time {
                            background-color: #DCEFFF;
                            color: #003366;
                        }

                        .task-duration {
                            background-color: #b4995e;
                            color: #42371b;
                        }

                        .task-meeting {
                            background-color: #EAF8E6;
                            color: #1F5D30;
                        }

                        .task-leave {
                            background-color: #FDECEC;
                            color: #991F1F;
                        }

                        .task-complete {
                            background-color: #E6F4EA;
                            color: #2D5F3B;
                            border-bottom-left-radius: 5px;
                        }

                        .task-overdue {
                            background-color: #ffcccc;
                            color: #B30000;
                            /* border: 1px dashed #B30000; */
                        }

                        .time_section {
                            width: 20%;
                            padding-right: 1.15vw;
                            margin: 4px;
                            padding-left: 0.15vw;
                            display: flex;
                            flex-direction: row;
                            align-content: center;
                            justify-content: center;
                            align-items: center;
                            border-right: 1px solid black;
                        }

                        .data_section {
                            display: flex;
                            width: 80%;
                            padding-left: 10px;
                            flex-direction: row;
                            flex-wrap: wrap;
                            align-content: center;
                            justify-content: flex-start;
                            align-items: center;
                        }

                        .task_inter_data_div {
                            display: flex;
                            flex-direction: row;
                            align-content: center;
                            align-items: center;
                        }

                        body {
                            font-family: Arial, sans-serif;
                            display: flex;
                            justify-content: center;
                            align-items: center;
                            flex-direction: column;
                            gap: 20px;
                        }

                        .calendar {
                            border: 1px solid #ccc;
                            background-color: white;
                            padding: 10px;
                            border-radius: 8px;
                            box-shadow: 2px 2px 12px rgba(0, 0, 0, 0.1);
                            text-align: center;
                            width: 90%;
                            overflow: auto;
                        }

                        table {
                            width: 100%;
                            border-collapse: collapse;
                            font-size: 1em;
                        }


                        th,
                        td {
                            width:
                                <?php echo $displayWeekends ? '14%' : '20%'; ?>
                            ;
                            height: 100px;
                            overflow: hidden;
                            text-align: center;
                            border: 1px solid #ddd;
                            vertical-align: top;
                        }

                        th {
                            background-color: #f3f3f3;
                        }

                        .day {
                            font-weight: bold;
                        }

                        .task {
                            padding: 2px;
                            /* border: 3px solid black; */
                            margin-top: 5px;
                            display: flex;
                            /* border-radius: 5px; */
                            font-size: 0.65em;
                            cursor: pointer;
                            box-shadow: 3px 2px 5px 0px rgba(0, 0, 0, 0.2);
                            flex-direction: row;
                            width: 79%;
                            margin-left: auto;
                            margin-right: auto;
                            overflow: hidden;
                            flex-wrap: wrap;
                            align-content: center;
                        }


                        .daily_task {
                            max-width: 80%;
                            padding: 8px;
                            /* border: 3px solid black; */
                            box-shadow: 3px 2px 5px 0px rgba(0, 0, 0, 0.2);
                            margin-top: 5px;
                            font-size: 0.65em;
                            margin-left: -3%;
                            cursor: pointer;

                        }

                        .past-day {
                            background-color: #f0f0f0;
                            color: #aaa;
                        }

                        .current-day {
                            background-color: rgba(151, 229, 243, 0.3);
                            /* border-bottom: #01b9f5 solid 5px; */
                            font-weight: bold;
                        }

                        .past-task {
                            background-color: #ff4d4d;
                        }

                        .holiday-label {
                            font-size: 0.75em;
                            font-weight: normal;
                            color: #999;
                            margin-top: 5px;
                        }

                        .popup {
                            display: none;
                            position: absolute;
                            background: white;
                            padding: 20px;
                            border: 1px solid #ccc;
                            box-shadow: 2px 2px 12px rgba(0, 0, 0, 0.3);
                            z-index: 1000;
                        }

                        .popup button {
                            margin-top: 10px;
                            padding: 5px 10px;
                        }

                    }
                </style>

                <?php
    }
}
class 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;
                align-items: center;
                overflow: hidden;
            }
            .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);
    }
}