<?php
$first = new DateTime(sprintf('%04d-%02d-01', $year, $month));
$pad = ((int) $first->format('N')) - 1;
$cursor = (clone $first)->modify('-' . $pad . ' days');
$byDay = [];
foreach ($events as $ev) {
    $key = date('Y-m-d', strtotime((string) $ev['starts_at']));
    $byDay[$key][] = $ev;
}
$prev = (clone $first)->modify('-1 month');
$next = (clone $first)->modify('+1 month');
$todayKey = date('Y-m-d');
$now = time();
$calUrl = static function (DateTime $d): string {
    return url('calendar') . '?' . http_build_query(['month' => $d->format('n'), 'year' => $d->format('Y')]);
};
$counts = $counts ?? ['all' => 0, 'today' => 0, 'upcoming' => 0, 'call' => 0, 'visit' => 0, 'meeting' => 0];
$summaries = [
    ['This month', (int) $counts['all'], 'bi-calendar3', '#2563eb', '#eff6ff'],
    ['Today', (int) $counts['today'], 'bi-sun-fill', '#16a34a', '#f0fdf4'],
    ['Upcoming', (int) $counts['upcoming'], 'bi-clock-fill', '#ea580c', '#fff7ed'],
    ['Calls', (int) $counts['call'], 'bi-telephone-fill', '#7c3aed', '#f3e8ff'],
];
$typeClass = [
    'call' => 'is-call',
    'visit' => 'is-visit',
    'meeting' => 'is-meeting',
    'other' => 'is-other',
];
$typeIcon = [
    'call' => 'bi-telephone-fill',
    'visit' => 'bi-geo-alt-fill',
    'meeting' => 'bi-people-fill',
    'other' => 'bi-dot',
];
$typeLabel = [
    'call' => 'Call',
    'visit' => 'Visit',
    'meeting' => 'Meeting',
    'other' => 'Other',
];
$upcoming = array_values(array_filter($events, static fn (array $e): bool => strtotime((string) $e['starts_at']) >= $now));
$upcoming = array_slice($upcoming, 0, 8);
$weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
$dayPayload = static function (array $dayEvents) use ($typeClass, $typeIcon, $typeLabel): string {
    $rows = [];
    foreach ($dayEvents as $ev) {
        $kind = (string) ($ev['meeting_type'] ?? 'meeting');
        $ts = strtotime((string) $ev['starts_at']);
        $end = !empty($ev['ends_at']) ? strtotime((string) $ev['ends_at']) : false;
        $owner = trim((string) ($ev['owner_name'] ?? ''));
        $rows[] = [
            'title' => (string) ($ev['title'] ?? ''),
            'type' => $typeLabel[$kind] ?? 'Meeting',
            'cls' => $typeClass[$kind] ?? 'is-meeting',
            'icon' => $typeIcon[$kind] ?? 'bi-people-fill',
            'time' => $ts ? date('g:i A', $ts) : '',
            'end' => $end ? date('g:i A', $end) : '',
            'location' => trim((string) ($ev['location'] ?? '')),
            'owner' => $owner,
            'initials' => $owner !== '' ? name_initials($owner) : '',
            'related' => trim((string) ($ev['related_name'] ?? '')),
            'notes' => trim((string) ($ev['notes'] ?? '')),
        ];
    }
    return htmlspecialchars((string) json_encode($rows, JSON_UNESCAPED_UNICODE), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
};
?>
<div class="cal-page">
  <div class="mb-3">
    <h1 class="page-title">Calendar</h1>
    <p class="page-sub mb-0"><?= e($first->format('F Y')) ?> · meetings stay in the CRM; Outlook and Google sync in Settings</p>
  </div>

  <div class="opp-toolbar mb-3">
    <div class="opp-toggle">
      <a href="<?= e($calUrl($prev)) ?>"><i class="bi bi-chevron-left"></i> Prev</a>
      <a class="<?= ((int) date('n') === $month && (int) date('Y') === $year) ? 'active' : '' ?>" href="<?= e(url('calendar')) ?>">Today</a>
      <a href="<?= e($calUrl($next)) ?>">Next <i class="bi bi-chevron-right"></i></a>
    </div>
    <button class="btn btn-primary cal-add-btn" type="button" data-bs-toggle="collapse" data-bs-target="#newMeeting">
      <i class="bi bi-plus-lg"></i> Add meeting
    </button>
  </div>

  <div class="task-summary mb-3">
    <?php foreach ($summaries as $s): ?>
      <div class="task-summary-card" style="--task-accent: <?= e($s[3]) ?>; --task-tint: <?= e($s[4]) ?>">
        <div class="task-summary-icon"><i class="bi <?= e($s[2]) ?>"></i></div>
        <div>
          <div class="task-summary-n"><?= (int) $s[1] ?></div>
          <div class="task-summary-l"><?= e($s[0]) ?></div>
        </div>
      </div>
    <?php endforeach; ?>
  </div>

  <form class="collapse contact-add mb-3 ajax-form" id="newMeeting" action="<?= e(url('calendar')) ?>" method="post">
    <?= csrf_field() ?>
    <div class="contact-add-title"><i class="bi bi-calendar-plus"></i> New meeting</div>
    <div class="row g-2 align-items-end">
      <div class="col-md-4"><label class="form-label">Title *</label><input class="form-control" name="title" required maxlength="180"></div>
      <div class="col-md-3"><label class="form-label">Starts *</label><input class="form-control" type="datetime-local" name="starts_at" required></div>
      <div class="col-md-2"><label class="form-label">Type</label>
        <select class="form-select" name="meeting_type">
          <option value="meeting">Meeting</option>
          <option value="call">Call</option>
          <option value="visit">Visit</option>
          <option value="other">Other</option>
        </select>
      </div>
      <div class="col-md-2"><label class="form-label">Place / Zoom</label><input class="form-control" name="location" maxlength="180"></div>
      <div class="col-md-1"><button class="btn btn-primary w-100" type="submit">Save</button></div>
    </div>
  </form>

  <div class="cal-board">
    <div class="cal-board-head">
      <div class="cal-board-month"><?= e($first->format('F Y')) ?></div>
      <div class="cal-legend" aria-label="Event types">
        <span><i class="cal-dot is-meeting"></i> Meeting</span>
        <span><i class="cal-dot is-call"></i> Call</span>
        <span><i class="cal-dot is-visit"></i> Visit</span>
      </div>
    </div>
    <div class="cal-weekdays">
      <?php foreach ($weekdays as $i => $d): ?>
        <div class="<?= $i >= 5 ? 'is-weekend' : '' ?>"><?= e($d) ?></div>
      <?php endforeach; ?>
    </div>
    <div class="cal-grid">
      <?php for ($i = 0; $i < 42; $i++):
          $key = $cursor->format('Y-m-d');
          $mute = (int) $cursor->format('n') !== $month;
          $isToday = $key === $todayKey;
          $isWeekend = (int) $cursor->format('N') >= 6;
          $dayEvents = $byDay[$key] ?? [];
          $shown = array_slice($dayEvents, 0, 3);
          $extra = count($dayEvents) - 3;
      ?>
        <div class="cal-cell <?= $mute ? 'mute' : '' ?> <?= $isToday ? 'is-today' : '' ?> <?= $isWeekend && !$mute ? 'is-weekend' : '' ?> <?= $dayEvents ? 'has-events' : '' ?>"
          <?php if ($dayEvents): ?>
            role="button" tabindex="0"
            data-date="<?= e($cursor->format('l, F j, Y')) ?>"
            data-count="<?= count($dayEvents) ?>"
            data-events="<?= $dayPayload($dayEvents) ?>"
          <?php endif; ?>
        >
          <div class="cal-daynum"><?= $cursor->format('j') ?></div>
          <?php foreach ($shown as $ev):
              $kind = (string) ($ev['meeting_type'] ?? 'meeting');
              $cls = $typeClass[$kind] ?? 'is-meeting';
              $when = date('g:ia', strtotime((string) $ev['starts_at']));
          ?>
            <div class="cal-event <?= e($cls) ?>" title="<?= e(($typeLabel[$kind] ?? 'Meeting') . ' · ' . $ev['title'] . ' · ' . date('g:i A', strtotime((string) $ev['starts_at']))) ?>">
              <?= e($when) ?> <?= e($ev['title']) ?>
            </div>
          <?php endforeach; ?>
          <?php if ($extra > 0): ?>
            <div class="cal-more">+<?= $extra ?> more</div>
          <?php endif; ?>
        </div>
      <?php $cursor->modify('+1 day'); endfor; ?>
    </div>
  </div>

  <div class="cal-side mt-3">
    <div class="cal-side-title">Coming up</div>
    <?php if (!$upcoming): ?>
      <p class="text-muted mb-0">No upcoming items this month.</p>
    <?php else: ?>
      <div class="cal-side-grid">
        <?php foreach ($upcoming as $ev):
            $kind = (string) ($ev['meeting_type'] ?? 'meeting');
            $cls = $typeClass[$kind] ?? 'is-meeting';
            $icon = $typeIcon[$kind] ?? 'bi-people-fill';
            $ts = strtotime((string) $ev['starts_at']);
            $owner = trim((string) ($ev['owner_name'] ?? ''));
        ?>
          <div class="cal-side-item">
            <div class="event-date <?= e($cls) ?>">
              <div class="mon"><?= e(date('M', $ts)) ?></div>
              <div class="day"><?= e(date('j', $ts)) ?></div>
            </div>
            <div class="min-w-0">
              <div class="fw-bold text-truncate"><?= e($ev['title']) ?></div>
              <div class="small text-muted text-truncate">
                <i class="bi <?= e($icon) ?>"></i>
                <?= e(date('g:i A', $ts)) ?>
                <?php if (!empty($ev['location'])): ?> · <?= e($ev['location']) ?><?php endif; ?>
              </div>
              <div class="cal-side-meta">
                <?php if ($owner !== ''): ?>
                  <span class="task-owner-chip" title="<?= e($owner) ?>">
                    <span class="task-avatar"><?= e(name_initials($owner)) ?></span>
                    <span class="task-owner text-truncate"><?= e($owner) ?></span>
                  </span>
                <?php endif; ?>
                <?php if (!empty($ev['related_name'])): ?>
                  <span class="cal-related text-truncate"><?= e($ev['related_name']) ?></span>
                <?php endif; ?>
              </div>
            </div>
          </div>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>
  </div>
</div>

<div class="modal fade" id="calDayModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
    <div class="modal-content cal-day-modal">
      <div class="modal-header">
        <div>
          <div class="cal-day-modal-count"></div>
          <h5 class="modal-title"></h5>
        </div>
        <button class="btn-close" type="button" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body" id="calDayModalBody"></div>
    </div>
  </div>
</div>
