<?php
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';

// Check if user is instructor or admin
anyRoleMiddleware(['instructor', 'admin']);

$user = getUserContext();
$db = getDB();
$userId = $_SESSION['user_id'];

$courseId = $_POST['course_id'] ?? $_GET['course_id'] ?? $_GET['id'] ?? 0;
$lessonData = $_POST;

// Ensure lesson data has default values
$lessonData = array_merge([
    'title' => 'Untitled Lesson',
    'description' => '',
    'content' => '',
    'lesson_type' => 'text',
    'video_url' => '',
    'estimated_time' => 0,
    'learning_objectives' => []
], $lessonData);

// Debug logging
error_log("Lesson Preview Debug - Course ID: $courseId, POST: " . json_encode($_POST) . ", GET: " . json_encode($_GET));

if (!$courseId) {
    error_log("Lesson Preview Error: No course ID provided");
    die('Course ID not provided');
}

// Get course details
try {
    $stmt = $db->prepare("SELECT * FROM courses WHERE id = ?");
    $stmt->execute([$courseId]);
    $course = $stmt->fetch();

    if (!$course) {
        error_log("Lesson Preview Error: Course not found for ID: $courseId");
        die('Course not found');
    }
    error_log("Lesson Preview Success: Found course '" . $course['title'] . "' for ID: $courseId");
} catch (PDOException $e) {
    error_log("Lesson Preview Database Error: " . $e->getMessage());
    die('Database error: ' . $e->getMessage());
}

// Check if user can edit this course
if (!canEditCourse($course['instructor_id'])) {
    error_log("Lesson Preview Error: Access denied for user " . $_SESSION['user_id'] . " to course $courseId owned by " . $course['instructor_id']);
    die('Access denied');
}

// Check if lesson data is provided for lesson preview
$lessonId = $_GET['lesson'] ?? null;
$isLessonPreview = !empty($lessonData) || !empty($lessonId);

if (!$isLessonPreview && $_SERVER['REQUEST_METHOD'] === 'GET') {
    // This is a course preview request, redirect to course detail page
    error_log("Lesson Preview: Redirecting to course detail for course ID: $courseId");
    header("Location: ../../courses/detail.php?id=$courseId");
    exit;
}

if ($isLessonPreview && empty($lessonData)) {
    // Try to load lesson data from database if lesson ID is provided
    if ($lessonId) {
        try {
            $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' => [] // Not stored in course_lessons table
                ];
                error_log("Lesson Preview: Loaded lesson data from database for lesson ID: $lessonId");
            } else {
                error_log("Lesson Preview Error: Lesson not found for ID: $lessonId in course: $courseId");
                die('Lesson not found');
            }
        } catch (PDOException $e) {
            error_log("Lesson Preview Database Error loading lesson: " . $e->getMessage());
            die('Database error loading lesson: ' . $e->getMessage());
        }
    } else {
        error_log("Lesson Preview Error: No lesson data provided for lesson preview");
        die('Lesson data not provided for preview');
    }
}

