<?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
    }
}