<?php
declare(strict_types=1);
require_once __DIR__ . '/../lib.php';

hw_require_method(['GET']);
$user = hw_auth_user();
if (!$user) hw_json(['success' => false, 'message' => 'Unauthorized'], 401);

$appointmentId = (int)($_GET['appointment_id'] ?? 0);
if ($appointmentId <= 0) hw_json(['success' => false, 'message' => 'appointment_id is required'], 422);

try {
    $pdo = hw_db();
    
    // Get appointment details
    $stmt = $pdo->prepare("
        SELECT a.*, c.display_name as coach_name, u.first_name, u.last_name
        FROM appointments a 
        JOIN coaches c ON a.coach_id = c.id 
        JOIN users u ON c.user_id = u.id 
        WHERE a.id = ? AND a.user_id = ?
    ");
    $stmt->execute([$appointmentId, (int)$user['sub']]);
    $appointment = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$appointment) {
        hw_json(['success' => false, 'message' => 'Appointment not found'], 404);
    }
    
    // Generate iCal content
    $startTime = new DateTime($appointment['starts_at']);
    $endTime = new DateTime($appointment['ends_at']);
    
    $ical = "BEGIN:VCALENDAR\r\n";
    $ical .= "VERSION:2.0\r\n";
    $ical .= "PRODID:-//Herbal Wellness Care//Appointment//EN\r\n";
    $ical .= "BEGIN:VEVENT\r\n";
    $ical .= "UID:" . $appointmentId . "@atasteofafricanmarketplace.local\r\n";
    $ical .= "DTSTAMP:" . gmdate('Ymd\THis\Z') . "\r\n";
    $ical .= "DTSTART:" . $startTime->format('Ymd\THis\Z') . "\r\n";
    $ical .= "DTEND:" . $endTime->format('Ymd\THis\Z') . "\r\n";
    $ical .= "SUMMARY:Wellness Session with " . $appointment['coach_name'] . "\r\n";
    $ical .= "DESCRIPTION:Wellness consultation session\\nCoach: " . $appointment['coach_name'] . "\\nNotes: " . ($appointment['notes'] ?: 'No notes') . "\r\n";
    $ical .= "LOCATION:Virtual Session\r\n";
    $ical .= "STATUS:CONFIRMED\r\n";
    $ical .= "BEGIN:VALARM\r\n";
    $ical .= "TRIGGER:-PT15M\r\n";
    $ical .= "ACTION:DISPLAY\r\n";
    $ical .= "DESCRIPTION:Wellness session reminder\r\n";
    $ical .= "END:VALARM\r\n";
    $ical .= "END:VEVENT\r\n";
    $ical .= "END:VCALENDAR\r\n";
    
    // Set headers for calendar download
    header('Content-Type: text/calendar; charset=utf-8');
    header('Content-Disposition: attachment; filename="appointment-' . $appointmentId . '.ics"');
    header('Content-Length: ' . strlen($ical));
    
    echo $ical;
    exit;
} catch (Throwable $e) {
    hw_json(['success' => false, 'message' => 'Server error', 'error' => $e->getMessage()], 500);
}