$pageTitle = 'Lesson Preview - ' . htmlspecialchars($course['title']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="Content-Security-Policy" content="frame-src https://www.youtube.com https://youtube.com https://vimeo.com https://player.vimeo.com;">
    <title><?php echo htmlspecialchars($pageTitle); ?></title>
    <!-- Load Tailwind CSS CDN -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Font Awesome for icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        /* Custom Tailwind Configuration and Base Styles */
        :root {
            --primary: #007bff; /* Blue */
            --secondary: #6c757d; /* Gray */
            --success: #28a745; /* Green */
            --danger: #dc3545; /* Red */
            --info: #17a2b8; /* Cyan */
        }
        .text-primary { color: var(--primary); }
        .bg-primary { background-color: var(--primary); }
        .bg-success { background-color: var(--success); }
        .bg-secondary { background-color: var(--secondary); }

        /* Ensure smooth scrolling and font */
        body { font-family: 'Inter', sans-serif; background-color: #f8f9fa; }

        .content-display {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            line-height: 1.6;
        }

        .content-display h1, .content-display h2, .content-display h3,
        .content-display h4, .content-display h5, .content-display h6 {
            margin-top: 1.5rem;
            margin-bottom: 0.5rem;
            font-weight: 600;
        }

        .content-display p {
            margin-bottom: 1rem;
        }

        .content-display ul, .content-display ol {
            margin-bottom: 1rem;
            padding-left: 2rem;
        }

        .content-display img {
            max-width: 100%;
            height: auto;
            border-radius: 8px;
            margin: 1rem 0;
        }

        .content-display a {
            color: #3b82f6;
            text-decoration: none;
        }

        .content-display a:hover {
            text-decoration: underline;
        }

        .video-container {
            position: relative;
            padding-bottom: 56.25%;
            height: 0;
            overflow: hidden;
            border-radius: 8px;
            margin: 1rem 0;
        }

        .video-container iframe {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            border: 0;
        }
    </style>
</head>
<body class="antialiased">
?>

<div class="min-h-screen bg-gray-50 py-8">
    <div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
        <!-- Header -->
        <div class="flex justify-between items-center mb-8">
            <div>
                <h1 class="text-3xl font-bold text-gray-800">Lesson Preview</h1>
                <p class="text-gray-600 mt-1">Course: <?php echo htmlspecialchars($course['title']); ?></p>
            </div>
            <button class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition duration-150" onclick="window.close()">
                <i class="fas fa-times mr-2"></i>Close Preview
            </button>
        </div>

        <!-- Lesson Content -->
        <div class="bg-white rounded-xl shadow-lg overflow-hidden">
            <div class="bg-gray-50 px-6 py-4 border-b border-gray-200">
                <h2 class="text-xl font-semibold text-gray-800"><?php echo htmlspecialchars($lessonData['title'] ?? 'Untitled Lesson'); ?></h2>
                <div class="flex items-center mt-2 space-x-3">
                    <span class="px-2 py-1 bg-gray-200 text-gray-700 text-sm rounded-full"><?php echo ucfirst($lessonData['lesson_type'] ?? 'text'); ?></span>
                    <?php if (!empty($lessonData['estimated_time'])): ?>
                        <span class="text-gray-500 text-sm"><?php echo $lessonData['estimated_time']; ?> minutes estimated</span>
                    <?php endif; ?>
                </div>
            </div>

            <div class="p-6">
                <?php if (!empty($lessonData['description'])): ?>
                    <div class="mb-6">
                        <h3 class="text-lg font-semibold text-gray-800 mb-3">Description</h3>
                        <p class="text-gray-700 leading-relaxed"><?php echo nl2br(htmlspecialchars($lessonData['description'])); ?></p>
                    </div>
                <?php endif; ?>

                <div class="lesson-content">
                    <?php if (!empty($lessonData['content'])): ?>
                        <div class="content-display">
                            <?php echo $lessonData['content']; ?>
                        </div>
                    <?php else: ?>
                        <div class="text-center py-12">
                            <i class="fas fa-file-alt text-6xl text-gray-400 mb-4"></i>
                            <p class="text-gray-500 text-lg">No content to preview</p>
                        </div>
                    <?php endif; ?>
                </div>

                <?php if (!empty($lessonData['video_url'])): ?>
                    <div class="mt-8">
                        <h3 class="text-lg font-semibold text-gray-800 mb-4">Video Content</h3>
                        <div class="video-container">
                            <iframe src="<?php echo htmlspecialchars($lessonData['video_url']); ?>" allowfullscreen></iframe>
                        </div>
                    </div>
                <?php endif; ?>

                <?php if (!empty($lessonData['learning_objectives'])): ?>
                    <div class="mt-8">
                        <h3 class="text-lg font-semibold text-gray-800 mb-4">Learning Objectives</h3>
                        <ul class="space-y-2">
                            <?php
                            // Handle learning_objectives - could be array from POST or JSON string from database
                            $objectives = $lessonData['learning_objectives'];
                            if (!is_array($objectives)) {
                                $objectives = json_decode($objectives, true);
                            }

                            if (is_array($objectives)) {
                                foreach ($objectives as $objective) {
                                    if (!empty($objective)) {
                                        echo '<li class="flex items-start"><i class="fas fa-check-circle text-green-500 mr-3 mt-0.5"></i><span class="text-gray-700">' . htmlspecialchars($objective) . '</span></li>';
                                    }
                                }
                            }
                            ?>
                        </ul>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

</body>
</html>