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

requireLogin();
requireAnyRole(['admin', 'super_admin']);

$db = Database::getInstance();

$currentPage = basename($_SERVER['PHP_SELF']);
$user = getCurrentUser();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'schedule_zoom') {
        $appointmentId = (int)($_POST['appointment_id'] ?? 0);
        $startRaw = trim($_POST['start_time'] ?? '');
        $duration = (int)($_POST['duration'] ?? 30);

        if ($appointmentId <= 0 || $startRaw === '' || $duration <= 0) {
            setFlashMessage('error', 'Appointment, start time and duration are required to schedule Zoom.');
            header('Location: ' . APP_URL . '/cms/appointments.php');
            exit;
        }

        $appointment = $db->get('SELECT * FROM appointments WHERE id = ?', [$appointmentId]);
        if (!$appointment) {
            setFlashMessage('error', 'Appointment not found.');
            header('Location: ' . APP_URL . '/cms/appointments.php');
            exit;
        }

        if (!function_exists('zoom_create_meeting') || !zoom_is_configured()) {
            setFlashMessage('error', 'Zoom integration is not configured.');
            header('Location: ' . APP_URL . '/cms/appointments.php');
            exit;
        }

        try {
            $startDt = new DateTime($startRaw);
        } catch (Exception $e) {
            setFlashMessage('error', 'Invalid start time format.');
            header('Location: ' . APP_URL . '/cms/appointments.php');
            exit;
        }

        $startIso = $startDt->format(DATE_ATOM);
        $topic = 'Appointment: ' . ($appointment['topic'] ?? 'SmartThink Session');

        $meeting = zoom_create_meeting($topic, $startIso, $duration, 'me', []);
        if (!$meeting) {
            setFlashMessage('error', 'Failed to create Zoom meeting for this appointment.');
            header('Location: ' . APP_URL . '/cms/appointments.php');
            exit;
        }

        $zoomStart = isset($meeting['start_time']) ? date('Y-m-d H:i:s', strtotime($meeting['start_time'])) : $startDt->format('Y-m-d H:i:s');
        $zoomJoinUrl = $meeting['join_url'] ?? null;

        $db->update('appointments', [
            'status' => 'scheduled',
            'zoom_meeting_id' => (string)($meeting['id'] ?? ''),
            'zoom_join_url' => $zoomJoinUrl,
            'zoom_start_time' => $zoomStart,
        ], 'id = ?', [$appointmentId]);

        if (function_exists('sendAppointmentScheduledNotification')) {
            sendAppointmentScheduledNotification($appointmentId);
        }

        setFlashMessage('success', 'Zoom meeting created and appointment scheduled successfully.');
        header('Location: ' . APP_URL . '/cms/appointments.php');
        exit;
    }
}

$status = isset($_GET['status']) ? trim($_GET['status']) : '';
$q = isset($_GET['q']) ? trim($_GET['q']) : '';

$where = [];
$params = [];

if ($status !== '') {
    $where[] = 'a.status = ?';
    $params[] = $status;
}
if ($q !== '') {
    $where[] = '(a.name LIKE ? OR a.email LIKE ? OR a.topic LIKE ?)';
    $params[] = "%$q%";
    $params[] = "%$q%";
    $params[] = "%$q%";
}

$whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

$appointments = $db->getAll(
    "SELECT a.*, u.first_name, u.last_name
     FROM appointments a
     LEFT JOIN users u ON a.user_id = u.id
     $whereSql
     ORDER BY a.created_at DESC
     LIMIT 200",
    $params
);

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

