<?php
// Enhanced Professional Lesson Preview
// Integrates site layout, #73D216 green theme, loading/fullscreen features
$pageTitle = 'Lesson Preview';
$active_link = 'courses'; // For sidebar highlighting
require_once '../../config/database.php';
require_once '../../config/auth.php';
require_once '../../config/rbac.php';
require_once '../../includes/functions.php';
require_once '../../includes/middleware.php';

// Security headers
header('X-Frame-Options: SAMEORIGIN');
header('X-Content-Type-Options: nosniff');
header('Content-Security-Policy: default-src \'self\'; script-src \'self\' \'unsafe-inline\' \'unsafe-eval\' https://cdn.tailwind.com https://cdnjs.cloudflare.com; style-src \'self\' \'unsafe-inline\' https://cdnjs.cloudflare.com; img-src \'self\' data: https: blob:; font-src \'self\' data: https://cdnjs.cloudflare.com; connect-src \'self\' https:; media-src \'self\' https:; frame-src https://www.youtube.com https://youtube.com https://youtu.be https://player.vimeo.com https://vimeo.com https://www.google.com; worker-src \'self\' blob:;');

// Auth check
anyRoleMiddleware(['instructor', 'admin']);
$user = getUserContext();
$db = getDB();
$userId = $_SESSION['user_id'];

$courseId = $_POST['course_id'] ?? $_GET['course_id'] ?? $_GET['id'] ?? 0;
$lessonData = $_POST;
$lessonId = $_GET['lesson'] ?? null;
$isLoading = true; // For loading state

$lessonData = array_merge([
    'title' => 'Untitled Lesson',
    'description' => '',
    'content' => '',
    'lesson_type' => 'text',
    'video_url' => '',
    'estimated_time' => 0,
    'learning_objectives' => []
], $lessonData);

if (!$courseId) die('Course ID not provided');

// Get course
$stmt = $db->prepare("SELECT * FROM courses WHERE id = ?");
$stmt->execute([$courseId]);
$course = $stmt->fetch();
if (!$course || !canEditCourse($course['instructor_id'])) die('Access denied or course not found');

