<?php
require_once 'includes/config.php';
requireLogin();
$uid = $_SESSION['user_id'];

// AJAX: regenerate token
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    $action = $_POST['action'] ?? '';
    if ($action === 'regenerate_token') {
        $newToken = bin2hex(random_bytes(24));
        $pdo->prepare("UPDATE users SET calendar_token=? WHERE id=?")->execute([$newToken, $uid]);
        jsonResponse(['success' => true, 'token' => $newToken]);
    }
    jsonResponse(['success' => false, 'message' => 'Unknown action.']);
}

// Ensure token exists
$stmt = $pdo->prepare("SELECT calendar_token FROM users WHERE id=?");
$stmt->execute([$uid]);
$token = $stmt->fetchColumn();
if (!$token) {
    $token = bin2hex(random_bytes(24));
    $pdo->prepare("UPDATE users SET calendar_token=? WHERE id=?")->execute([$token, $uid]);
}

$feedUrlHttps = SITE_URL . '/calendar-feed.php?token=' . $token;
$feedUrlWebcal = str_replace(['https://', 'http://'], 'webcal://', $feedUrlHttps);

// Upcoming exam dates for quick one-off Google Calendar links
$exams = $pdo->query("SELECT * FROM al_exam_dates WHERE is_active=1 AND exam_date >= CURDATE() ORDER BY exam_date ASC LIMIT 8")->fetchAll();

function gcalLink($title, $dateYmd, $desc = '') {
    $start = $dateYmd;
    $end = date('Ymd', strtotime($dateYmd . ' +1 day'));
    return 'https://calendar.google.com/calendar/render?action=TEMPLATE&text=' . urlencode($title) .
           '&dates=' . $start . '/' . $end . '&details=' . urlencode($desc);
}

require_once 'includes/header.php';
renderHeader('Calendar Sync', 'calendar-sync');
?>
<div style="margin-bottom:22px">
  <div style="font-size:22px;font-weight:800;font-family:'Sora',sans-serif">📅 Calendar Sync</div>
  <div style="font-size:13px;color:var(--text-muted);margin-top:3px">Subscribe once and your timetable, exam dates, task deadlines & goal deadlines stay synced automatically</div>
</div>

<div class="card" style="margin-bottom:18px">
  <div style="font-size:15px;font-weight:700;margin-bottom:6px">🔗 Your Private Sync Link</div>
  <div style="font-size:13px;color:var(--text-secondary);margin-bottom:14px">This link is unique to you — anyone with it can view your schedule, so don't share it publicly.</div>

  <div style="display:flex;gap:8px;flex-wrap:wrap;align-items:center">
    <input type="text" id="feedUrl" class="form-input" value="<?= htmlspecialchars($feedUrlHttps) ?>" readonly style="flex:1;min-width:240px;font-family:monospace;font-size:12px">
    <button class="btn btn-primary btn-sm" onclick="copyFeed()">📋 Copy Link</button>
    <button class="btn btn-secondary btn-sm" onclick="regenerateToken()">🔄 Regenerate</button>
  </div>
  <div id="copyMsg" style="display:none;margin-top:10px"></div>
</div>

<div class="card" style="margin-bottom:18px">
  <div style="font-size:15px;font-weight:700;margin-bottom:12px">📱 How to subscribe</div>
  <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:16px">
    <div>
      <div style="font-weight:700;font-size:13px;margin-bottom:6px">Google Calendar</div>
      <div style="font-size:12px;color:var(--text-secondary);line-height:1.6">
        On desktop: Google Calendar → <b>Other calendars +</b> → <b>From URL</b> → paste the link above → <b>Add calendar</b>.
        It refreshes automatically every few hours.
      </div>
    </div>
    <div>
      <div style="font-weight:700;font-size:13px;margin-bottom:6px">Apple Calendar</div>
      <div style="font-size:12px;color:var(--text-secondary);line-height:1.6">
        Tap the <b>Copy Link</b> button, then in the Calendar app: <b>File → New Calendar Subscription</b> (Mac) or
        <b>Settings → Calendar → Add Account → Other → Add Subscribed Calendar</b> (iPhone), then paste it.
      </div>
    </div>
    <div>
      <div style="font-weight:700;font-size:13px;margin-bottom:6px">Outlook</div>
      <div style="font-size:12px;color:var(--text-secondary);line-height:1.6">
        Add calendar → <b>Subscribe from web</b> → paste the link above.
      </div>
    </div>
  </div>
</div>

<?php if ($exams): ?>
<div class="card">
  <div style="font-size:15px;font-weight:700;margin-bottom:12px">➕ Quick add: Upcoming A/L exam dates</div>
  <div style="display:flex;flex-direction:column;gap:10px">
    <?php foreach ($exams as $e): ?>
      <div style="display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap;padding:10px;background:var(--bg-secondary);border-radius:10px">
        <div>
          <div style="font-size:13px;font-weight:600"><?= htmlspecialchars($e['exam_name']) ?></div>
          <div style="font-size:12px;color:var(--text-muted)"><?= date('l, M j, Y', strtotime($e['exam_date'])) ?></div>
        </div>
        <a class="btn btn-secondary btn-sm" target="_blank" href="<?= htmlspecialchars(gcalLink($e['exam_name'], $e['exam_date'], $e['description'] ?: '')) ?>">Add to Google Calendar</a>
      </div>
    <?php endforeach; ?>
  </div>
</div>
<?php endif; ?>

<script>
function copyFeed() {
  const input = document.getElementById('feedUrl');
  input.select(); input.setSelectionRange(0, 99999);
  navigator.clipboard.writeText(input.value).then(() => {
    const msg = document.getElementById('copyMsg');
    msg.style.display = 'block'; msg.className = 'alert alert-success';
    msg.textContent = 'Link copied! Paste it into your calendar app.';
    setTimeout(() => msg.style.display = 'none', 2500);
  });
}

async function regenerateToken() {
  if (!(await stConfirm('Regenerate your sync link? Your old link will stop working in any calendar app you already subscribed with.', {icon:'🔄', okStyle:'primary', okLabel:'Regenerate'}))) return;
  const fd = new FormData(); fd.append('action', 'regenerate_token');
  const r = await fetch(location.href, { method:'POST', headers:{'X-Requested-With':'XMLHttpRequest'}, body: fd });
  const data = await r.json();
  if (data.success) location.reload();
}
</script>

<?php require_once 'includes/footer.php'; renderFooter(); ?>