<div class="container-xxl flex-grow-1 container-p-y">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h1 class="h4 mb-0">Appointments</h1>
            <p class="text-muted mb-0">Manage incoming appointment requests and schedule Zoom meetings.</p>
        </div>
    </div>

    <div class="card mb-4">
        <div class="card-header">
            <form method="get" class="row g-3 align-items-end">
                <div class="col-sm-3">
                    <label class="form-label">Status</label>
                    <select name="status" class="form-select">
                        <option value="">All</option>
                        <?php foreach (['requested','accepted','scheduled','cancelled','completed'] as $opt): ?>
                            <option value="<?php echo $opt; ?>" <?php echo $status === $opt ? 'selected' : ''; ?>><?php echo ucfirst($opt); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-sm-5">
                    <label class="form-label">Search</label>
                    <input type="text" name="q" class="form-control" placeholder="name, email or topic" value="<?php echo htmlspecialchars($q); ?>">
                </div>
                <div class="col-sm-2">
                    <button type="submit" class="btn btn-primary w-100">Filter</button>
                </div>
                <div class="col-sm-2">
                    <a href="appointments.php" class="btn btn-outline-secondary w-100">Reset</a>
                </div>
            </form>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-striped table-hover mb-0 align-middle">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Requester</th>
                            <th>Contact</th>
                            <th>Topic</th>
                            <th>Preferred</th>
                            <th>Status</th>
                            <th>Zoom</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($appointments)): ?>
                            <tr>
                                <td colspan="8" class="text-center text-muted py-4">No appointments found.</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($appointments as $appt): ?>
                                <?php
                                    $preferred = $appt['preferred_datetime'] ? date('Y-m-d H:i', strtotime($appt['preferred_datetime'])) : 'Not specified';
                                    $statusVal = $appt['status'] ?? 'requested';
                                    $statusLabel = ucfirst($statusVal);
                                    $badgeClass = 'bg-secondary';
                                    if ($statusVal === 'requested') {
                                        $badgeClass = 'bg-warning text-dark';
                                    } elseif ($statusVal === 'scheduled') {
                                        $badgeClass = 'bg-success';
                                    } elseif ($statusVal === 'cancelled') {
                                        $badgeClass = 'bg-danger';
                                    }

                                    $zoomUrl = $appt['zoom_join_url'] ?? null;
                                    $zoomStart = $appt['zoom_start_time'] ? date('Y-m-d H:i', strtotime($appt['zoom_start_time'])) : null;

                                    $defaultStartValue = '';
                                    if (!empty($appt['preferred_datetime'])) {
                                        $defaultStartValue = date('Y-m-d\TH:i', strtotime($appt['preferred_datetime']));
                                    }
                                ?>
                                <tr>
                                    <td>#<?php echo (int)$appt['id']; ?></td>
                                    <td>
                                        <div class="fw-semibold mb-0"><?php echo htmlspecialchars($appt['name']); ?></div>
                                        <?php if (!empty($appt['first_name']) || !empty($appt['last_name'])): ?>
                                            <div class="text-muted small">User: <?php echo htmlspecialchars(trim(($appt['first_name'] ?? '') . ' ' . ($appt['last_name'] ?? ''))); ?></div>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <div><?php echo htmlspecialchars($appt['email']); ?></div>
                                        <?php if (!empty($appt['phone'])): ?>
                                            <div class="text-muted small"><?php echo htmlspecialchars($appt['phone']); ?></div>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <div class="fw-semibold mb-0"><?php echo htmlspecialchars($appt['topic']); ?></div>
                                        <?php if (!empty($appt['details'])): ?>
                                            <div class="text-muted small text-truncate" style="max-width: 260px;">
                                                <?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): ?>
                                            <div><a href="<?php echo htmlspecialchars($zoomUrl); ?>" target="_blank" class="small">Join link</a></div>
                                            <?php if ($zoomStart): ?>
                                                <div class="text-muted small"><?php echo htmlspecialchars($zoomStart); ?></div>
                                            <?php endif; ?>
                                        <?php else: ?>
                                            <span class="text-muted small">Not scheduled</span>
                                        <?php endif; ?>
                                    </td>
                                    <td style="min-width: 260px;">
                                        <?php if (in_array($statusVal, ['requested','accepted','cancelled'], true) || !$zoomUrl): ?>
                                            <form method="post" class="row g-2">
                                                <input type="hidden" name="action" value="schedule_zoom">
                                                <input type="hidden" name="appointment_id" value="<?php echo (int)$appt['id']; ?>">
                                                <div class="col-7">
                                                    <input type="datetime-local" name="start_time" class="form-control form-control-sm" value="<?php echo htmlspecialchars($defaultStartValue); ?>" required>
                                                </div>
                                                <div class="col-3">
                                                    <input type="number" name="duration" class="form-control form-control-sm" value="30" min="15" step="5" required>
                                                </div>
                                                <div class="col-12 mt-1">
                                                    <button type="submit" class="btn btn-sm btn-primary w-100">
                                                        <i class="ri ri-video-chat-line me-1"></i>Schedule Zoom
                                                    </button>
                                                </div>
                                            </form>
                                        <?php else: ?>
                                            <span class="text-muted small">Zoom scheduled</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

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