<?php
$pageTitle = 'Lesson Preview';
$active_link = 'courses';
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';

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:;');

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 = !isset($courseId) || !$courseId;

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

if (!$courseId) {
    $demoCourse = ['title' => 'Demo Course - Add ?course_id=1 to test with real data'];
} else {
    $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');
    }
}

if (empty(array_filter($lessonData)) && $lessonId && $courseId) {
    $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 .= isset($course) ? ' - ' . 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 href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script>
        tailwind.config = {
            theme: { extend: {
                colors: { primary: '#73D216', 'primary-dark': '#5FA015' },
                fontFamily: { sans: ['Inter', 'sans-serif'] }
            }}
        }
    </script>
    <style>
        body { font-family: 'Inter', sans-serif; background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%); }
        .glass { backdrop-filter: blur(12px); }
        .fade-in { animation: fadeIn 0.6s ease-out; }
        @keyframes fadeIn { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
        .content-display h1,h2,h3 { @apply mt-8 mb-4 font-bold text-gray-900; }
        .content-display p { @apply mb-4; }
        .content-display img { @apply rounded-2xl shadow-xl max-w-full h-auto my-6; }
        .video-container { position: relative; height: 0; padding-bottom: 56.25%; border-radius: 1rem; overflow: hidden; box-shadow: 0 25px 50px rgba(0,0,0,0.15); }
        .video-container iframe { @apply absolute inset-0 w-full h-full rounded-2xl; }
        .fullscreen-preview { @apply fixed inset-0 z-[10000] bg-white shadow-2xl; }
        .progress-sim { transition: width 0.4s cubic-bezier(0.4,0,.2,1); }
    </style>
</head>
<body class="min-h-screen">
    <!-- Top Header Bar -->
    <header class="fixed top-0 left-0 right-0 bg-white/95 backdrop-blur-xl z-50 border-b border-gray-200 shadow-sm">
        <div class="max-w-7xl mx-auto px-6 py-4 flex items-center justify-between">
            <div class="flex items-center gap-3">
                <i class="fas fa-graduation-cap text-2xl text-primary"></i>
                <div>
                    <h1 class="text-xl font-bold text-gray-900">Lesson Preview</h1>
                    <p class="text-sm text-gray-600">Instructor Tools</p>
                </div>
            </div>
            <div class="flex items-center gap-3">
                <a href="../index.php" class="p-2 text-gray-600 hover:text-primary hover:bg-gray-100 rounded-lg transition-all"><i class="fas fa-arrow-left"></i></a>
                <button onclick="toggleFullscreen()" class="p-3 bg-primary/10 hover:bg-primary/20 text-primary rounded-xl shadow-md hover:shadow-lg transition-all flex items-center gap-2">
                    <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 shadow-md hover:shadow-lg transition-all flex items-center gap-2">
                    <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 shadow-md hover:shadow-lg transition-all flex items-center gap-2">
                    <i class="fas fa-times"></i> Close
                </a>
            </div>
        </div>
    </header>

    <!-- Loading Overlay -->
    <div id="loading-overlay" class="<?php echo $isLoading ? '' : 'hidden'; ?> fixed inset-0 bg-gradient-to-br from-primary/20 via-white/90 to-green-50 flex items-center justify-center z-40 backdrop-blur-sm">
        <div class="bg-white/80 backdrop-blur-xl p-8 rounded-3xl shadow-2xl border border-primary/30 max-w-md text-center">
            <div class="w-20 h-20 border-4 border-primary/20 border-t-primary rounded-full animate-spin mx-auto mb-6"></div>
            <div class="text-primary">
                <p class="text-2xl font-bold mb-2">Loading Professional Preview...</p>
                <?php if (!$courseId): ?>
                    <p class="text-lg mb-4">Demo mode active. Add <code class="bg-gray-100 px-2 py-1 rounded text-sm font-mono">?course_id=1</code> for real data</p>
                <?php endif; ?>
                <div class="flex gap-2 justify-center flex-wrap">
                    <a href="?course_id=1" class="px-4 py-2 bg-primary text-white rounded-xl font-semibold hover:bg-primary-dark transition-all">Load Course 1</a>
                </div>
            </div>
        </div>
    </div>

    <!-- Main Content -->
    <main class="pt-24 pb-12 px-6 max-w-6xl mx-auto">
        <!-- Course Info Bar -->
        <div class="bg-gradient-to-r from-primary/5 to-green-50 p-6 rounded-3xl shadow-xl border border-primary/20 mb-10 backdrop-blur-sm">
            <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
                <div>
                    <h1 class="text-4xl font-black bg-gradient-to-r from-gray-900 via-gray-800 to-primary bg-clip-text text-transparent mb-2">
                        <?php echo htmlspecialchars($lessonData['title']); ?>
                    </h1>
                    <div class="flex items-center gap-6 text-sm text-gray-600">
                        <span class="flex items-center gap-2 px-4 py-2 bg-white/50 rounded-2xl shadow-sm">
                            <i class="fas fa-<?php echo $lessonData['lesson_type'] === 'video' ? 'video' : 'file-alt'; ?>"></i>
                            <?php echo ucfirst($lessonData['lesson_type']); ?>
                        </span>
                        <?php if ($lessonData['estimated_time']): ?>
                            <span class="flex items-center gap-2">
                                <i class="fas fa-clock"></i> <?php echo $lessonData['estimated_time']; ?> min
                            </span>
                        <?php endif; ?>
                        <span class="text-primary font-semibold">
                            <?php echo htmlspecialchars($course['title'] ?? 'Demo Course'); ?>
                        </span>
                    </div>
                </div>
                <div class="flex gap-3">
                    <button onclick="simulateProgress()" class="px-6 py-3 bg-gradient-to-r from-primary to-primary-dark text-white font-bold rounded-2xl shadow-lg hover:shadow-xl hover:scale-[1.02] transition-all flex items-center gap-2">
                        <i class="fas fa-play"></i> Simulate Progress
                    </button>
                    <button onclick="resetProgress()" class="px-6 py-3 bg-gray-100 hover:bg-gray-200 text-gray-700 font-semibold rounded-2xl shadow-lg hover:shadow-xl transition-all flex items-center gap-2">
                        <i class="fas fa-redo"></i> Reset
                    </button>
                </div>
            </div>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            <!-- Main Preview Card -->
            <div class="lg:col-span-2 space-y-8">
                <!-- Description (if exists) -->
                <?php if ($lessonData['description']): ?>
                    <div class="bg-white rounded-3xl shadow-2xl p-10 border border-gray-100 hover:shadow-3xl transition-all">
                        <h2 class="text-2xl font-bold text-gray-900 mb-6 flex items-center gap-4">
                            <div class="w-12 h-12 bg-blue-100 rounded-2xl flex items-center justify-center">
                                <i class="fas fa-info-circle text-blue-600 text-xl"></i>
                            </div>
                            Lesson Description
                        </h2>
                        <div class="prose prose-lg max-w-none text-gray-700 leading-relaxed">
                            <?php echo nl2br(htmlspecialchars($lessonData['description'])); ?>
                        </div>
                    </div>
                <?php endif; ?>

                <!-- Video Content -->
                <?php if ($lessonData['video_url']): ?>
                    <div class="bg-white rounded-3xl shadow-2xl p-10 border border-gray-100 hover:shadow-3xl transition-all">
                        <h2 class="text-2xl font-bold text-gray-900 mb-8 flex items-center gap-4">
                            <div class="w-12 h-12 bg-red-100 rounded-2xl flex items-center justify-center">
                                <i class="fas fa-video text-red-600 text-xl"></i>
                            </div>
                            Video Lesson
                        </h2>
                        <div class="video-container max-w-4xl mx-auto">
                            <?php
                            $videoUrl = $lessonData['video_url'];
                            $embedUrl = $videoUrl;
                            if (strpos($videoUrl, 'http') === 0) {
                                if (preg_match('/(?:youtube\.com\/(?:[^\/\s]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/', $videoUrl, $matches)) {
                                    $embedUrl = 'https://www.youtube.com/embed/' . $matches[1] . '?rel=0';
                                } elseif (preg_match('/vimeo\.com\/(?:video\/)?(\d+)/', $videoUrl, $matches)) {
                                    $embedUrl = 'https://player.vimeo.com/video/' . $matches[1];
                                }
                            }
                            ?>
                            <iframe src="<?php echo htmlspecialchars($embedUrl); ?>" 
                                    title="Lesson Video" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" 
                                    allowfullscreen class="w-full h-auto rounded-2xl shadow-inner">
                            </iframe>
                        </div>
                    </div>
                <?php endif; ?>

                <!-- Main Lesson Content -->
                <div class="bg-white rounded-3xl shadow-2xl p-10 border border-gray-100 hover:shadow-3xl transition-all">
                    <h2 class="text-2xl font-bold text-gray-900 mb-8 flex items-center gap-4">
                        <div class="w-12 h-12 bg-indigo-100 rounded-2xl flex items-center justify-center">
                            <i class="fas fa-book-open text-indigo-600 text-xl"></i>
                        </div>
                        Lesson Content
                    </h2>
                    <?php if ($lessonData['content']): ?>
                        <div class="content-display prose prose-xl max-w-none text-gray-800">
                            <?php echo $lessonData['content']; ?>
                        </div>
                    <?php else: ?>
                        <div class="text-center py-20">
                            <i class="fas fa-file-lines text-7xl text-gray-300 mb-8 opacity-75"></i>
                            <h3 class="text-3xl font-bold text-gray-500 mb-4">No Content Yet</h3>
                            <p class="text-xl text-gray-400 max-w-md mx-auto">Lesson content will appear here when added in the editor. Perfect preview of what students see!</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Right Sidebar - Objectives & Progress -->
            <div class="space-y-8">
                <!-- Learning Objectives -->
                <?php if (!empty($lessonData['learning_objectives'])): ?>
                    <div class="bg-gradient-to-br from-emerald-50 to-teal-50 rounded-3xl p-8 shadow-xl border border-emerald-200 sticky top-8">
                        <h3 class="text-xl font-bold text-gray-900 mb-6 flex items-center gap-3">
                            <div class="w-10 h-10 bg-emerald-100 rounded-xl flex items-center justify-center">
                                <i class="fas fa-lightbulb text-emerald-600"></i>
                            </div>
                            Learning Objectives
                        </h3>
                        <ul class="space-y-3">
                            <?php 
                            $objectives = is_array($lessonData['learning_objectives']) ? $lessonData['learning_objectives'] : json_decode($lessonData['learning_objectives'] ?? '[]', true);
                            foreach ((array)$objectives as $index => $obj): 
                                if (trim($obj) === '') continue;
                            ?>
                                <li class="group flex items-start gap-4 p-4 bg-white/80 backdrop-blur-sm rounded-2xl border border-emerald-100 hover:border-emerald-300 hover:shadow-md transition-all cursor-pointer">
                                    <div class="w-8 h-8 bg-gradient-to-r from-emerald-500 to-teal-500 rounded-xl flex items-center justify-center flex-shrink-0 mt-1 text-white font-bold text-sm shadow-lg">
                                        <?php echo $index + 1; ?>
                                    </div>
                                    <span class="text-gray-700 leading-relaxed group-hover:text-emerald-700"><?php echo htmlspecialchars($obj); ?></span>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                <?php endif; ?>

                <!-- Progress Simulator -->
                <div class="bg-gradient-to-br from-blue-50 to-indigo-50 rounded-3xl p-8 shadow-xl border border-blue-200 sticky top-8">
                    <h3 class="text-xl font-bold text-gray-900 mb-6 flex items-center gap-3">
                        <div class="w-10 h-10 bg-blue-100 rounded-xl flex items-center justify-center">
                            <i class="fas fa-chart-line text-blue-600"></i>
                        </div>
                        Progress Simulator
                    </h3>
                    <div class="space-y-4">
                        <div class="w-full bg-gray-200 rounded-full h-3 overflow-hidden shadow-inner">
                            <div id="progress-bar" class="bg-gradient-to-r from-primary to-primary-dark h-3 rounded-full shadow-lg progress-sim" style="width: 0%"></div>
                        </div>
                        <div class="flex justify-between text-sm font-mono text-gray-500 tracking-wide">
                            <span>00:00</span>
                            <span id="progress-percent">0%</span>
                        </div>
                        <div class="flex gap-3 pt-4 border-t border-blue-100">
                            <button onclick="simulateProgress()" class="flex-1 px-4 py-3 bg-gradient-to-r from-primary to-primary-dark text-white font-bold rounded-2xl shadow-lg hover:shadow-xl hover:scale-[1.02] transition-all flex items-center justify-center gap-2">
                                <i class="fas fa-play"></i> Simulate
                            </button>
                            <button onclick="resetProgress()" class="px-4 py-3 bg-white border-2 border-gray-300 text-gray-700 font-semibold rounded-2xl shadow-lg hover:shadow-md hover:border-gray-400 transition-all flex items-center justify-center gap-2 flex-shrink-0">
                                <i class="fas fa-redo"></i> Reset
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <!-- Footer - Slim version for preview tool -->
    <footer class="mt-24 bg-gradient-to-r from-primary to-primary-dark text-white py-12">
        <div class="max-w-7xl mx-auto px-6 text-center">
            <p class="text-lg font-semibold mb-4">Mutalex Academy &copy; 2025</p>
            <p class="text-sm opacity-90">Professional Lesson Preview Tool</p>
        </div>
    </footer>

    <script>
        let progress = 0, simInterval;
        window.addEventListener('load', () => {
            document.getElementById('loading-overlay')?.classList.add('hidden');
        });

        function toggleFullscreen() {
            const content = document.querySelector('main');
            if (!document.fullscreenElement) {
                content.requestFullscreen().catch(() => {});
            } else {
                document.exitFullscreen();
            }
        }

        function simulateProgress() {
            if (simInterval) clearInterval(simInterval);
            progress = 0;
            const bar = document.getElementById('progress-bar');
            const text = document.getElementById('progress-percent');
            simInterval = setInterval(() => {
                progress = Math.min(100, progress + (Math.random()*8 + 2));
                bar.style.width = progress + '%';
                text.textContent = Math.round(progress) + '%';
                if (progress >= 100) {
                    clearInterval(simInterval);
                    text.textContent = '100% ✓';
                }
            }, 150);
        }

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

        // Smooth scroll for internal links
        document.querySelectorAll('a[href^=\"#\"]').forEach(anchor => {
            anchor.addEventListener('click', e => {
                e.preventDefault();
                document.querySelector(anchor.getAttribute('href')).scrollIntoView({ behavior: 'smooth' });
            });
        });

        // Print optimization
        window.matchMedia('print').addListener(mql => {
            if (mql.matches) document.body.classList.add('print');
        });
    </script>
</body>
</html>

