<?php
session_start();
include 'layouts/dbconn.php';
include 'layouts/session.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$user_id = $_SESSION['user_id'];
$role_code = $_SESSION['role_code'];

// Fetch video conferencing settings
function getVideoSettings($conn) {
    $sql = "SELECT setting_key, setting_value FROM system_settings WHERE category = 'video_conferencing'";
    $result = $conn->query($sql);
    
    $settings = [];
    while ($row = $result->fetch_assoc()) {
        $settings[$row['setting_key']] = $row['setting_value'];
    }
    return $settings;
}

$video_settings = getVideoSettings($conn);
$video_enabled = ($video_settings['video_enabled'] ?? '0') == '1';
$video_provider = $video_settings['video_provider'] ?? 'jitsi';

// Fetch filters
$status_filter = isset($_GET['status']) ? $_GET['status'] : 'all';
$date_filter = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');
$search = isset($_GET['search']) ? trim($_GET['search']) : '';

// Pagination
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$records_per_page = 15;
$offset = ($page - 1) * $records_per_page;

// Build query
$where_conditions = ["a.appointment_type = 'TELEMEDICINE'"];
$params = [];
$types = "";

// Role-based filtering
if ($role_code === 'ENT_CONSULTANT' || $role_code === 'ENT_DOCTOR') {
    $where_conditions[] = "a.doctor_id = ?";
    $params[] = $user_id;
    $types .= "i";
}

// Status filter
if ($status_filter !== 'all') {
    $where_conditions[] = "a.status = ?";
    $params[] = $status_filter;
    $types .= "s";
}

// Date filter
if (!empty($date_filter)) {
    $where_conditions[] = "DATE(a.appointment_date) = ?";
    $params[] = $date_filter;
    $types .= "s";
}

// Search filter
if (!empty($search)) {
    $where_conditions[] = "(p.patient_number LIKE ? OR pu.full_name LIKE ? OR a.appointment_number LIKE ?)";
    $search_param = "%$search%";
    $params = array_merge($params, [$search_param, $search_param, $search_param]);
    $types .= "sss";
}

$where_clause = implode(" AND ", $where_conditions);

// Count total records
$count_sql = "SELECT COUNT(*) as total 
              FROM appointments a
              INNER JOIN patients p ON a.patient_id = p.patient_id
              INNER JOIN users pu ON p.user_id = pu.user_id
              WHERE $where_clause";

$count_stmt = $conn->prepare($count_sql);
if (!empty($params)) {
    $count_stmt->bind_param($types, ...$params);
}
$count_stmt->execute();
$total_records = $count_stmt->get_result()->fetch_assoc()['total'];
$total_pages = ceil($total_records / $records_per_page);

// Fetch telemedicine appointments
$sql = "SELECT 
            a.*,
            p.patient_number,
            pu.full_name as patient_name,
            pu.phone_primary as patient_phone,
            pu.email as patient_email,
            pu.date_of_birth,
            TIMESTAMPDIFF(YEAR, pu.date_of_birth, CURDATE()) as patient_age,
            d.full_name as doctor_name,
            doc.specialization,
            doc.consultation_fee
        FROM appointments a
        INNER JOIN patients p ON a.patient_id = p.patient_id
        INNER JOIN users pu ON p.user_id = pu.user_id
        INNER JOIN users d ON a.doctor_id = d.user_id
        LEFT JOIN doctors doc ON d.user_id = doc.user_id
        WHERE $where_clause
        ORDER BY a.appointment_date DESC, a.appointment_time DESC
        LIMIT ? OFFSET ?";

$stmt = $conn->prepare($sql);
$params[] = $records_per_page;
$params[] = $offset;
$types .= "ii";
$stmt->bind_param($types, ...$params);
$stmt->execute();
$appointments = $stmt->get_result();

// Get statistics
$stats_sql = "SELECT 
                COUNT(*) as total_appointments,
                SUM(CASE WHEN status = 'SCHEDULED' THEN 1 ELSE 0 END) as scheduled,
                SUM(CASE WHEN status = 'CONFIRMED' THEN 1 ELSE 0 END) as confirmed,
                SUM(CASE WHEN status = 'IN_PROGRESS' THEN 1 ELSE 0 END) as in_progress,
                SUM(CASE WHEN status = 'COMPLETED' THEN 1 ELSE 0 END) as completed,
                SUM(CASE WHEN DATE(appointment_date) = CURDATE() THEN 1 ELSE 0 END) as today,
                SUM(CASE WHEN status = 'CANCELLED' THEN 1 ELSE 0 END) as cancelled
              FROM appointments a
              WHERE appointment_type = 'TELEMEDICINE' 
              " . (($role_code === 'ENT_CONSULTANT' || $role_code === 'ENT_DOCTOR') ? "AND a.doctor_id = $user_id" : "");
$stats_result = $conn->query($stats_sql);
$stats = $stats_result->fetch_assoc();

