<?php
require 'db.php';

/* ===============================
   GROUP SETUP
================================ */
$groupSlug = $_GET['group'] ?? null;
if (!$groupSlug) {
  die("Group not specified.");
}

/* Fetch group */
$stmt = $pdo->prepare("SELECT id, name FROM groups WHERE slug = ?");
$stmt->execute([$groupSlug]);
$group = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$group) {
  die("Group not found.");
}

/* ===============================
   MONTH / YEAR SETUP
================================ */
$month = isset($_GET['month']) ? (int)$_GET['month'] : (int)date('m');
$year  = isset($_GET['year'])  ? (int)$_GET['year']  : (int)date('Y');

if ($month < 1) { $month = 12; $year--; }
if ($month > 12) { $month = 1; $year++; }

$prevMonth = $month - 1;
$prevYear  = $year;
if ($prevMonth < 1) { $prevMonth = 12; $prevYear--; }

$nextMonth = $month + 1;
$nextYear  = $year;
if ($nextMonth > 12) { $nextMonth = 1; $nextYear++; }

/* Calendar math */
$firstDayTimestamp = strtotime("$year-$month-01");
$daysInMonth = date('t', $firstDayTimestamp);
$startDay = date('w', $firstDayTimestamp);

/* ===============================
   GROUP EVENT COUNTS
================================ */
$stmt = $pdo->prepare("
  SELECT event_date, COUNT(*) AS total
  FROM events
  WHERE group_id = ?
    AND MONTH(event_date) = ?
    AND YEAR(event_date)  = ?
  GROUP BY event_date
");
$stmt->execute([$group['id'], $month, $year]);

$eventCounts = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

/* ===============================
   RETURN URL
================================ */
$currentUrl = $_SERVER['REQUEST_URI'];
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><?= htmlspecialchars($group['name']) ?> Calendar</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<style>
body {
  font-family: Inter, Arial, sans-serif;
  background: #f8f5f0;
  margin: 0;
  padding: 20px;
  color: #1f2937;
}

/* HEADER */
.calendar-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
  margin-bottom: 16px;
  flex-wrap: wrap;
}

.calendar-title {
  width: 100%;
  text-align: center;
  font-family: "Playfair Display", serif;
  font-size: 1.4rem;
  color: #2c5aa0;
  margin-bottom: 6px;
}

.nav-btn {
  background: #2c5aa0;
  color: #fff;
  padding: 6px 12px;
  border-radius: 6px;
  text-decoration: none;
  font-size: 0.8rem;
}

/* SELECT */
.calendar-select {
  display: flex;
  gap: 6px;
}

.calendar-select select {
  padding: 6px 8px;
  border-radius: 6px;
  border: 1px solid #cbd5e1;
  font-size: 0.8rem;
}

/* TABLE */
table {
  width: 100%;
  border-collapse: collapse;
  background: #ffffff;
  border-radius: 12px;
  overflow: hidden;
}

th {
  background: #2c5aa0;
  color: #ffffff;
  padding: 8px;
  font-size: 0.7rem;
}

td {
  border: 1px solid #e5e7eb;
  text-align: center;
  padding: 10px 4px;
}

td a {
  display: block;
  text-decoration: none;
  color: #1f2937;
}

/* DAY */
.day-number {
  font-size: 0.9rem;
  font-weight: 500;
}

/* EVENT */
.has-event {
  background: #f5d48b;
  font-weight: 600;
}

.today {
  outline: 2px solid #2c5aa0;
  outline-offset: -2px;
}

.event-dot {
  width: 6px;
  height: 6px;
  background: #8b5e1a;
  border-radius: 50%;
  margin: 4px auto 0;
}

.event-badge {
  background: #8b5e1a;
  color: #fff;
  font-size: 0.65rem;
  border-radius: 10px;
  padding: 2px 6px;
  margin-top: 4px;
  display: inline-block;
}

/* MOBILE */
@media (max-width: 600px) {
  .calendar-select {
    width: 100%;
    justify-content: center;
  }
}
</style>
</head>

<body>

<div class="calendar-header">

  <div class="calendar-title">
    <?= htmlspecialchars($group['name']) ?> Calendar
  </div>

  <a class="nav-btn"
     href="?group=<?= urlencode($groupSlug) ?>&month=<?= $prevMonth ?>&year=<?= $prevYear ?>">
     ← Prev
  </a>

  <form method="get" class="calendar-select">
    <input type="hidden" name="group" value="<?= htmlspecialchars($groupSlug) ?>">

    <select name="month" onchange="this.form.submit()">
      <?php
      for ($m = 1; $m <= 12; $m++) {
        $sel = ($m == $month) ? 'selected' : '';
        echo "<option value='$m' $sel>" .
             date('F', mktime(0,0,0,$m,1)) .
             "</option>";
      }
      ?>
    </select>

    <select name="year" onchange="this.form.submit()">
      <?php
      $cy = date('Y');
      for ($y = $cy - 5; $y <= $cy + 5; $y++) {
        $sel = ($y == $year) ? 'selected' : '';
        echo "<option value='$y' $sel>$y</option>";
      }
      ?>
    </select>
  </form>

  <a class="nav-btn"
     href="?group=<?= urlencode($groupSlug) ?>&month=<?= $nextMonth ?>&year=<?= $nextYear ?>">
     Next →
  </a>

</div>

<table>
<tr>
  <th>Sun</th><th>Mon</th><th>Tue</th>
  <th>Wed</th><th>Thu</th><th>Fri</th><th>Sat</th>
</tr>
<tr>

<?php
$day = 1;

/* Empty cells */
for ($i = 0; $i < $startDay; $i++) {
  echo "<td></td>";
}

/* Days */
while ($day <= $daysInMonth) {

  $date  = sprintf('%04d-%02d-%02d', $year, $month, $day);
  $count = $eventCounts[$date] ?? 0;

  $classes = [];
  if ($count > 0) $classes[] = 'has-event';
  if ($date === date('Y-m-d')) $classes[] = 'today';

  //$eventUrl = "../events.php?date=$date&return=" . urlencode($currentUrl);
$eventUrl = "/cathedral-portal/events.php?date=$date&return=" . urlencode($currentUrl);

  echo "<td class='".implode(' ', $classes)."'>
          <a href='$eventUrl'>
            <span class='day-number'>$day</span>";

  if ($count == 1) {
    echo "<span class='event-dot'></span>";
  } elseif ($count > 1) {
    echo "<span class='event-badge'>$count</span>";
  }

  echo "</a></td>";

  if ((($day + $startDay) % 7) == 0) {
    echo "</tr><tr>";
  }

  $day++;
}
?>

</tr>
</table>

</body>
</html>

