<?php
// ============================================================
// Elegant Work — Meeting RSVP (public, no auth required)
// GET  /api/meetings/rsvp.php?token=XXX          → show form
// GET  /api/meetings/rsvp.php?token=XXX&r=accept|decline|reschedule&date=YYYY-MM-DD&time=HH:MM&place=text
// ============================================================
require_once __DIR__ . '/../config/db.php';

$db     = getDB();
$token  = trim($_GET['token'] ?? '');
$r      = trim($_GET['r']     ?? ''); // accept | decline | reschedule
$date   = trim($_GET['date']  ?? ''); // proposed new date for reschedule
$time   = trim($_GET['time']  ?? ''); // proposed new time
$place  = trim($_GET['place'] ?? ''); // proposed new location

header('Content-Type: text/html; charset=utf-8');
header('X-Frame-Options: SAMEORIGIN');

if (!$token) { echo _page('Invalid Link', '<p>This RSVP link is invalid or has already been used.</p>', 'error'); exit; }

// ── Look up attendee + meeting ────────────────────────────────
$stmt = $db->prepare("
    SELECT ma.id AS attendee_id, ma.name, ma.email, ma.rsvp_status,
           ma.meeting_id,
           m.title, m.meeting_date, m.start_time, m.end_time,
           m.location, m.description, m.created_by,
           u.full_name AS organiser_name, u.email AS organiser_email
    FROM meeting_attendees ma
    JOIN meetings m ON m.id = ma.meeting_id
    LEFT JOIN users u ON u.id = m.created_by
    WHERE ma.rsvp_token = ?
    LIMIT 1
");
$stmt->execute([$token]);
$row = $stmt->fetch();

if (!$row) { echo _page('Invalid Link', '<p>This RSVP link is invalid or has expired.</p>', 'error'); exit; }

$name    = htmlspecialchars($row['name'] ?: 'Guest');
$title   = htmlspecialchars($row['title']);
$dateStr = date('l, d F Y', strtotime($row['meeting_date']));
$timeStr = $row['start_time']
    ? date('H:i', strtotime($row['start_time'])) . ($row['end_time'] ? ' – '.date('H:i', strtotime($row['end_time'])) : '')
    : 'All Day';
$loc     = htmlspecialchars($row['location'] ?? '');

// ── Process response ──────────────────────────────────────────
if ($r && in_array($r, ['accept','decline','reschedule'])) {
    // Reschedule requires a date
    if ($r === 'reschedule' && !$date) {
        // Show the reschedule form
        echo _rescheduleForm($name, $title, $dateStr, $timeStr, $loc, $token);
        exit;
    }

    $statusMap = ['accept' => 'accepted', 'decline' => 'declined', 'reschedule' => 'reschedule_requested'];
    $newStatus = $statusMap[$r];
    $noteParts = [];
    if ($r === 'reschedule') {
        if ($date)  $noteParts[] = "date:$date";
        if ($time)  $noteParts[] = "time:$time";
        if ($place) $noteParts[] = "place:" . $place;
    }
    $note = implode('|', $noteParts);

    $db->prepare("
        UPDATE meeting_attendees
        SET rsvp_status=?, rsvp_note=?, rsvp_at=NOW()
        WHERE rsvp_token=?
    ")->execute([$newStatus, $note, $token]);

    // Queue notification to organiser (direct DB insert, no mailer dependency)
    try {
        $cfg = $db->query("SELECT setting_key, setting_value FROM settings WHERE setting_group='email'")->fetchAll(\PDO::FETCH_KEY_PAIR);
        if (!empty($cfg['email_enabled']) && $cfg['email_enabled'] === '1' && !empty($row['organiser_email'])) {
            $icons  = ['accepted'=>'✅','declined'=>'❌','reschedule_requested'=>'🔄'];
            $labels = ['accepted'=>'Accepted','declined'=>'Declined','reschedule_requested'=>'Reschedule Requested'];
            $colors = ['accepted'=>'#16a34a','declined'=>'#dc2626','reschedule_requested'=>'#0284c7'];
            $icon   = $icons[$newStatus]  ?? '📋';
            $label  = $labels[$newStatus] ?? $newStatus;
            $color  = $colors[$newStatus] ?? '#6b7280';
            // Parse structured note
            $noteHtml = '';
            if ($note && $newStatus === 'reschedule_requested') {
                $parts = [];
                foreach (explode('|', $note) as $part) {
                    if (str_starts_with($part, 'date:'))  $parts['Date']     = substr($part, 5);
                    if (str_starts_with($part, 'time:'))  $parts['Time']     = substr($part, 5);
                    if (str_starts_with($part, 'place:')) $parts['Location'] = substr($part, 6);
                }
                if ($parts) {
                    $rows = '';
                    foreach ($parts as $k => $v) $rows .= "<tr><td style='padding:4px 8px;color:#6b7280;font-size:12px'>$k</td><td style='padding:4px 8px;font-weight:600'>" . htmlspecialchars($v) . "</td></tr>";
                    $appUrl  = $cfg['email_app_url'] ?? '';
                    $meetId  = $row['meeting_id'];
                    $attId   = $row['attendee_id'];
                    $noteHtml = "<div style='background:#e0f2fe;border:1px solid #7dd3fc;border-radius:8px;padding:14px;margin-top:12px'>
                        <div style='font-size:12px;font-weight:700;color:#0284c7;text-transform:uppercase;margin-bottom:8px'>Proposed Changes</div>
                        <table cellpadding='0' cellspacing='0'>$rows</table>
                    </div>
                    " . ($appUrl ? "<div style='margin-top:14px;display:flex;gap:8px'>
                        <a href='{$appUrl}api/meetings/organiser_action.php?meeting_id={$meetId}&attendee_id={$attId}&action=accept_reschedule&note=" . urlencode($note) . "' style='padding:9px 16px;background:#16a34a;color:#fff;border-radius:6px;text-decoration:none;font-weight:600;font-size:13px'>✅ Accept Reschedule</a>
                        <a href='{$appUrl}api/meetings/organiser_action.php?meeting_id={$meetId}&attendee_id={$attId}&action=keep_original' style='padding:9px 16px;background:#f3f4f6;color:#374151;border-radius:6px;text-decoration:none;font-weight:600;font-size:13px'>Keep Original Date</a>
                    </div>" : '');
                }
            } elseif ($note) {
                $noteHtml = "<p style='margin-top:12px;color:#6b7280;font-size:13px'>Note: <em>" . htmlspecialchars($note) . "</em></p>";
            }
            $subject = "📅 RSVP {$label}: {$row['title']}";
            $html = "<!DOCTYPE html><html><body style='font-family:sans-serif;background:#f4f6f9;padding:32px'>
                <div style='max-width:500px;margin:0 auto;background:#fff;border-radius:10px;padding:32px'>
                <div style='font-size:2rem;text-align:center'>{$icon}</div>
                <h2 style='text-align:center;color:{$color}'>{$label}</h2>
                <p style='color:#374151'><strong>" . htmlspecialchars($row['name']) . "</strong> has responded to <strong>{$title}</strong>.</p>
                {$noteHtml}
                <p style='color:#6b7280;font-size:12px;margin-top:24px'>Elegant Work Meeting System</p>
                </div></body></html>";
            $db->prepare("
                INSERT INTO email_queue (notification_type, recipient_email, recipient_name, subject, body_html, related_type, related_id)
                VALUES ('meeting_rsvp', ?, ?, ?, ?, 'meeting', ?)
            ")->execute([$row['organiser_email'], $row['organiser_name'], $subject, $html, $row['meeting_id']]);
        }
    } catch (Exception $e) { /* silent */ }

    $messages = [
        'accepted'             => ['✅ You\'re In!',           "Thanks <strong>{$name}</strong>, your attendance for <strong>{$title}</strong> on {$dateStr} is confirmed."],
        'declined'             => ['❌ RSVP Declined',         "Thanks <strong>{$name}</strong>, we've noted you won't be attending <strong>{$title}</strong>."],
        'reschedule_requested' => ['🔄 Reschedule Requested',  "Thanks <strong>{$name}</strong>, the organiser has been notified of your reschedule request for <strong>{$title}</strong>." . ($date ? " Proposed date: <strong>" . htmlspecialchars($date) . "</strong>" : '') . ($time ? " at <strong>" . htmlspecialchars($time) . "</strong>" : '') . ($place ? ". Proposed location: <strong>" . htmlspecialchars($place) . "</strong>" : '') . "."],
    ];
    [$heading, $body] = $messages[$newStatus];
    echo _page($heading, "<p style='color:#374151;line-height:1.6'>{$body}</p>", $r === 'accept' ? 'success' : 'info');
    exit;
}

// ── Show invite form ──────────────────────────────────────────
echo _inviteForm($name, $title, $dateStr, $timeStr, $loc, $token, htmlspecialchars($row['description'] ?? ''));
exit;

// ── HTML Helpers ──────────────────────────────────────────────
function _shell(string $content): string {
    return <<<HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1">
  <title>Meeting RSVP</title>
  <style>
    * { margin:0; padding:0; box-sizing:border-box }
    body { font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Helvetica,Arial,sans-serif;
           background:#f0f4ff; min-height:100vh; display:flex; align-items:center;
           justify-content:center; padding:20px }
    .card { background:#fff; border-radius:14px; box-shadow:0 8px 32px rgba(27,75,138,.12);
            max-width:480px; width:100%; overflow:hidden }
    .card-head { background:#1b4b8a; padding:24px 28px; color:#fff }
    .card-head h1 { font-size:18px; font-weight:700; margin-bottom:3px }
    .card-head p  { font-size:13px; opacity:.75 }
    .card-body { padding:24px 28px }
    .detail { display:flex; gap:10px; margin-bottom:12px; align-items:flex-start }
    .detail-icon { font-size:1.1rem; flex-shrink:0; line-height:1.4 }
    .detail-label { font-size:11px; color:#9ca3af; text-transform:uppercase; letter-spacing:.4px; margin-bottom:1px }
    .detail-value { font-size:14px; color:#1a1a2e; font-weight:500; line-height:1.4 }
    .divider { height:1px; background:#f3f4f6; margin:18px 0 }
    .btn { display:block; width:100%; padding:14px; border:none; border-radius:9px;
           font-size:15px; font-weight:600; cursor:pointer; margin-bottom:10px;
           text-align:center; text-decoration:none; transition:opacity .15s }
    .btn:hover { opacity:.88 }
    .btn-accept    { background:#16a34a; color:#fff }
    .btn-decline   { background:#fee2e2; color:#dc2626 }
    .btn-reschedule{ background:#e0f2fe; color:#0284c7 }
    .brand { text-align:center; font-size:11px; color:#c3cfe0; padding:12px 28px 20px }
    /* result page */
    .result-icon { font-size:3rem; text-align:center; margin-bottom:12px }
    .result-head { font-size:20px; font-weight:700; text-align:center; margin-bottom:10px }
    .result-head.success { color:#16a34a }
    .result-head.error   { color:#dc2626 }
    .result-head.info    { color:#0284c7 }
    /* reschedule form */
    label.field-label { display:block; font-size:12px; font-weight:600; color:#6b7280;
                        text-transform:uppercase; letter-spacing:.4px; margin-bottom:5px }
    input[type=date], input[type=time], input[type=text] {
        width:100%; max-width:100%; padding:11px 13px; border:2px solid #e5e7eb;
        border-radius:8px; font-size:15px; margin-bottom:16px; font-family:inherit;
        box-sizing:border-box; -webkit-appearance:none; appearance:none }
    input[type=date]:focus, input[type=time]:focus, input[type=text]:focus
        { outline:none; border-color:#1b4b8a }
  </style>
</head>
<body>
  <div class="card">
    {$content}
    <div class="brand">Powered by Elegant Work</div>
  </div>
</body>
</html>
HTML;
}

function _inviteForm(string $name, string $title, string $dateStr, string $timeStr, string $loc, string $token, string $desc): string {
    $locHtml = $loc ? "<div class='detail'><div class='detail-icon'>📍</div><div><div class='detail-label'>Location</div><div class='detail-value'>{$loc}</div></div></div>" : '';
    $descHtml = $desc ? "<div class='detail'><div class='detail-icon'>📝</div><div><div class='detail-label'>Details</div><div class='detail-value' style='white-space:pre-wrap'>{$desc}</div></div></div>" : '';
    $t = urlencode($token);
    return _shell(<<<HTML
    <div class="card-head">
      <h1>📅 Meeting Invitation</h1>
      <p>Please let the organiser know if you can attend</p>
    </div>
    <div class="card-body">
      <p style="font-size:15px;color:#1a1a2e;font-weight:600;margin-bottom:16px">{$title}</p>
      <div class="detail"><div class="detail-icon">📅</div><div><div class="detail-label">Date</div><div class="detail-value">{$dateStr}</div></div></div>
      <div class="detail"><div class="detail-icon">⏰</div><div><div class="detail-label">Time</div><div class="detail-value">{$timeStr}</div></div></div>
      {$locHtml}
      {$descHtml}
      <div class="divider"></div>
      <p style="font-size:13px;color:#6b7280;margin-bottom:16px">Hi <strong>{$name}</strong>, will you be attending?</p>
      <a class="btn btn-accept"     href="?token={$t}&r=accept">✅ Yes, I'll be there</a>
      <a class="btn btn-decline"    href="?token={$t}&r=decline">❌ No, I can't make it</a>
      <a class="btn btn-reschedule" href="?token={$t}&r=reschedule">🔄 Request to reschedule</a>
    </div>
HTML);
}

function _rescheduleForm(string $name, string $title, string $dateStr, string $timeStr, string $loc, string $token): string {
    $t = htmlspecialchars($token);
    $today = date('Y-m-d');
    return _shell(<<<HTML
    <div class="card-head">
      <h1>🔄 Request Reschedule</h1>
      <p>Suggest an alternative date, time and place</p>
    </div>
    <div class="card-body">
      <p style="font-size:14px;color:#6b7280;margin-bottom:20px">
        Requesting to reschedule <strong>{$title}</strong> currently scheduled for <strong>{$dateStr}</strong> at <strong>{$timeStr}</strong>.
      </p>
      <form method="GET" action="" style="width:100%">
        <input type="hidden" name="token" value="{$t}">
        <input type="hidden" name="r" value="reschedule">
        <label class="field-label">Proposed date <span style="color:#dc2626">*</span></label>
        <input type="date" name="date" required min="{$today}">
        <label class="field-label">Proposed time <span style="color:#9ca3af">(optional)</span></label>
        <input type="time" name="time">
        <label class="field-label">Proposed location <span style="color:#9ca3af">(optional)</span></label>
        <input type="text" name="place" placeholder="e.g. Conference Room B or Zoom link" maxlength="255">
        <button type="submit" class="btn btn-reschedule" style="margin-top:8px">Send Reschedule Request</button>
      </form>
      <a href="?token={$t}" style="display:block;text-align:center;font-size:13px;color:#9ca3af;margin-top:12px;text-decoration:none">← Back</a>
    </div>
HTML);
}

function _page(string $heading, string $body, string $type = 'info'): string {
    $cls = $type === 'success' ? 'success' : ($type === 'error' ? 'error' : 'info');
    return _shell(<<<HTML
    <div class="card-head">
      <h1>RSVP Confirmed</h1>
      <p>Your response has been recorded</p>
    </div>
    <div class="card-body" style="text-align:center;padding:32px 28px">
      <div class="result-icon">{$heading[0]}</div>
      <div class="result-head {$cls}">{$heading}</div>
      <div style="font-size:14px;color:#6b7280;line-height:1.6;margin-top:8px">{$body}</div>
    </div>
HTML);
}