<?php
// file: build_calendar.php

if (!isset($_GET['month']) || !isset($_GET['year'])) {
    exit;
}

$month = $_GET['month'];
$year = $_GET['year'];
$holidays = json_decode($_GET['holidays'], true);

$firstDay = mktime(0, 0, 0, $month, 1, $year);
$title = date('F Y', $firstDay);
$dayOfWeek = date('w', $firstDay);
$daysInMonth = date('t', $firstDay);
$runningDay = date('w', $firstDay);
$daysInWeek = 1;
$dayCounter = 0;

$calendar = '<h3 class="text-center">' . $title . '</h3>';
$calendar .= '<table class="table table-bordered">';
$calendar .= '<tr class="text-center"><th>Min</th><th>Sen</th><th>Sel</th><th>Rab</th><th>Kam</th><th>Jum</th><th>Sab</th></tr>';
$calendar .= '<tr>';

// Buat kotak kosong untuk hari-hari sebelum tanggal 1
for ($x = 0; $x < $runningDay; $x++) {
    $calendar .= '<td></td>';
    $daysInWeek++;
}

// Loop untuk setiap hari di bulan
for ($day = 1; $day <= $daysInMonth; $day++) {
    $currentDate = date('Y-m-d', mktime(0, 0, 0, $month, $day, $year));
    $isWeekend = (date('w', strtotime($currentDate)) == 0 || date('w', strtotime($currentDate)) == 6);
    $isHoliday = isset($holidays[$currentDate]);

    $class = '';
    if ($isWeekend) {
        $class = 'warning';
    } elseif ($isHoliday) {
        $class = 'danger';
    }

    $calendar .= '<td class="day-box ' . $class . '" data-date="' . $currentDate . '" data-day="' . date('w', strtotime($currentDate)) . '">';
    $calendar .= '<strong>' . $day . '</strong>';
    if ($isHoliday) {
        $calendar .= '<br><small>' . htmlspecialchars($holidays[$currentDate]) . '</small>';
    }
    $calendar .= '</td>';

    if ($runningDay == 6) {
        $calendar .= '</tr>';
        if (($dayCounter + 1) != $daysInMonth) {
            $calendar .= '<tr>';
        }
        $runningDay = -1;
        $daysInWeek = 0;
    }
    $runningDay++;
    $dayCounter++;
    $daysInWeek++;
}

if ($daysInWeek < 8) {
    for ($x = 1; $x <= (8 - $daysInWeek); $x++) {
        $calendar .= '<td></td>';
    }
}

$calendar .= '</tr></table>';
echo $calendar;
?>