<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

include '../include/config.php';

$doctor_id = $_SESSION['doctor_id'];
$doctor_name = $_SESSION['doctor_name'];
$cme_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

// Get CME session details
$cme = $conn->query("SELECT * FROM cme_sessions WHERE id = '$cme_id'")->fetch_assoc();

if (!$cme) {
    header("Location: doctor_engagement.php");
    exit();
}

// Create CME registrations table if not exists
$conn->query("CREATE TABLE IF NOT EXISTS cme_registrations (
    id INT AUTO_INCREMENT PRIMARY KEY,
    doctor_id INT NOT NULL,
    cme_id INT NOT NULL,
    registered_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    attended TINYINT DEFAULT 0,
    certificate_issued TINYINT DEFAULT 0
)");

// Check if already registered
$check_reg = $conn->query("SELECT * FROM cme_registrations WHERE doctor_id = '$doctor_id' AND cme_id = '$cme_id'");
$registered = $check_reg && $check_reg->num_rows > 0;

// Handle registration
$success_msg = '';
$error_msg = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['register'])) {
    if (!$registered) {
        $insert = $conn->query("INSERT INTO cme_registrations (doctor_id, cme_id, registered_at) 
                                VALUES ('$doctor_id', '$cme_id', NOW())");
        if ($insert) {
            $success_msg = "Successfully registered for CME session!";
            $registered = true;
        } else {
            $error_msg = "Registration failed: " . $conn->error;
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($cme['title']) ?> | UHD CME</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css">
    <style>
        :root {
            --uhd-green: #0a3d2f;
            --uhd-gold: #d4a017;
            --uhd-dark: #064e3b;
        }
        body { background: #f0f2f5; font-family: 'Segoe UI', sans-serif; }
        
        /* Sidebar */
        .sidebar {
            position: fixed;
            left: 0;
            top: 0;
            width: 280px;
            height: 100%;
            background: linear-gradient(135deg, #0a3d2f, #064e3b);
            color: white;
            z-index: 1000;
            overflow-y: auto;
            transition: 0.3s;
        }
        .sidebar-header {
            padding: 25px;
            text-align: center;
            border-bottom: 1px solid rgba(255,255,255,0.2);
        }
        .sidebar-header h4 { font-size: 1.2rem; margin: 10px 0 5px; }
        .sidebar-header p { font-size: 0.75rem; opacity: 0.8; }
        .sidebar-menu a {
            display: block;
            padding: 12px 20px;
            color: white;
            text-decoration: none;
            transition: 0.2s;
        }
        .sidebar-menu a:hover, .sidebar-menu a.active {
            background: rgba(255,255,255,0.15);
            border-left: 4px solid var(--uhd-gold);
        }
        .sidebar-menu i { width: 28px; margin-right: 10px; }
        
        .main-content {
            margin-left: 280px;
            padding: 25px;
            transition: 0.3s;
        }
        
        .cme-container { max-width: 800px; margin: 0 auto; }
        .cme-card {
            background: white;
            border-radius: 24px;
            padding: 35px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.08);
        }
        .credit-badge {
            background: linear-gradient(135deg, var(--uhd-gold), #b8860b);
            color: white;
            padding: 10px 25px;
            border-radius: 40px;
            display: inline-block;
            font-weight: 600;
        }
        .info-row {
            display: flex;
            align-items: center;
            gap: 15px;
            padding: 12px 0;
            border-bottom: 1px solid #e0e0e0;
        }
        .info-icon {
            width: 40px;
            height: 40px;
            background: #f8f9fa;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: var(--uhd-gold);
        }
        .btn-gold {
            background: var(--uhd-gold);
            color: white;
            border-radius: 40px;
            padding: 12px 25px;
            font-weight: 600;
            border: none;
            transition: 0.2s;
        }
        .btn-gold:hover {
            background: #b8860b;
            color: white;
        }
        .btn-outline-gold {
            background: transparent;
            border: 1px solid var(--uhd-gold);
            color: var(--uhd-gold);
            border-radius: 40px;
            padding: 10px 20px;
        }
        .btn-outline-gold:hover {
            background: var(--uhd-gold);
            color: white;
        }
        .menu-toggle {
            display: none;
            position: fixed;
            top: 15px;
            left: 15px;
            z-index: 1100;
            background: var(--uhd-green);
            color: white;
            border: none;
            padding: 8px 14px;
            border-radius: 8px;
        }
        
        @media (max-width: 768px) {
            .sidebar { transform: translateX(-100%); width: 260px; }
            .sidebar.active { transform: translateX(0); }
            .main-content { margin-left: 0; }
            .menu-toggle { display: block; }
            .cme-card { padding: 20px; }
        }
    </style>
</head>
<body>

<button class="menu-toggle" onclick="document.getElementById('sidebar').classList.toggle('active')">
    <i class="fas fa-bars"></i> Menu
</button>

<div class="sidebar" id="sidebar">
    <div class="sidebar-header">
        <i class="fas fa-graduation-cap fa-3x mb-2" style="color: var(--uhd-gold);"></i>
        <h4>Dr. <?= htmlspecialchars($doctor_name) ?></h4>
        <p>UHD CME Portal</p>
    </div>
    <div class="sidebar-menu">
        <a href="dashboard.php"><i class="fas fa-tachometer-alt"></i> Dashboard</a>
        <a href="my_patients.php"><i class="fas fa-users"></i> My Patients</a>
        <a href="consultations.php"><i class="fas fa-video"></i> Video Consult</a>
        <a href="appointments.php"><i class="fas fa-calendar-alt"></i> Appointments</a>
        <a href="doctor_engagement.php"><i class="fas fa-handshake"></i> Engagement Hub</a>
        <a href="cme_sessions.php" class="active"><i class="fas fa-graduation-cap"></i> CME Sessions</a>
        <a href="ai_assistant.php"><i class="fas fa-robot"></i> AI Assistant</a>
        <a href="doctor_payments.php"><i class="fas fa-money-bill-wave"></i> Payments</a>
        <a href="referral.php"><i class="fas fa-share-alt"></i> Refer & Earn</a>
        <a href="profile.php"><i class="fas fa-user-edit"></i> Profile</a>
        <a href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a>
    </div>
</div>

<div class="main-content">
    <div class="cme-container">
        <!-- Alerts -->
        <?php if ($success_msg): ?>
            <div class="alert alert-success alert-dismissible fade show"><?= $success_msg ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
        <?php endif; ?>
        <?php if ($error_msg): ?>
            <div class="alert alert-danger alert-dismissible fade show"><?= $error_msg ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
        <?php endif; ?>

        <!-- CME Details Card -->
        <div class="cme-card">
            <div class="text-center mb-4">
                <div class="credit-badge">
                    <i class="fas fa-star me-2"></i> <?= $cme['credits'] ?> CME Credits
                </div>
            </div>
            
            <h2 class="mb-4 text-center" style="color: var(--uhd-green);">
                <?= htmlspecialchars($cme['title']) ?>
            </h2>
            
            <div class="info-row">
                <div class="info-icon"><i class="fas fa-calendar-alt fa-lg"></i></div>
                <div>
                    <strong>Date:</strong> <?= date('l, F j, Y', strtotime($cme['scheduled_date'])) ?>
                </div>
            </div>
            
            <div class="info-row">
                <div class="info-icon"><i class="fas fa-clock fa-lg"></i></div>
                <div>
                    <strong>Time:</strong> <?= date('h:i A', strtotime($cme['scheduled_time'])) ?>
                </div>
            </div>
            
            <div class="info-row">
                <div class="info-icon"><i class="fas fa-certificate fa-lg"></i></div>
                <div>
                    <strong>Credits:</strong> <?= $cme['credits'] ?> Continuing Medical Education credits
                </div>
            </div>
            
            <div class="info-row">
                <div class="info-icon"><i class="fas fa-info-circle fa-lg"></i></div>
                <div>
                    <strong>Status:</strong> 
                    <span class="badge bg-<?= $cme['status'] == 'upcoming' ? 'success' : ($cme['status'] == 'ongoing' ? 'warning' : 'secondary') ?>">
                        <?= ucfirst($cme['status']) ?>
                    </span>
                </div>
            </div>
            
            <div class="mt-4 mb-4">
                <h5><i class="fas fa-align-left me-2" style="color: var(--uhd-gold);"></i> Description</h5>
                <div class="p-3 bg-light rounded">
                    <?= nl2br(htmlspecialchars($cme['description'])) ?>
                </div>
            </div>
            
            <!-- Registration Section -->
            <div class="text-center">
                <?php if ($registered): ?>
                    <div class="alert alert-success">
                        <i class="fas fa-check-circle me-2"></i> 
                        You are registered for this CME session!
                    </div>
                    <p class="text-muted small">Registration confirmed on <?= date('M d, Y', strtotime($check_reg->fetch_assoc()['registered_at'] ?? 'now')) ?></p>
                    
                <?php elseif ($cme['status'] == 'upcoming'): ?>
                    <form method="POST">
                        <button type="submit" name="register" class="btn btn-gold w-100 py-3">
                            <i class="fas fa-calendar-plus me-2"></i> Register for CME
                        </button>
                    </form>
                    
                <?php elseif ($cme['status'] == 'ongoing'): ?>
                    <div class="alert alert-warning">
                        <i class="fas fa-hourglass-half me-2"></i> 
                        This session is currently ongoing. Contact administrator for late registration.
                    </div>
                    
                <?php else: ?>
                    <div class="alert alert-secondary">
                        <i class="fas fa-clock me-2"></i> 
                        This CME session has ended. Check upcoming sessions for more opportunities.
                    </div>
                <?php endif; ?>
            </div>
            
            <hr class="my-4">
            
            <div class="d-flex gap-3">
                <a href="cme_sessions.php" class="btn btn-outline-gold">
                    <i class="fas fa-arrow-left me-2"></i> All CME Sessions
                </a>
                <a href="doctor_engagement.php" class="btn btn-outline-secondary">
                    <i class="fas fa-handshake me-2"></i> Engagement Hub
                </a>
            </div>
        </div>
        
        <!-- Related Information -->
        <div class="cme-card mt-4">
            <h5><i class="fas fa-lightbulb me-2" style="color: var(--uhd-gold);"></i> What to Expect</h5>
            <ul class="text-muted">
                <li>Live virtual session with expert faculty</li>
                <li>Interactive Q&A at the end of the session</li>
                <li>Certificate of completion issued within 7 days</li>
                <li>Session recording available for 30 days</li>
            </ul>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>