<?php
require_once __DIR__ . '/../config/database.php';

requireLogin();
$user = getCurrentUser();

if (!$user || !isset($_SESSION['role']) || $_SESSION['role'] !== 'student') {
    setFlashMessage('error', 'Only students can view appointments.');
    header('Location: ' . APP_URL . '/lms/dashboard.php');
    exit;
}

$db = Database::getInstance();

$appointments = $db->getAll(
    'SELECT * FROM appointments WHERE user_id = ? ORDER BY created_at DESC',
    [$user['id']]
);

$pageTitle = 'My Appointments';
include __DIR__ . '/includes/header.php';
?>

<div class="container-xxl flex-grow-1 container-p-y">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <div>
                    <h4 class="mb-1">My Appointments</h4>
                    <p class="text-muted mb-0">View your scheduled and requested appointments with SmartThink.</p>
                </div>
                <div>
                    <a href="<?php echo APP_URL; ?>/website/appointment.php" class="btn btn-primary" target="_blank">
                        <i class="ri ri-calendar-check-line me-1"></i>
                        Book New Appointment
                    </a>
                </div>
            </div>

            <div class="card">
                <div class="card-body">
                    <?php if (empty($appointments)): ?>
                        <p class="text-muted mb-0">You have not booked any appointments yet.</p>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-striped align-middle mb-0">
                                <thead>
                                    <tr>
                                        <th>Topic</th>
                                        <th>Requested For</th>
                                        <th>Status</th>
                                        <th>Zoom</th>
                                        <th>Created</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($appointments as $appt): ?>
                                        <?php
                                            $preferred = $appt['preferred_datetime'] ? date('Y-m-d H:i', strtotime($appt['preferred_datetime'])) : 'Not specified';
                                            $created = $appt['created_at'] ? date('Y-m-d H:i', strtotime($appt['created_at'])) : '';

                                            $status = $appt['status'] ?? 'requested';
                                            $statusLabel = ucfirst($status);
                                            $badgeClass = 'bg-secondary';
                                            if ($status === 'requested') {
                                                $badgeClass = 'bg-warning text-dark';
                                            } elseif ($status === 'scheduled') {
                                                $badgeClass = 'bg-success';
                                            } elseif ($status === 'cancelled') {
                                                $badgeClass = 'bg-danger';
                                            }

                                            $zoomUrl = $appt['zoom_join_url'] ?? null;
                                            $zoomStart = $appt['zoom_start_time'] ? strtotime($appt['zoom_start_time']) : null;
                                            $now = time();
                                            $canJoin = $zoomUrl && $zoomStart && ($now >= $zoomStart - 1800); // allow join 30 min before
                                        ?>
                                        <tr>
                                            <td>
                                                <div class="fw-semibold mb-0"><?php echo htmlspecialchars($appt['topic'] ?? 'Appointment'); ?></div>
                                                <?php if (!empty($appt['details'])): ?>
                                                    <div class="text-muted small text-truncate" style="max-width: 320px;">
                                                        <?php echo htmlspecialchars($appt['details']); ?>
                                                    </div>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <div><?php echo htmlspecialchars($preferred); ?></div>
                                                <?php if (!empty($appt['timezone'])): ?>
                                                    <div class="text-muted small"><?php echo htmlspecialchars($appt['timezone']); ?></div>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <span class="badge <?php echo $badgeClass; ?>"><?php echo htmlspecialchars($statusLabel); ?></span>
                                            </td>
                                            <td>
                                                <?php if ($zoomUrl && $status === 'scheduled'): ?>
                                                    <?php if ($canJoin): ?>
                                                        <a href="<?php echo htmlspecialchars($zoomUrl); ?>" target="_blank" class="btn btn-sm btn-primary mb-1">Join Zoom</a>
                                                    <?php else: ?>
                                                        <span class="text-muted small">Zoom scheduled</span>
                                                    <?php endif; ?>
                                                <?php else: ?>
                                                    <span class="text-muted small">Not scheduled</span>
                                                <?php endif; ?>
                                            </td>
                                            <td><?php echo htmlspecialchars($created); ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include __DIR__ . '/includes/footer.php'; ?>