// Load lesson from DB if no POST data
if (empty($lessonData) && $lessonId) {
    $stmt = $db->prepare("SELECT * FROM course_lessons WHERE id = ? AND course_id = ?");
    $stmt->execute([$lessonId, $courseId]);
    $lessonFromDB = $stmt->fetch();
    if ($lessonFromDB) {
        $lessonData = [
            'title' => $lessonFromDB['title'] ?? 'Untitled Lesson',
            'description' => $lessonFromDB['description'] ?? '',
            'content' => $lessonFromDB['content'] ?? '',
            'lesson_type' => $lessonFromDB['lesson_type'] ?? 'text',
            'video_url' => $lessonFromDB['video_url'] ?? '',
            'estimated_time' => $lessonFromDB['estimated_time'] ?? 0,
            'learning_objectives' => []
        ];
    }
}
$isLoading = false;
$pageTitle .= ' - ' . htmlspecialchars($course['title']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($pageTitle); ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#73D216', // Site green
                        'primary-dark': '#5FA015',
                    },
                    fontFamily: {
                        sans: ['Inter', 'sans-serif'],
                    }
                }
            }
        }
    </script>
    <style>
        body { font-family: 'Inter', sans-serif; background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%); }
        .content-display { line-height: 1.7; }
        .content-display h1, .content-display h2 { margin-top: 2rem; margin-bottom: 1rem; font-weight: 700; color: #1e293b; }
        .content-display p { margin-bottom: 1.25rem; }
        .content-display img { max-width: 100%; height: auto; border-radius: 12px; box-shadow: 0 10px 25px rgba(0,0,0,0.1); }
        .video-container { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; border-radius: 16px; box-shadow: 0 20px 40px rgba(0,0,0,0.1); }
        .video-container iframe { position: absolute; top: 0; left: 0; width: 100%; height: 100%; border: 0; }
        #loading-spinner { display: none; }
        .fullscreen-preview { position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; z-index: 1000; background: white; }
        .progress-sim { transition: width 0.3s ease; }
        @keyframes fadeIn { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
        .fade-in { animation: fadeIn 0.6s ease-out; }
    </style>
</head>
<body class="min-h-screen">
    <!-- Header -->
    <?php include '../../includes/header.php'; ?>

    <div class="flex min-h-screen pt-16"> <!-- pt-16 for fixed header -->
        <!-- Sidebar -->
        <?php include '../includes/sidebar.php'; ?>

        <!-- Main Content -->
        <main class="flex-1 p-8 lg:ml-0 overflow-auto">
            <!-- Loading Overlay -->
            <div id="loading-overlay" class="fixed inset-0 bg-gradient-to-br from-primary/10 to-green-50 flex items-center justify-center z-50 <?php echo $isLoading ? '' : 'hidden'; ?>">
                <div class="text-center">
                    <div class="w-16 h-16 border-4 border-primary/20 border-t-primary rounded-full animate-spin mx-auto mb-4"></div>
                    <p class="text-lg font-semibold text-primary">Loading Lesson Preview...</p>
                </div>
            </div>

            <!-- Breadcrumb -->
            <nav class="flex mb-8 text-sm text-gray-600">
                <ol class="flex items-center space-x-2">
                    <li><a href="index.php" class="hover:text-primary"><i class="fas fa-courses mr-1"></i>Courses</a></li>
                    <li><span class="mx-2">/</span></li>
                    <li class="font-semibold text-primary"><?php echo htmlspecialchars($course['title']); ?></li>
                    <li><span class="mx-2">/</span></li>
                    <li class="text-gray-900">Preview</li>
                </ol>
            </nav>

            <div class="max-w-4xl mx-auto space-y-8">
                <!-- Page Header -->
                <div class="bg-white rounded-2xl shadow-xl border border-gray-200 p-8 fade-in">
                    <div class="flex justify-between items-start mb-6">
                        <div>
                            <h1 class="text-3xl lg:text-4xl font-bold bg-gradient-to-r from-gray-900 to-gray-700 bg-clip-text text-transparent mb-2">
                                Lesson Preview
                            </h1>
                            <p class="text-xl text-gray-600">Course: <span class="font-semibold text-primary"><?php echo htmlspecialchars($course['title']); ?></span></p>
                        </div>
                        <div class="flex gap-3">
                            <button onclick="toggleFullscreen()" class="p-3 bg-primary/10 hover:bg-primary/20 text-primary rounded-xl transition-all flex items-center gap-2 shadow-md hover:shadow-lg">
                                <i class="fas fa-expand"></i> Fullscreen
                            </button>
                            <button onclick="window.print()" class="p-3 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-xl transition-all flex items-center gap-2 shadow-md hover:shadow-lg">
                                <i class="fas fa-print"></i> Print
                            </button>
                            <a href="javascript:window.close()" class="p-3 bg-red-100 hover:bg-red-200 text-red-700 rounded-xl transition-all flex items-center gap-2 shadow-md hover:shadow-lg">
                                <i class="fas fa-times"></i> Close
                            </a>
                        </div>
                    </div>
                </div>

                <!-- Main Content Card -->
                <div id="preview-content" class="bg-white rounded-3xl shadow-2xl border border-gray-100 overflow-hidden fade-in">
                    <!-- Lesson Header -->
                    <div class="bg-gradient-to-r from-primary to-primary-dark px-8 py-6 border-b border-primary/10">
                        <div class="flex justify-between items-center">
                            <div>
                                <h2 class="text-2xl md:text-3xl font-bold text-white mb-1"><?php echo htmlspecialchars($lessonData['title']); ?></h2>
                                <div class="flex items-center gap-4 text-white/90 text-sm">
                                    <span class="px-3 py-1 bg-white/20 backdrop-blur-sm rounded-full"><?php echo ucfirst($lessonData['lesson_type']); ?></span>
                                    <?php if ($lessonData['estimated_time']): ?>
                                        <span><i class="fas fa-clock mr-1"></i><?php echo $lessonData['estimated_time']; ?> min estimated</span>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <div class="flex gap-2">
                                <button onclick="simulateProgress()" class="p-2 bg-white/20 hover:bg-white/30 rounded-xl text-white transition-all"><i class="fas fa-play"></i></button>
                            </div>
                        </div>
                    </div>

                    <!-- Content Body -->
                    <div class="p-8 lg:p-12">
                        <?php if ($lessonData['description']): ?>
                            <div class="mb-10 p-6 bg-gradient-to-br from-gray-50 to-blue-50 rounded-2xl border border-blue-100">
                                <h3 class="text-xl font-bold text-gray-800 mb-4 flex items-center gap-3">
                                    <i class="fas fa-info-circle text-blue-500"></i>Description
                                </h3>
                                <div class="prose prose-lg max-w-none text-gray-700 leading-relaxed"><?php echo nl2br(htmlspecialchars($lessonData['description'])); ?></div>
                            </div>
                        <?php endif; ?>

                        <!-- Video Section -->
                        <?php if ($lessonData['video_url']): ?>
                            <div class="mb-10">
                                <h3 class="text-xl font-bold text-gray-800 mb-6 flex items-center gap-3">
                                    <i class="fas fa-video text-red-500"></i>Video Content
                                </h3>
                                <div class="video-container mx-auto max-w-4xl">
                                    <?php
                                    $videoUrl = $lessonData['video_url'];
                                    $embedUrl = $videoUrl;
                                    $isLocalVideo = strpos($videoUrl, 'uploads/video/') !== false;
                                    $isHttp = strpos($videoUrl, 'http') === 0;
                                    
                                    if ($isLocalVideo) {
                                        $videoPath = '../../../' . $videoUrl;
                                    } elseif ($isHttp) {
                                        if (strpos($videoUrl, 'youtube.com') !== false || strpos($videoUrl, 'youtu.be') !== false) {
                                            if (preg_match('/(?:youtube\.com\/(?:[^\/\s]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/', $videoUrl, $matches)) {
                                                $embedUrl = 'https://www.youtube.com/embed/' . $matches[1];
                                            }
                                        } elseif (strpos($videoUrl, 'vimeo.com') !== false) {
                                            if (preg_match('/vimeo\.com\/(?:video\/)?(\d+)/', $videoUrl, $matches)) {
                                                $embedUrl = 'https://player.vimeo.com/video/' . $matches[1];
                                            }
                                        }
                                    }
                                    
                                    if ($isLocalVideo) {
                                        echo '<video controls class="w-full h-full object-contain" style="position:absolute;top:0;left:0;width:100%;height:100%;">';
                                        echo '<source src="' . htmlspecialchars($videoPath) . '" type="video/' . pathinfo($videoUrl, PATHINFO_EXTENSION) . '">';
                                        echo 'Your browser does not support the video tag.';
                                        echo '</video>';
                                    } else {
                                        echo '<iframe src="' . htmlspecialchars($embedUrl) . '" ';
                                        echo 'allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" ';
                                        echo 'allowfullscreen ';
                                        echo 'class="w-full h-full">';
                                        echo '</iframe>';
                                    }
                                    ?>
                                </div>
                            </div>
                        <?php endif; ?>

                        <!-- Main Content -->
                        <?php if ($lessonData['content']): ?>
                            <div class="mb-10">
                                <h3 class="text-xl font-bold text-gray-800 mb-6 flex items-center gap-3">
                                    <i class="fas fa-book-open text-blue-500"></i>Content
                                </h3>
                                <div class="content-display prose prose-lg max-w-none">
                                    <?php echo $lessonData['content']; ?>
                                </div>
                            </div>
                        <?php else: ?>
                            <div class="text-center py-20 bg-gray-50 rounded-2xl">
                                <i class="fas fa-file-alt text-6xl text-gray-400 mb-6"></i>
                                <h3 class="text-2xl font-bold text-gray-600 mb-2">No Content Preview</h3>
                                <p class="text-gray-500">Add content in the lesson editor to see the preview here.</p>
                            </div>
                        <?php endif; ?>

                        <!-- Learning Objectives -->
                        <?php if (!empty($lessonData['learning_objectives'])): ?>
                            <div class="bg-gradient-to-r from-emerald-50 to-green-50 p-8 rounded-2xl border border-emerald-200">
                                <h3 class="text-xl font-bold text-gray-800 mb-6 flex items-center gap-3">
                                    <i class="fas fa-lightbulb text-emerald-500"></i>Learning Objectives
                                </h3>
                                <ul class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <?php
                                    $objectives = is_array($lessonData['learning_objectives']) ? $lessonData['learning_objectives'] : json_decode($lessonData['learning_objectives'], true);
                                    foreach ((array)$objectives as $obj): if (empty($obj)) continue;
                                    ?>
                                        <li class="flex items-start gap-3 p-4 bg-white rounded-xl shadow-sm border border-gray-100 hover:shadow-md transition-all">
                                            <div class="w-6 h-6 bg-emerald-100 rounded-lg flex items-center justify-center flex-shrink-0 mt-0.5">
                                                <i class="fas fa-check text-emerald-600 text-sm"></i>
                                            </div>
                                            <span class="text-gray-700 leading-relaxed"><?php echo htmlspecialchars($obj); ?></span>
                                        </li>
                                    <?php endforeach; ?>
                                </ul>
                            </div>
                        <?php endif; ?>

                        <!-- Progress Simulation Bar -->
                        <div class="mt-12 p-6 bg-gradient-to-r from-blue-50 to-indigo-50 rounded-2xl border border-blue-200">
                            <h4 class="text-lg font-bold text-gray-800 mb-4 flex items-center gap-2">
                                <i class="fas fa-chart-line text-blue-500"></i>Student Progress Simulation
                            </h4>
                            <div class="w-full bg-gray-200 rounded-full h-4">
                                <div id="progress-bar" class="bg-gradient-to-r from-primary to-primary-dark h-4 rounded-full progress-sim" style="width: 0%;"></div>
                            </div>
                            <div class="flex justify-between text-sm text-gray-600 mt-2">
                                <span>0%</span>
                                <span id="progress-text">0%</span>
                            </div>
                            <button onclick="resetProgress()" class="mt-4 px-6 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 font-medium rounded-xl transition-all flex items-center gap-2 mx-auto">
                                <i class="fas fa-redo"></i> Reset Simulation
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <!-- Footer -->
    <?php include '../../includes/footer.php'; ?>

    <script>
        // Hide loading after page load
        window.addEventListener('load', () => {
            document.getElementById('loading-overlay').classList.add('hidden');
        });

        // Fullscreen Toggle
        function toggleFullscreen() {
            const content = document.getElementById('preview-content');
            const isFullscreen = content.classList.contains('fullscreen-preview');
            if (!isFullscreen) {
                content.classList.add('fullscreen-preview');
                content.style.position = 'fixed';
                content.style.top = '0';
                content.style.left = '0';
                content.style.width = '100vw';
                content.style.height = '100vh';
                content.style.zIndex = '1000';
                content.style.background = 'white';
                document.body.style.overflow = 'hidden';
            } else {
                content.classList.remove('fullscreen-preview');
                content.style.position = '';
                content.style.top = '';
                content.style.left = '';
                content.style.width = '';
                content.style.height = '';
                content.style.zIndex = '';
                document.body.style.overflow = '';
            }
        }

        // Progress Simulation
        let progress = 0;
        function simulateProgress() {
            progress = 0;
            const bar = document.getElementById('progress-bar');
            const text = document.getElementById('progress-text');
            const interval = setInterval(() => {
                progress += Math.random() * 5;
                if (progress > 100) progress = 100;
                bar.style.width = progress + '%';
                text.textContent = Math.round(progress) + '%';
                if (progress >= 100) clearInterval(interval);
            }, 200);
        }

        function resetProgress() {
            progress = 0;
            document.getElementById('progress-bar').style.width = '0%';
            document.getElementById('progress-text').textContent = '0%';
        }

        // Print Styles
        window.addEventListener('beforeprint', () => {
            document.body.classList.add('printing');
        });
        window.addEventListener('afterprint', () => {
            document.body.classList.remove('printing');
        });
    </script>
</body>
</html>
