<?php
// ============================================================
// Elegant Work — Organiser Reschedule Action (email deep-link)
// GET /api/meetings/organiser_action.php
//     ?meeting_id=X&attendee_id=X&action=accept_reschedule|keep_original&note=...
// Also accepts POST from the app (JSON response for API calls)
// ============================================================
require_once __DIR__ . '/../config/db.php';

$db         = getDB();
$meetingId  = (int)($_GET['meeting_id']  ?? $_POST['meeting_id']  ?? 0);
$attendeeId = (int)($_GET['attendee_id'] ?? $_POST['attendee_id'] ?? 0);
$action     = trim($_GET['action'] ?? $_POST['action'] ?? '');
$note       = trim($_GET['note']   ?? $_POST['note']   ?? '');
$isApi      = ($_SERVER['REQUEST_METHOD'] === 'POST') ||
              !empty($_SERVER['HTTP_X_REQUESTED_WITH']);

if (!$meetingId || !$attendeeId || !in_array($action, ['accept_reschedule','keep_original'])) {
    if ($isApi) { header('Content-Type: application/json'); echo json_encode(['success'=>false,'message'=>'Invalid request.']); }
    else echo _html('Invalid Request', '<p>This link is invalid or has expired.</p>', 'error');
    exit;
}

// Fetch meeting + attendee
$mStmt = $db->prepare("SELECT * FROM meetings WHERE id=? LIMIT 1");
$mStmt->execute([$meetingId]);
$m = $mStmt->fetch();

$aStmt = $db->prepare("SELECT * FROM meeting_attendees WHERE id=? AND meeting_id=? LIMIT 1");
$aStmt->execute([$attendeeId, $meetingId]);
$att = $aStmt->fetch();

if (!$m || !$att) {
    if ($isApi) { header('Content-Type: application/json'); echo json_encode(['success'=>false,'message'=>'Not found.']); }
    else echo _html('Not Found', '<p>Meeting or attendee not found.</p>', 'error');
    exit;
}

// Parse proposed changes from note (format: "date:YYYY-MM-DD|time:HH:MM|place:text")
$proposed = [];
foreach (explode('|', $note ?: ($att['rsvp_note'] ?? '')) as $part) {
    if (str_starts_with($part, 'date:'))  $proposed['date']  = trim(substr($part, 5));
    if (str_starts_with($part, 'time:'))  $proposed['time']  = trim(substr($part, 5));
    if (str_starts_with($part, 'place:')) $proposed['place'] = trim(substr($part, 6));
}

$attName = htmlspecialchars($att['name'] ?: $att['email'] ?: 'Attendee');