// Handle status updates
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_status'])) {
    $appointment_id = (int)$_POST['appointment_id'];
    $new_status = $_POST['new_status'];
    
    $conn->begin_transaction();
    try {
        $update_sql = "UPDATE appointments SET status = ?, updated_at = NOW() WHERE appointment_id = ?";
        $update_stmt = $conn->prepare($update_sql);
        $update_stmt->bind_param('si', $new_status, $appointment_id);
        $update_stmt->execute();
        
        // Log activity
        $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, ip_address, logged_at)
                   VALUES (?, 'UPDATE', 'TELEMEDICINE', ?, 'APPOINTMENT', ?, NOW())";
        $log_stmt = $conn->prepare($log_sql);
        $ip_address = $_SERVER['REMOTE_ADDR'];
        $log_stmt->bind_param('iis', $user_id, $appointment_id, $ip_address);
        $log_stmt->execute();
        
        $conn->commit();
        $_SESSION['success_message'] = 'Appointment status updated successfully';
    } catch (Exception $e) {
        $conn->rollback();
        $_SESSION['error_message'] = 'Failed to update appointment status';
    }
    
    header('Location: telemedicine.php');
    exit();
}
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Telemedicine')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <?php if ($video_enabled && $video_provider === 'jitsi'): ?>
    <!-- Jitsi Meet External API -->
    <script src='<?php echo htmlspecialchars($video_settings['jitsi_server_url'] ?? 'https://meet.jit.si'); ?>/external_api.js'></script>
    <?php endif; ?>
    
    <style>
    :root {
        --primary-color: #3b82f6;
        --primary-dark: #2563eb;
        --success-color: #10b981;
        --danger-color: #ef4444;
        --warning-color: #f59e0b;
        --info-color: #06b6d4;
        --purple-color: #8b5cf6;
        --gray-50: #f9fafb;
        --gray-100: #f3f4f6;
        --gray-200: #e5e7eb;
        --gray-600: #4b5563;
        --gray-700: #374151;
        --gray-900: #111827;
    }
    body {
        background: var(--gray-50);
        font-family: 'Inter', system-ui, sans-serif;
    }
    .main-content,
    .page-content {
        padding-top: 0.5rem !important;
        margin-top: 0 !important;
    }
    .page-header {
        background: linear-gradient(135deg, #06b6d4, #0891b2);
        border-radius: 16px;
        padding: 2rem;
        margin: 0 0 1rem 0;
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    }
    .page-header h1 {
        color: white;
        font-size: 1.875rem;
        font-weight: 700;
        margin: 0 0 0.5rem 0;
        display: flex;
        align-items: center;
        gap: 0.75rem;
    }
    .page-header p {
        color: rgba(255, 255, 255, 0.9);
        margin: 0;
    }
    .integration-notice {
        background: linear-gradient(135deg, #fef3c7, #fde68a);
        border-left: 4px solid #f59e0b;
        border-radius: 12px;
        padding: 1.5rem;
        margin-bottom: 1rem;
    }
    .integration-notice.success {
        background: linear-gradient(135deg, #d1fae5, #a7f3d0);
        border-left-color: #10b981;
    }
    .integration-notice h6 {
        color: #92400e;
        font-weight: 700;
        margin-bottom: 1rem;
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }
    .integration-notice.success h6 {
        color: #065f46;
    }
    .provider-badge {
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
        background: white;
        padding: 0.5rem 1rem;
        border-radius: 8px;
        font-weight: 600;
        margin-top: 0.5rem;
    }
    .stats-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 1rem;
        margin-bottom: 1rem;
    }
    .stat-card {
        background: white;
        border-radius: 12px;
        padding: 1.5rem;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        border: 1px solid var(--gray-200);
        transition: all 0.3s ease;
    }
    .stat-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    }
    .stat-icon {
        width: 48px;
        height: 48px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.5rem;
        margin-bottom: 1rem;
    }
    .stat-value {
        font-size: 1.875rem;
        font-weight: 700;
        color: var(--gray-900);
        margin-bottom: 0.25rem;
    }
    .stat-label {
        font-size: 0.875rem;
        color: var(--gray-600);
        font-weight: 500;
    }
    .filters-section {
        background: white;
        border-radius: 12px;
        padding: 1.5rem;
        margin-bottom: 1rem;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        border: 1px solid var(--gray-200);
    }
    .filter-tabs {
        display: flex;
        gap: 1rem;
        margin-bottom: 1rem;
        border-bottom: 2px solid var(--gray-200);
        flex-wrap: wrap;
    }
    .filter-tab {
        padding: 0.75rem 1.5rem;
        border: none;
        background: none;
        color: var(--gray-600);
        font-weight: 600;
        cursor: pointer;
        border-bottom: 2px solid transparent;
        margin-bottom: -2px;
        transition: all 0.2s ease;
    }
    .filter-tab:hover {
        color: var(--info-color);
    }
    .filter-tab.active {
        color: var(--info-color);
        border-bottom-color: var(--info-color);
    }
    .table-container {
        background: white;
        border-radius: 12px;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        border: 1px solid var(--gray-200);
        overflow: hidden;
    }
    .table {
        margin: 0;
    }
    .table thead {
        background: var(--gray-50);
    }
    .table thead th {
        font-weight: 600;
        color: var(--gray-700);
        border-bottom: 2px solid var(--gray-200);
        padding: 1rem;
        font-size: 0.875rem;
        text-transform: uppercase;
        letter-spacing: 0.05em;
    }
    .table tbody td {
        padding: 1rem;
        vertical-align: middle;
        color: var(--gray-700);
    }
    .table tbody tr {
        border-bottom: 1px solid var(--gray-200);
        transition: background 0.2s ease;
    }
    .table tbody tr:hover {
        background: var(--gray-50);
    }
    .badge {
        padding: 0.375rem 0.75rem;
        border-radius: 6px;
        font-weight: 600;
        font-size: 0.75rem;
        text-transform: uppercase;
        letter-spacing: 0.025em;
    }
    .badge-primary { background: #dbeafe; color: #1e40af; }
    .badge-success { background: #d1fae5; color: #065f46; }
    .badge-warning { background: #fef3c7; color: #92400e; }
    .badge-danger { background: #fee2e2; color: #991b1b; }
    .badge-info { background: #cffafe; color: #164e63; }
    .badge-purple { background: #e9d5ff; color: #6b21a8; }
    .patient-info {
        display: flex;
        flex-direction: column;
        gap: 0.25rem;
    }
    .patient-name {
        font-weight: 600;
        color: var(--gray-900);
    }
    .patient-details {
        font-size: 0.8125rem;
        color: var(--gray-600);
    }
    .video-btn {
        background: linear-gradient(135deg, #06b6d4, #0891b2);
        color: white;
        border: none;
        padding: 0.5rem 1rem;
        border-radius: 8px;
        font-weight: 600;
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
        cursor: pointer;
        transition: all 0.2s ease;
    }
    .video-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 6px rgba(6, 182, 212, 0.3);
    }
    .video-btn:disabled {
        opacity: 0.6;
        cursor: not-allowed;
        transform: none;
    }
    .video-btn i {
        font-size: 1.125rem;
    }
    .time-indicator {
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }
    .time-indicator.upcoming {
        color: var(--warning-color);
    }
    .time-indicator.now {
        color: var(--success-color);
        font-weight: 700;
    }
    #jitsiContainer {
        width: 100%;
        height: 100%;
        min-height: 500px;
    }
    @media (max-width: 768px) {
        .stats-grid {
            grid-template-columns: 1fr;
        }
        .filter-tabs {
            overflow-x: auto;
        }
        .table-container {
            overflow-x: auto;
        }
        .page-header {
            padding: 1.5rem;
            margin-bottom: 0.5rem;
        }
        .integration-notice {
            padding: 1rem;
            margin-bottom: 0.5rem;
        }
    }
</style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <!-- Page Header -->
                    <div class="page-header">
                        <h1>
                            <i class="ri-video-chat-line"></i>
                            Telemedicine Consultations
                        </h1>
                        <p>Manage virtual patient consultations and video appointments</p>
                    </div>

                    <!-- Integration Status -->
                    <?php if ($video_enabled): ?>
                    <div class="integration-notice success">
                        <h6>
                            <i class="ri-checkbox-circle-line"></i>
                            Video Conferencing: ENABLED
                        </h6>
                        <p style="color: #065f46; margin-bottom: 0.5rem;">
                            Video calls are active and ready to use!
                        </p>
                        <div class="provider-badge">
                            <i class="ri-vidicon-line"></i>
                            Provider: <strong><?php echo strtoupper($video_provider); ?></strong>
                            <?php if ($video_provider === 'jitsi'): ?>
                                (<?php echo parse_url($video_settings['jitsi_server_url'] ?? 'https://meet.jit.si', PHP_URL_HOST); ?>)
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php else: ?>
                    <div class="integration-notice">
                        <h6>
                            <i class="ri-information-line"></i>
                            Video Conferencing: NOT CONFIGURED
                        </h6>
                        <p style="color: #92400e; margin-bottom: 0.5rem;">
                            Video conferencing is not enabled. Configure in <a href="system_settings.php" class="fw-bold">System Settings</a> to enable video calls.
                        </p>
                    </div>
                    <?php endif; ?>

                    <!-- Statistics Cards -->
                    <div class="stats-grid">
                        <div class="stat-card">
                            <div class="stat-icon" style="background: #cffafe; color: #164e63;">
                                <i class="ri-video-line"></i>
                            </div>
                            <div class="stat-value"><?php echo number_format($stats['total_appointments']); ?></div>
                            <div class="stat-label">Total Sessions</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-icon" style="background: #dbeafe; color: #1e40af;">
                                <i class="ri-calendar-check-line"></i>
                            </div>
                            <div class="stat-value"><?php echo number_format($stats['scheduled']); ?></div>
                            <div class="stat-label">Scheduled</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-icon" style="background: #fef3c7; color: #92400e;">
                                <i class="ri-live-line"></i>
                            </div>
                            <div class="stat-value"><?php echo number_format($stats['in_progress']); ?></div>
                            <div class="stat-label">In Progress</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-icon" style="background: #d1fae5; color: #065f46;">
                                <i class="ri-checkbox-circle-line"></i>
                            </div>
                            <div class="stat-value"><?php echo number_format($stats['completed']); ?></div>
                            <div class="stat-label">Completed</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-icon" style="background: #e0e7ff; color: #3730a3;">
                                <i class="ri-calendar-event-line"></i>
                            </div>
                            <div class="stat-value"><?php echo number_format($stats['today']); ?></div>
                            <div class="stat-label">Today's Sessions</div>
                        </div>
                    </div>

                    <!-- Filters -->
                    <div class="filters-section">
                        <div class="filter-tabs">
                            <button class="filter-tab <?php echo $status_filter === 'all' ? 'active' : ''; ?>" 
                                    onclick="window.location.href='?status=all&date=<?php echo $date_filter; ?>'">
                                <i class="ri-list-check"></i> All Sessions
                            </button>
                            <button class="filter-tab <?php echo $status_filter === 'SCHEDULED' ? 'active' : ''; ?>" 
                                    onclick="window.location.href='?status=SCHEDULED&date=<?php echo $date_filter; ?>'">
                                <i class="ri-calendar-check-line"></i> Scheduled
                            </button>
                            <button class="filter-tab <?php echo $status_filter === 'IN_PROGRESS' ? 'active' : ''; ?>" 
                                    onclick="window.location.href='?status=IN_PROGRESS&date=<?php echo $date_filter; ?>'">
                                <i class="ri-live-line"></i> Live Now
                            </button>
                            <button class="filter-tab <?php echo $status_filter === 'COMPLETED' ? 'active' : ''; ?>" 
                                    onclick="window.location.href='?status=COMPLETED&date=<?php echo $date_filter; ?>'">
                                <i class="ri-checkbox-circle-line"></i> Completed
                            </button>
                        </div>

                        <form method="GET" action="" class="row g-3">
                            <input type="hidden" name="status" value="<?php echo htmlspecialchars($status_filter); ?>">
                            <div class="col-md-4">
                                <label class="form-label">Search</label>
                                <input type="text" class="form-control" name="search" 
                                       value="<?php echo htmlspecialchars($search); ?>" 
                                       placeholder="Patient name, number, appointment #...">
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Appointment Date</label>
                                <input type="date" class="form-control" name="date" 
                                       value="<?php echo htmlspecialchars($date_filter); ?>">
                            </div>
                            <div class="col-md-2 d-flex align-items-end">
                                <button type="submit" class="btn btn-primary w-100">
                                    <i class="ri-search-line"></i> Search
                                </button>
                            </div>
                            <div class="col-md-3 d-flex align-items-end">
                                <a href="schedule_appointment.php?type=TELEMEDICINE" class="btn btn-success w-100">
                                    <i class="ri-add-line"></i> Schedule Telemedicine
                                </a>
                            </div>
                        </form>
                    </div>

                    <!-- Appointments Table -->
                    <div class="table-container">
                        <div class="table-responsive">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>Appointment #</th>
                                        <th>Patient</th>
                                        <th>Doctor</th>
                                        <th>Date & Time</th>
                                        <th>Chief Complaint</th>
                                        <th>Status</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if ($appointments->num_rows > 0): ?>
                                        <?php while ($row = $appointments->fetch_assoc()): 
                                            $appointment_datetime = strtotime($row['appointment_date'] . ' ' . $row['appointment_time']);
                                            $current_time = time();
                                            $time_diff = $appointment_datetime - $current_time;
                                            $is_now = abs($time_diff) <= 900; // Within 15 minutes
                                            $is_upcoming = $time_diff > 0 && $time_diff <= 3600; // Within 1 hour
                                        ?>
                                            <tr>
                                                <td>
                                                    <strong><?php echo htmlspecialchars($row['appointment_number']); ?></strong>
                                                    <br>
                                                    <span class="badge badge-info">TELEMEDICINE</span>
                                                </td>
                                                <td>
                                                    <div class="patient-info">
                                                        <span class="patient-name"><?php echo htmlspecialchars($row['patient_name']); ?></span>
                                                        <span class="patient-details">
                                                            <?php echo htmlspecialchars($row['patient_number']); ?> • 
                                                            <?php echo $row['patient_age']; ?> yrs
                                                        </span>
                                                        <span class="patient-details">
                                                            <i class="ri-phone-line"></i> <?php echo htmlspecialchars($row['patient_phone']); ?>
                                                        </span>
                                                        <?php if ($row['patient_email']): ?>
                                                        <span class="patient-details">
                                                            <i class="ri-mail-line"></i> <?php echo htmlspecialchars($row['patient_email']); ?>
                                                        </span>
                                                        <?php endif; ?>
                                                    </div>
                                                </td>
                                                <td>
                                                    <strong><?php echo htmlspecialchars($row['doctor_name']); ?></strong>
                                                    <?php if ($row['specialization']): ?>
                                                        <br><small class="text-muted"><?php echo htmlspecialchars($row['specialization']); ?></small>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <div class="time-indicator <?php echo $is_now ? 'now' : ($is_upcoming ? 'upcoming' : ''); ?>">
                                                        <?php if ($is_now): ?>
                                                            <i class="ri-time-line"></i>
                                                            <strong>NOW</strong>
                                                        <?php elseif ($is_upcoming): ?>
                                                            <i class="ri-alarm-warning-line"></i>
                                                            <strong>Soon</strong>
                                                        <?php endif; ?>
                                                    </div>
                                                    <?php echo date('d M Y', strtotime($row['appointment_date'])); ?><br>
                                                    <strong><?php echo date('h:i A', strtotime($row['appointment_time'])); ?></strong>
                                                </td>
                                                <td>
                                                    <?php 
                                                    $complaint = htmlspecialchars($row['chief_complaint'] ?? 'Not specified');
                                                    echo strlen($complaint) > 40 ? substr($complaint, 0, 40) . '...' : $complaint;
                                                    ?>
                                                </td>
                                                <td>
                                                    <?php
                                                    $status_badges = [
                                                        'SCHEDULED' => 'badge-primary',
                                                        'CONFIRMED' => 'badge-info',
                                                        'IN_PROGRESS' => 'badge-warning',
                                                        'COMPLETED' => 'badge-success',
                                                        'CANCELLED' => 'badge-danger',
                                                        'NO_SHOW' => 'badge-danger'
                                                    ];
                                                    $status_class = $status_badges[$row['status']] ?? 'badge-secondary';
                                                    ?>
                                                    <span class="badge <?php echo $status_class; ?>">
                                                        <?php echo str_replace('_', ' ', $row['status']); ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <div class="d-flex gap-2 flex-column">
                                                        <?php if ($video_enabled && ($row['status'] === 'SCHEDULED' || $row['status'] === 'CONFIRMED' || $row['status'] === 'IN_PROGRESS')): ?>
                                                            <button class="video-btn" 
                                                                    onclick="startVideoCall(<?php echo $row['appointment_id']; ?>, '<?php echo htmlspecialchars($row['appointment_number']); ?>', '<?php echo htmlspecialchars($row['patient_name']); ?>', '<?php echo htmlspecialchars($row['doctor_name']); ?>')">
                                                                <i class="ri-video-add-line"></i>
                                                                Start Video Call
                                                            </button>
                                                        <?php elseif (!$video_enabled && ($row['status'] === 'SCHEDULED' || $row['status'] === 'CONFIRMED')): ?>
                                                            <button class="video-btn" disabled title="Video conferencing not configured">
                                                                <i class="ri-video-off-line"></i>
                                                                Video Disabled
                                                            </button>
                                                        <?php endif; ?>
                                                        
                                                        <div class="btn-group" role="group">
                                                            <a href="view_appointment.php?id=<?php echo $row['appointment_id']; ?>" 
                                                               class="btn btn-sm btn-info" title="View Details">
                                                                <i class="ri-eye-line"></i>
                                                            </a>
                                                            
                                                            <?php if ($row['status'] !== 'COMPLETED' && $row['status'] !== 'CANCELLED'): ?>
                                                            <button class="btn btn-sm btn-success" 
                                                                    onclick="updateStatus(<?php echo $row['appointment_id']; ?>, 'CONFIRMED')"
                                                                    title="Confirm">
                                                                <i class="ri-check-line"></i>
                                                            </button>
                                                            <button class="btn btn-sm btn-danger" 
                                                                    onclick="updateStatus(<?php echo $row['appointment_id']; ?>, 'CANCELLED')"
                                                                    title="Cancel">
                                                                <i class="ri-close-line"></i>
                                                            </button>
                                                            <?php endif; ?>
                                                            
                                                            <button class="btn btn-sm btn-primary" 
                                                                    onclick="sendReminder(<?php echo $row['appointment_id']; ?>)"
                                                                    title="Send Reminder">
                                                                <i class="ri-notification-line"></i>
                                                            </button>
                                                        </div>
                                                    </div>
                                                </td>
                                            </tr>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <tr>
                                            <td colspan="7" class="text-center py-4">
                                                <i class="ri-video-off-line" style="font-size: 3rem; color: var(--gray-300);"></i>
                                                <p class="text-muted mt-2">No telemedicine appointments found</p>
                                                <a href="schedule_appointment.php?type=TELEMEDICINE" class="btn btn-primary mt-2">
                                                    <i class="ri-add-line"></i> Schedule First Telemedicine Session
                                                </a>
                                            </td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>

                        <!-- Pagination -->
                        <?php if ($total_pages > 1): ?>
                            <nav>
                                <ul class="pagination justify-content-center my-4">
                                    <?php if ($page > 1): ?>
                                        <li class="page-item">
                                            <a class="page-link" href="?page=<?php echo $page - 1; ?>&<?php echo http_build_query(array_filter($_GET, function($k) { return $k !== 'page'; }, ARRAY_FILTER_USE_KEY)); ?>">
                                                Previous
                                            </a>
                                        </li>
                                    <?php endif; ?>
                                    
                                    <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                                        <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                                            <a class="page-link" href="?page=<?php echo $i; ?>&<?php echo http_build_query(array_filter($_GET, function($k) { return $k !== 'page'; }, ARRAY_FILTER_USE_KEY)); ?>">
                                                <?php echo $i; ?>
                                            </a>
                                        </li>
                                    <?php endfor; ?>
                                    
                                    <?php if ($page < $total_pages): ?>
                                        <li class="page-item">
                                            <a class="page-link" href="?page=<?php echo $page + 1; ?>&<?php echo http_build_query(array_filter($_GET, function($k) { return $k !== 'page'; }, ARRAY_FILTER_USE_KEY)); ?>">
                                                Next
                                            </a>
                                        </li>
                                    <?php endif; ?>
                                </ul>
                            </nav>
                        <?php endif; ?>
                    </div>

                </div>
            </div>
        </div>
    </div>

    <!-- Video Call Modal -->
    <div class="modal fade" id="videoCallModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
        <div class="modal-dialog modal-xl modal-fullscreen-lg-down">
            <div class="modal-content">
                <div class="modal-header bg-dark text-white">
                    <h5 class="modal-title">
                        <i class="ri-video-chat-line"></i>
                        Telemedicine Video Call - <span id="appointmentNumber"></span>
                    </h5>
                    <button type="button" class="btn-close btn-close-white" onclick="confirmEndCall()"></button>
                </div>
                <div class="modal-body p-0" style="min-height: 500px; background: #1a1a1a;">
                    <!-- Video Container -->
                    <div id="jitsiContainer" style="height: 70vh; min-height: 500px;"></div>
                </div>
                <div class="modal-footer bg-dark">
                    <div class="d-flex justify-content-between w-100 align-items-center">
                        <div class="text-white">
                            <small>
                                <i class="ri-user-line"></i> 
                                Patient: <strong id="patientNameDisplay"></strong> | 
                                Doctor: <strong id="doctorNameDisplay"></strong>
                            </small>
                        </div>
                        <div>
                            <button type="button" class="btn btn-danger" onclick="confirmEndCall()">
                                <i class="ri-phone-line"></i> End Call
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <script>
        // Video conferencing configuration from PHP
        const videoConfig = {
            enabled: <?php echo $video_enabled ? 'true' : 'false'; ?>,
            provider: '<?php echo $video_provider; ?>',
            <?php if ($video_provider === 'jitsi'): ?>
            jitsi: {
                serverUrl: '<?php echo htmlspecialchars($video_settings['jitsi_server_url'] ?? 'https://meet.jit.si'); ?>',
                enableRecording: <?php echo ($video_settings['jitsi_enable_recording'] ?? '0') == '1' ? 'true' : 'false'; ?>,
                enableLobby: <?php echo ($video_settings['jitsi_enable_lobby'] ?? '1') == '1' ? 'true' : 'false'; ?>
            },
            <?php elseif ($video_provider === 'daily'): ?>
            daily: {
                apiKey: '<?php echo htmlspecialchars($video_settings['daily_api_key'] ?? ''); ?>',
                domain: '<?php echo htmlspecialchars($video_settings['daily_domain'] ?? ''); ?>'
            },
            <?php elseif ($video_provider === 'zoom'): ?>
            zoom: {
                apiKey: '<?php echo htmlspecialchars($video_settings['zoom_client_id'] ?? ''); ?>',
                apiSecret: '<?php echo htmlspecialchars($video_settings['zoom_client_secret'] ?? ''); ?>'
            },
            <?php elseif ($video_provider === 'whereby'): ?>
            whereby: {
                apiKey: '<?php echo htmlspecialchars($video_settings['whereby_api_key'] ?? ''); ?>',
                subdomain: '<?php echo htmlspecialchars($video_settings['whereby_subdomain'] ?? ''); ?>'
            },
            <?php endif; ?>
            quality: '<?php echo htmlspecialchars($video_settings['video_quality'] ?? '720p'); ?>',
            enableChat: <?php echo ($video_settings['video_enable_chat'] ?? '1') == '1' ? 'true' : 'false'; ?>
        };

        let jitsiApi = null;
        let currentAppointmentId = null;

        // Start video call function
        function startVideoCall(appointmentId, appointmentNumber, patientName, doctorName) {
            if (!videoConfig.enabled) {
                Swal.fire({
                    icon: 'error',
                    title: 'Video Not Configured',
                    text: 'Please enable video conferencing in System Settings',
                    confirmButtonColor: '#ef4444'
                });
                return;
            }

            currentAppointmentId = appointmentId;
            document.getElementById('appointmentNumber').textContent = appointmentNumber;
            document.getElementById('patientNameDisplay').textContent = patientName;
            document.getElementById('doctorNameDisplay').textContent = doctorName;
            
            // Show modal
            const videoModal = new bootstrap.Modal(document.getElementById('videoCallModal'));
            videoModal.show();
            
            // Update appointment status to IN_PROGRESS
            updateAppointmentStatus(appointmentId, 'IN_PROGRESS');
            
            // Initialize video based on provider
            if (videoConfig.provider === 'jitsi') {
                initJitsiMeet(appointmentNumber, doctorName);
            } else if (videoConfig.provider === 'daily') {
                initDailyCo(appointmentNumber);
            } else if (videoConfig.provider === 'zoom') {
                initZoom(appointmentNumber);
            } else if (videoConfig.provider === 'whereby') {
                initWhereby(appointmentNumber);
            }
        }
        
        // Initialize Jitsi Meet
        function initJitsiMeet(roomName, displayName) {
            if (typeof JitsiMeetExternalAPI === 'undefined') {
                Swal.fire({
                    icon: 'error',
                    title: 'Jitsi Not Loaded',
                    text: 'Jitsi Meet API failed to load. Please check your internet connection.',
                    confirmButtonColor: '#ef4444'
                });
                return;
            }

            const domain = videoConfig.jitsi.serverUrl.replace('https://', '').replace('http://', '');
            const options = {
                roomName: 'ENTHospital_' + roomName.replace(/[^a-zA-Z0-9]/g, '_'),
                width: '100%',
                height: '100%',
                parentNode: document.querySelector('#jitsiContainer'),
                userInfo: {
                    displayName: displayName
                },
                configOverwrite: {
                    startWithAudioMuted: false,
                    startWithVideoMuted: false,
                    enableWelcomePage: false,
                    prejoinPageEnabled: false,
                    disableDeepLinking: true,
                    enableNoisyMicDetection: true,
                    resolution: videoConfig.quality === '1080p' ? 1080 : (videoConfig.quality === '720p' ? 720 : 480)
                },
                interfaceConfigOverwrite: {
                    TOOLBAR_BUTTONS: [
                        'microphone', 'camera', 'closedcaptions', 'desktop', 'fullscreen',
                        'fodeviceselection', 'hangup', 'profile', 'chat', 'recording',
                        'livestreaming', 'etherpad', 'sharedvideo', 'settings', 'raisehand',
                        'videoquality', 'filmstrip', 'invite', 'feedback', 'stats', 'shortcuts',
                        'tileview', 'videobackgroundblur', 'download', 'help', 'mute-everyone'
                    ],
                    SHOW_JITSI_WATERMARK: false,
                    SHOW_WATERMARK_FOR_GUESTS: false,
                    DEFAULT_REMOTE_DISPLAY_NAME: 'Patient'
                }
            };

            jitsiApi = new JitsiMeetExternalAPI(domain, options);
            
            // Event listeners
            jitsiApi.addEventListener('videoConferenceJoined', () => {
                console.log('Video conference joined');
            });
            
            jitsiApi.addEventListener('videoConferenceLeft', () => {
                console.log('Video conference left');
                endVideoCall();
            });
            
            jitsiApi.addEventListener('participantLeft', (participant) => {
                console.log('Participant left:', participant);
            });
        }

        // Initialize Daily.co
        function initDailyCo(roomName) {
            // Daily.co integration
            const roomUrl = `https://${videoConfig.daily.domain}/${roomName}`;
            const iframe = document.createElement('iframe');
            iframe.allow = 'camera; microphone; fullscreen; display-capture';
            iframe.src = roomUrl;
            iframe.style.width = '100%';
            iframe.style.height = '100%';
            iframe.style.border = 'none';
            
            const container = document.getElementById('jitsiContainer');
            container.innerHTML = '';
            container.appendChild(iframe);
        }

        // Initialize Zoom
        function initZoom(roomName) {
            // Zoom integration would require server-side meeting creation
            Swal.fire({
                icon: 'info',
                title: 'Zoom Integration',
                text: 'Zoom meeting will be created. Please implement server-side meeting generation.',
                confirmButtonColor: '#06b6d4'
            });
        }

        // Initialize Whereby
        function initWhereby(roomName) {
            const roomUrl = `https://${videoConfig.whereby.subdomain}.whereby.com/${roomName}`;
            const iframe = document.createElement('iframe');
            iframe.allow = 'camera; microphone; fullscreen; display-capture';
            iframe.src = roomUrl;
            iframe.style.width = '100%';
            iframe.style.height = '100%';
            iframe.style.border = 'none';
            
            const container = document.getElementById('jitsiContainer');
            container.innerHTML = '';
            container.appendChild(iframe);
        }
        
        // Confirm end call
        function confirmEndCall() {
            Swal.fire({
                title: 'End Video Call?',
                text: 'This will close the video session. Continue?',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#ef4444',
                cancelButtonColor: '#6b7280',
                confirmButtonText: 'Yes, end call'
            }).then((result) => {
                if (result.isConfirmed) {
                    endVideoCall();
                }
            });
        }
        
        // End video call
        function endVideoCall() {
            // Dispose Jitsi API if exists
            if (jitsiApi) {
                jitsiApi.dispose();
                jitsiApi = null;
            }
            
            // Clear container
            document.getElementById('jitsiContainer').innerHTML = '';
            
            // Update appointment status to COMPLETED
            if (currentAppointmentId) {
                updateAppointmentStatus(currentAppointmentId, 'COMPLETED');
            }
            
            // Close modal
            const modalElement = document.getElementById('videoCallModal');
            const modalInstance = bootstrap.Modal.getInstance(modalElement);
            if (modalInstance) {
                modalInstance.hide();
            }
            
            Swal.fire({
                icon: 'success',
                title: 'Call Ended',
                text: 'Video call has been ended successfully',
                confirmButtonColor: '#10b981'
            }).then(() => {
                // Reload page to update status
                location.reload();
            });
        }
        
        // Update appointment status
        function updateAppointmentStatus(appointmentId, status) {
            fetch('api/update_appointment_status.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    appointment_id: appointmentId,
                    status: status
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    console.log('Status updated to: ' + status);
                }
            })
            .catch(error => console.error('Error:', error));
        }
        
        // Update status button
        function updateStatus(appointmentId, newStatus) {
            const statusText = newStatus === 'CONFIRMED' ? 'confirm' : 'cancel';
            
            Swal.fire({
                title: `${statusText.charAt(0).toUpperCase() + statusText.slice(1)} Appointment?`,
                text: `Do you want to ${statusText} this telemedicine appointment?`,
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: newStatus === 'CONFIRMED' ? '#10b981' : '#ef4444',
                cancelButtonColor: '#6b7280',
                confirmButtonText: `Yes, ${statusText} it`
            }).then((result) => {
                if (result.isConfirmed) {
                    // Create form and submit
                    const form = document.createElement('form');
                    form.method = 'POST';
                    form.action = 'telemedicine.php';
                    
                    const appointmentInput = document.createElement('input');
                    appointmentInput.type = 'hidden';
                    appointmentInput.name = 'appointment_id';
                    appointmentInput.value = appointmentId;
                    
                    const statusInput = document.createElement('input');
                    statusInput.type = 'hidden';
                    statusInput.name = 'new_status';
                    statusInput.value = newStatus;
                    
                    const updateInput = document.createElement('input');
                    updateInput.type = 'hidden';
                    updateInput.name = 'update_status';
                    updateInput.value = '1';
                    
                    form.appendChild(appointmentInput);
                    form.appendChild(statusInput);
                    form.appendChild(updateInput);
                    
                    document.body.appendChild(form);
                    form.submit();
                }
            });
        }
        
        // Send reminder
        function sendReminder(appointmentId) {
            Swal.fire({
                title: 'Send Reminder?',
                text: 'This will send SMS and email reminders to the patient',
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#06b6d4',
                cancelButtonColor: '#6b7280',
                confirmButtonText: 'Yes, send reminder'
            }).then((result) => {
                if (result.isConfirmed) {
                    // Send reminder via AJAX
                    fetch('api/send_appointment_reminder.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            appointment_id: appointmentId
                        })
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            Swal.fire({
                                icon: 'success',
                                title: 'Reminder Sent!',
                                text: data.message || 'Patient has been notified via SMS and email',
                                confirmButtonColor: '#10b981'
                            });
                        } else {
                            Swal.fire({
                                icon: 'error',
                                title: 'Failed to Send',
                                text: data.message || 'Could not send reminder',
                                confirmButtonColor: '#ef4444'
                            });
                        }
                    })
                    .catch(error => {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: 'Failed to send reminder: ' + error.message,
                            confirmButtonColor: '#ef4444'
                        });
                    });
                }
            });
        }

        // Cleanup on page unload
        window.addEventListener('beforeunload', function() {
            if (jitsiApi) {
                jitsiApi.dispose();
            }
        });
    </script>
    
    <?php if (isset($_SESSION['success_message'])): ?>
    <script>
        Swal.fire({
            icon: 'success',
            title: 'Success!',
            text: '<?php echo $_SESSION['success_message']; ?>',
            confirmButtonColor: '#10b981'
        });
    </script>
    <?php unset($_SESSION['success_message']); endif; ?>
    
    <?php if (isset($_SESSION['error_message'])): ?>
    <script>
        Swal.fire({
            icon: 'error',
            title: 'Error!',
            text: '<?php echo $_SESSION['error_message']; ?>',
            confirmButtonColor: '#ef4444'
        });
    </script>
    <?php unset($_SESSION['error_message']); endif; ?>
</body>
</html>