if ($action === 'accept_reschedule') {
    // Update meeting date/time/location
    $updates = [];
    $params  = [];
    if (!empty($proposed['date']))  { $updates[] = 'meeting_date=?'; $params[] = $proposed['date']; }
    if (!empty($proposed['time']))  { $updates[] = 'start_time=?';   $params[] = $proposed['time']; }
    if (!empty($proposed['place'])) { $updates[] = 'location=?';     $params[] = $proposed['place']; }

    if ($updates) {
        $params[] = $meetingId;
        $db->prepare("UPDATE meetings SET " . implode(',', $updates) . " WHERE id=?")->execute($params);
    }

    // Mark this attendee as accepted (they proposed it, so they're in)
    $db->prepare("UPDATE meeting_attendees SET rsvp_status='accepted', rsvp_note=? WHERE id=?")
       ->execute(["Reschedule accepted by organiser", $attendeeId]);

    // Reset all OTHER attendees to pending so they get re-invited
    $db->prepare("UPDATE meeting_attendees SET rsvp_status='pending', invite_sent=0 WHERE meeting_id=? AND id!=?")
       ->execute([$meetingId, $attendeeId]);

    // Queue re-invite emails to all other attendees
    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') {
            $appUrl      = $cfg['email_app_url'] ?? '';
            $compName    = $db->query("SELECT setting_value FROM settings WHERE setting_key='company_name' LIMIT 1")->fetchColumn() ?: 'Elegant Work';
            $newDate     = !empty($proposed['date']) ? date('D, d M Y', strtotime($proposed['date'])) : date('D, d M Y', strtotime($m['meeting_date']));
            $newTime     = !empty($proposed['time']) ? date('H:i', strtotime($proposed['time'])) : ($m['start_time'] ? date('H:i', strtotime($m['start_time'])) : 'TBC');
            $newPlace    = !empty($proposed['place']) ? htmlspecialchars($proposed['place']) : htmlspecialchars($m['location'] ?? '');
            $newPlaceRow = $newPlace ? "<tr><td style='padding:4px 12px 4px 0;color:#6b7280;font-size:12px;text-transform:uppercase'>Location</td><td style='padding:4px 0;font-weight:600;font-size:14px'>{$newPlace}</td></tr>" : '';

            $others = $db->prepare("SELECT * FROM meeting_attendees WHERE meeting_id=? AND id!=? AND email IS NOT NULL AND email!=''");
            $others->execute([$meetingId, $attendeeId]);
            foreach ($others->fetchAll() as $oa) {
                $rsvpUrl = $appUrl . "api/meetings/rsvp.php?token=" . urlencode($oa['rsvp_token']);
                $subject = "📅 Meeting Rescheduled: " . $m['title'];
                $name    = htmlspecialchars($oa['name'] ?: $oa['email']);
                $html = <<<MAIL
<!DOCTYPE html><html><body style="font-family:sans-serif;background:#f4f6f9;padding:32px">
<div style="max-width:520px;margin:0 auto;background:#fff;border-radius:10px;overflow:hidden">
  <div style="background:#1b4b8a;padding:24px 28px;color:#fff">
    <h2 style="margin:0;font-size:18px">📅 Meeting Rescheduled</h2>
    <p style="margin:4px 0 0;opacity:.75;font-size:13px">The date has been updated</p>
  </div>
  <div style="padding:28px">
    <p style="color:#374151;font-size:14px">Hi <strong>{$name}</strong>,</p>
    <p style="color:#6b7280;font-size:14px;margin-bottom:20px"><strong>{$m['title']}</strong> has been rescheduled.</p>
    <div style="background:#f0f4ff;border:1.5px solid #c7d7f8;border-radius:8px;padding:16px;margin-bottom:20px">
      <table cellpadding="0" cellspacing="0">
        <tr><td style="padding:4px 12px 4px 0;color:#6b7280;font-size:12px;text-transform:uppercase">Date</td><td style="padding:4px 0;font-weight:600;font-size:14px">{$newDate}</td></tr>
        <tr><td style="padding:4px 12px 4px 0;color:#6b7280;font-size:12px;text-transform:uppercase">Time</td><td style="padding:4px 0;font-weight:600;font-size:14px">{$newTime}</td></tr>
        {$newPlaceRow}
      </table>
    </div>
    <a href="{$rsvpUrl}" style="display:inline-block;background:#1b4b8a;color:#fff;padding:12px 24px;border-radius:8px;text-decoration:none;font-weight:600;font-size:14px">✅ Confirm Attendance</a>
  </div>
  <div style="padding:12px 28px 20px;font-size:11px;color:#9ca3af;text-align:center">{$compName} · Meeting System</div>
</div>
</body></html>
MAIL;
                $db->prepare("INSERT INTO email_queue (notification_type, recipient_email, recipient_name, subject, body_html, related_type, related_id) VALUES ('meeting_invite',?,?,?,?,'meeting',?)")
                   ->execute([$oa['email'], $oa['name'], $subject, $html, $meetingId]);
                $db->prepare("UPDATE meeting_attendees SET invite_sent=1, invite_sent_at=NOW() WHERE id=?")->execute([$oa['id']]);
            }
        }
    } catch (Exception $e) { /* silent */ }

    $newDateLabel = !empty($proposed['date']) ? date('D, d M Y', strtotime($proposed['date'])) : 'the proposed date';
    $msg = "Meeting rescheduled to <strong>{$newDateLabel}</strong>. All other attendees have been notified and asked to re-confirm.";
    if ($isApi) { header('Content-Type: application/json'); echo json_encode(['success'=>true,'message'=>'Reschedule accepted.']); }
    else echo _html('✅ Reschedule Accepted', "<p style='color:#374151;line-height:1.6'>{$msg}</p>", 'success');

} else { // keep_original
    // Mark this attendee as declined (they can't make the original date)
    $db->prepare("UPDATE meeting_attendees SET rsvp_status='declined', rsvp_note='Could not accommodate reschedule request — original date kept.' WHERE id=?")
       ->execute([$attendeeId]);

    // Optionally notify the attendee their reschedule was not accepted
    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($att['email'])) {
            $origDate    = date('D, d M Y', strtotime($m['meeting_date']));
            $origTime    = $m['start_time'] ? date('H:i', strtotime($m['start_time'])) : '';
            $origTimeStr = $origTime ? " at <strong>{$origTime}</strong>" : '';
            $name     = htmlspecialchars($att['name'] ?: $att['email']);
            $subject  = "📅 Regarding your reschedule request: " . $m['title'];
            $html = <<<MAIL
<!DOCTYPE html><html><body style="font-family:sans-serif;background:#f4f6f9;padding:32px">
<div style="max-width:480px;margin:0 auto;background:#fff;border-radius:10px;overflow:hidden">
  <div style="background:#1b4b8a;padding:24px 28px;color:#fff">
    <h2 style="margin:0;font-size:18px">📅 Reschedule Update</h2>
  </div>
  <div style="padding:28px">
    <p style="color:#374151;font-size:14px">Hi <strong>{$name}</strong>,</p>
    <p style="color:#6b7280;font-size:14px;line-height:1.6">We weren't able to accommodate your reschedule request for <strong>{$m['title']}</strong>. The meeting will proceed on the original date: <strong>{$origDate}</strong>{$origTimeStr}.</p>
    <p style="color:#6b7280;font-size:13px;margin-top:16px">We're sorry you won't be able to join us. The organiser has been notified.</p>
  </div>
</div>
</body></html>
MAIL;
            $db->prepare("INSERT INTO email_queue (notification_type, recipient_email, recipient_name, subject, body_html, related_type, related_id) VALUES ('meeting_rsvp',?,?,?,?,'meeting',?)")
               ->execute([$att['email'], $att['name'], $subject, $html, $meetingId]);
        }
    } catch (Exception $e) { /* silent */ }

    if ($isApi) { header('Content-Type: application/json'); echo json_encode(['success'=>true,'message'=>'Original date kept.']); }
    else echo _html('📅 Original Date Kept', "<p style='color:#374151;line-height:1.6'>{$attName} has been notified that the original meeting date will be kept. They have been marked as declined.</p>", 'info');
}

function _html(string $heading, string $body, string $type = 'info'): string {
    $color = ['success'=>'#16a34a','error'=>'#dc2626','info'=>'#0284c7'][$type] ?? '#1b4b8a';
    return <<<HTML
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Meeting Action</title>
<style>*{margin:0;padding:0;box-sizing:border-box}body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;background:#f4f6f9;min-height:100vh;display:flex;align-items:center;justify-content:center;padding:20px}
.card{background:#fff;border-radius:12px;box-shadow:0 4px 24px rgba(0,0,0,.1);padding:40px;max-width:480px;width:100%;text-align:center}
h2{color:{$color};font-size:22px;margin-bottom:12px}.brand{margin-top:28px;font-size:11px;color:#9ca3af}</style></head>
<body><div class="card"><h2>{$heading}</h2><div style="font-size:14px;color:#374151;line-height:1.6">{$body}</div>
<div class="brand">Powered by Elegant Work</div></div></body></html>
HTML;
}