<?php
require_once '../config/database.php';
require_once '../config/auth.php';
require_once '../includes/functions.php';
require_once '../includes/middleware.php';

studentOrHigher();

$db = getDB();
$userId = $_SESSION['user_id'];
$courseId = $_GET['id'] ?? 0;
$lessonId = $_GET['lesson'] ?? 0;

if (!$courseId || !$lessonId) {
    header('Location: index.php');
    exit;
}

// Get course details
$stmt = $db->prepare("
    SELECT c.*, cat.name as category_name,
           COUNT(DISTINCT cl.id) as total_lessons
    FROM courses c
    LEFT JOIN course_categories cat ON c.category_id = cat.id
    LEFT JOIN course_lessons cl ON c.id = cl.course_id
    WHERE c.id = ? AND c.status = 'published'
    GROUP BY c.id
");
$stmt->execute([$courseId]);
$course = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$course) {
    $_SESSION['error_message'] = 'Course not found.';
    header('Location: index.php');
    exit;
}

// Check enrollment
$stmt = $db->prepare("
    SELECT * FROM course_enrollments
    WHERE course_id = ? AND student_id = ?
");
$stmt->execute([$courseId, $userId]);
$enrollment = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$enrollment) {
    $_SESSION['error_message'] = 'You are not enrolled in this course.';
    header('Location: detail.php?id=' . $courseId);
    exit;
}

// Get course lessons
$stmt = $db->prepare("
    SELECT cl.*,
           COALESCE(clp.status, 'not_started') as progress_status,
           clp.completed_at,
           clp.time_spent,
           clp.notes
    FROM course_lessons cl
    LEFT JOIN course_lesson_progress clp ON cl.id = clp.lesson_id AND clp.enrollment_id = ?
    WHERE cl.course_id = ?
    ORDER BY cl.sort_order
");
$stmt->execute([$enrollment['id'], $courseId]);
$lessons = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Find current lesson
$currentLesson = null;
foreach ($lessons as $lesson) {
    if ($lesson['id'] == $lessonId) {
        $currentLesson = $lesson;
        break;
    }
}

if (!$currentLesson) {
    header('Location: index.php?id=' . $courseId);
    exit;
}

// Calculate progress
$completedLessons = 0;
$totalTimeSpent = 0;
foreach ($lessons as $lesson) {
    if ($lesson['progress_status'] === 'completed') {
        $completedLessons++;
    }
    $totalTimeSpent += $lesson['time_spent'] ?? 0;
}

$progressPercentage = $course['total_lessons'] > 0 ? round(($completedLessons / $course['total_lessons']) * 100) : 0;

// Get current lesson index
$currentIndex = array_search($currentLesson, array_column($lessons, null, 'id'));

$page_title = htmlspecialchars($course['title']) . ' - ' . htmlspecialchars($currentLesson['title']) . ' - Mutalex Academy';
include '../includes/header.php';
?>

<div class="min-h-screen bg-gray-50 font-sans text-slate-800">
    {/* Header */}
    <header class="bg-white border-b border-gray-200 sticky top-0 z-10">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 h-20 flex items-center justify-between">
            <div class="flex-1">
                <h1 class="text-xl font-bold text-slate-800"><?php echo htmlspecialchars($course['title']); ?></h1>
                <div class="mt-2 flex items-center gap-3">
                    <div class="h-2 w-48 bg-gray-100 rounded-full overflow-hidden">
                        <div
                            class="h-full bg-gradient-to-r from-green-500 to-emerald-400 transition-all duration-500"
                            style="width: <?php echo $progressPercentage; ?>%"
                        ></div>
                    </div>
                    <span class="text-xs text-gray-500 font-medium"><?php echo $progressPercentage; ?>% Complete</span>
                </div>
            </div>

            <div class="flex gap-3">
                <button class="flex items-center gap-2 px-4 py-2 text-sm font-medium text-blue-600 bg-blue-50 hover:bg-blue-100 rounded-lg transition-colors">
                    <i class="fas fa-info-circle"></i>
                    <span class="hidden sm:inline">Course Info</span>
                </button>
                <button class="flex items-center gap-2 px-4 py-2 text-sm font-medium text-gray-600 hover:bg-gray-100 rounded-lg transition-colors">
                    <i class="fas fa-tachometer-alt"></i>
                    <span class="hidden sm:inline">Dashboard</span>
                </button>
            </div>
        </div>
    </header>

    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
        <div class="grid grid-cols-1 lg:grid-cols-12 gap-6">

            {/* Left Sidebar (Lesson List) */}
            <div class="lg:col-span-3">
                <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden sticky top-24">
                    <div class="p-4 border-b border-gray-100 bg-gray-50/50">
                        <h3 class="font-semibold text-gray-900">Course Content</h3>
                        <p class="text-xs text-gray-500 mt-1"><?php echo count($lessons); ?> lessons • <?php echo array_sum(array_column($lessons, 'estimated_time')); ?> mins total</p>
                    </div>
                    <div class="max-h-[calc(100vh-300px)] overflow-y-auto">
                        <?php foreach ($lessons as $index => $lesson): ?>
                            <a
                                href="?id=<?php echo $courseId; ?>&lesson=<?php echo $lesson['id']; ?>"
                                class="block p-4 text-left transition-colors border-l-4 <?php echo $currentLessonId == $lesson['id'] ? 'bg-blue-50 border-blue-600' : 'border-transparent hover:bg-gray-50'; ?>"
                            >
                                <div class="flex items-start gap-3">
                                    <div class="mt-0.5">
                                        <?php if ($lesson['progress_status'] === 'completed'): ?>
                                            <i class="fas fa-check-circle w-5 h-5 text-green-500"></i>
                                        <?php elseif ($lesson['progress_status'] === 'in_progress'): ?>
                                            <i class="fas fa-play w-5 h-5 text-blue-500"></i>
                                        <?php elseif ($lesson['lesson_type'] === 'quiz'): ?>
                                            <i class="fas fa-question-circle w-5 h-5 text-gray-400"></i>
                                        <?php elseif ($lesson['lesson_type'] === 'assignment'): ?>
                                            <i class="fas fa-pencil-alt w-5 h-5 text-gray-400"></i>
                                        <?php elseif ($lesson['lesson_type'] === 'resource'): ?>
                                            <i class="fas fa-download w-5 h-5 text-gray-400"></i>
                                        <?php else: ?>
                                            <i class="fas fa-file-alt w-5 h-5 text-gray-400"></i>
                                        <?php endif; ?>
                                    </div>
                                    <div class="flex-1 min-w-0">
                                        <p class="text-sm font-medium truncate <?php echo $currentLessonId == $lesson['id'] ? 'text-blue-900' : 'text-gray-700'; ?>">
                                            <?php echo $index + 1; ?>. <?php echo htmlspecialchars($lesson['title']); ?>
                                        </p>
                                        <div class="flex items-center gap-2 mt-1">
                                            <span class="text-xs text-gray-400 flex items-center gap-1 capitalize">
                                                <?php echo $lesson['lesson_type']; ?>
                                            </span>
                                            <span class="text-gray-300">•</span>
                                            <span class="text-xs text-gray-400"><?php echo $lesson['estimated_time'] ?? 0; ?> min</span>
                                        </div>
                                    </div>
                                </div>
                            </a>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>

            {/* Main Content Area */}
            <div class="lg:col-span-6">
                <div class="bg-white rounded-xl shadow-sm border border-gray-100 min-h-[600px] flex flex-col">

                    {/* Navigation Bar */}
                    <div class="p-4 border-b border-gray-100 flex justify-between items-center bg-gray-50/30">
                        <?php
                        $prevLesson = $currentIndex > 0 ? $lessons[$currentIndex - 1] : null;
                        $nextLesson = $currentIndex < count($lessons) - 1 ? $lessons[$currentIndex + 1] : null;
                        ?>
                        <button
                            onclick="navigateLesson(<?php echo $prevLesson ? $prevLesson['id'] : 'null'; ?>)"
                            <?php echo !$prevLesson ? 'disabled' : ''; ?>
                            class="flex items-center gap-1 text-sm text-gray-600 hover:text-blue-600 disabled:opacity-30 disabled:hover:text-gray-600 transition-colors"
                        >
                            <i class="fas fa-chevron-left"></i> Previous
                        </button>
                        <button
                            onclick="navigateLesson(<?php echo $nextLesson ? $nextLesson['id'] : 'null'; ?>)"
                            <?php echo !$nextLesson ? 'disabled' : ''; ?>
                            class="flex items-center gap-1 text-sm font-medium text-blue-600 hover:text-blue-700 disabled:opacity-30 disabled:hover:text-blue-600 transition-colors"
                        >
                            Next <i class="fas fa-chevron-right"></i>
                        </button>
                    </div>

                    {/* Content Body */}
                    <div class="p-6 sm:p-8 flex-1">
                        <h2 class="text-2xl font-bold text-slate-900 mb-2"><?php echo htmlspecialchars($currentLesson['title']); ?></h2>
                        <p class="text-gray-500 mb-6"><?php echo htmlspecialchars($currentLesson['description']); ?></p>

                        {/* Dynamic Content Rendering based on Type */}
                        <div class="mb-8">
                            <?php if ($currentLesson['lesson_type'] === 'video' && $currentLesson['video_url']): ?>
                                <div class="aspect-video bg-black rounded-lg overflow-hidden shadow-lg">
                                    <?php
                                    $videoUrl = $currentLesson['video_url'];
                                    $embedUrl = $videoUrl;
                                    if (preg_match('/(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/', $videoUrl, $matches)) {
                                        $embedUrl = "https://www.youtube.com/embed/{$matches[1]}";
                                    } elseif (preg_match('/vimeo\.com\/(\d+)/', $videoUrl, $matches)) {
                                        $embedUrl = "https://player.vimeo.com/video/{$matches[1]}";
                                    }
                                    ?>
                                    <iframe
                                        src="<?php echo htmlspecialchars($embedUrl); ?>"
                                        class="w-full h-full"
                                        allowfullscreen
                                        title="<?php echo htmlspecialchars($currentLesson['title']); ?>"
                                    ></iframe>
                                </div>
                            <?php elseif ($currentLesson['lesson_type'] === 'text'): ?>
                                <div class="prose prose-slate max-w-none bg-gray-50 p-6 rounded-lg border border-gray-100">
                                    <?php echo $currentLesson['content']; ?>
                                </div>
                            <?php elseif ($currentLesson['lesson_type'] === 'quiz'): ?>
                                <div class="bg-blue-50 border border-blue-100 rounded-lg p-8 text-center">
                                    <div class="w-16 h-16 bg-blue-100 text-blue-600 rounded-full flex items-center justify-center mx-auto mb-4">
                                        <i class="fas fa-question-circle text-3xl"></i>
                                    </div>
                                    <h3 class="text-lg font-semibold text-blue-900 mb-2">Quiz Time!</h3>
                                    <p class="text-blue-700 mb-6">This module contains a quiz to test your understanding. You need 80% to pass.</p>
                                    <a href="../student/exams/take.php?id=<?php echo $currentLesson['id']; ?>" class="bg-blue-600 text-white px-6 py-2.5 rounded-lg hover:bg-blue-700 transition-colors font-medium inline-flex items-center gap-2">
                                        <i class="fas fa-play"></i> Start Quiz
                                    </a>
                                </div>
                            <?php elseif ($currentLesson['lesson_type'] === 'assignment'): ?>
                                <div class="bg-amber-50 border border-amber-100 rounded-lg p-8 text-center">
                                    <div class="w-16 h-16 bg-amber-100 text-amber-600 rounded-full flex items-center justify-center mx-auto mb-4">
                                        <i class="fas fa-pencil-alt text-3xl"></i>
                                    </div>
                                    <h3 class="text-lg font-semibold text-amber-900 mb-2">Assignment Required</h3>
                                    <p class="text-amber-700 mb-6">Please upload your project files to complete this lesson.</p>
                                    <button onclick="showAssignmentModal()" class="bg-amber-600 text-white px-6 py-2.5 rounded-lg hover:bg-amber-700 transition-colors font-medium inline-flex items-center gap-2">
                                        <i class="fas fa-upload"></i> Submit Assignment
                                    </button>
                                </div>
                            <?php elseif ($currentLesson['lesson_type'] === 'resource'): ?>
                                <div class="bg-green-50 border border-green-100 rounded-lg p-8 text-center">
                                    <div class="w-16 h-16 bg-green-100 text-green-600 rounded-full flex items-center justify-center mx-auto mb-4">
                                        <i class="fas fa-download text-3xl"></i>
                                    </div>
                                    <h3 class="text-lg font-semibold text-green-900 mb-2">Download Resource</h3>
                                    <p class="text-green-700 mb-6">Download the resource file to complete this lesson.</p>
                                    <?php if ($currentLesson['attachment_url']): ?>
                                        <a href="<?php echo htmlspecialchars($currentLesson['attachment_url']); ?>" class="bg-green-600 text-white px-6 py-2.5 rounded-lg hover:bg-green-700 transition-colors font-medium inline-flex items-center gap-2" download>
                                            <i class="fas fa-download"></i> Download Resource
                                        </a>
                                    <?php endif; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>

                    {/* Lesson Footer Actions */}
                    <div class="p-6 bg-gray-50 border-t border-gray-100 flex items-center justify-between">
                        <button
                            onclick="markLessonComplete(<?php echo $currentLesson['id']; ?>)"
                            <?php echo $currentLesson['progress_status'] === 'completed' ? 'disabled' : ''; ?>
                            class="flex items-center gap-2 px-6 py-2.5 rounded-lg font-medium transition-all <?php echo $currentLesson['progress_status'] === 'completed' ? 'bg-green-100 text-green-700 cursor-default' : 'bg-green-600 text-white hover:bg-green-700 shadow-sm'; ?>"
                        >
                            <i class="fas fa-check-circle"></i>
                            <?php echo $currentLesson['progress_status'] === 'completed' ? 'Completed' : 'Mark as Complete'; ?>
                        </button>

                        <button onclick="toggleNotes()" class="flex items-center gap-2 px-4 py-2.5 text-gray-700 hover:bg-white hover:shadow-sm rounded-lg transition-all border border-transparent hover:border-gray-200">
                            <i class="fas fa-sticky-note"></i>
                            <span class="hidden sm:inline">Notes</span>
                        </button>
                    </div>
                </div>
            </div>

            {/* Right Sidebar (Progress & Notes) */}
            <div class="lg:col-span-3">
                <div class="sticky top-24 space-y-6">

                    {/* Notes Panel */}
                    <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
                        <div class="p-4 border-b border-gray-100 bg-yellow-50/50 flex justify-between items-center">
                            <h4 class="font-semibold text-gray-900 flex items-center gap-2">
                                <i class="fas fa-sticky-note text-yellow-600"></i>
                                My Notes
                            </h4>
                            <?php if (!empty($currentLesson['notes'])): ?>
                                <span class="text-xs bg-yellow-100 text-yellow-700 px-2 py-0.5 rounded-full">Saved</span>
                            <?php endif; ?>
                        </div>
                        <div class="p-4">
                            <textarea id="lesson-notes" class="w-full h-40 p-3 text-sm text-gray-700 bg-yellow-50/20 border border-gray-200 rounded-lg focus:outline-none focus:border-yellow-400 focus:ring-1 focus:ring-yellow-400 resize-none" placeholder="Type your notes for this lesson here..."><?php echo htmlspecialchars($currentLesson['notes'] ?? ''); ?></textarea>
                            <button onclick="saveNotes()" class="mt-3 w-full py-2 bg-gray-900 text-white text-xs font-medium rounded-lg hover:bg-gray-800 transition-colors">
                                Save Note
                            </button>
                        </div>
                    </div>

                    {/* Stats Panel */}
                    <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-5">
                        <h4 class="font-semibold text-gray-900 mb-4">Your Progress</h4>

                        <div class="grid grid-cols-2 gap-4 mb-6">
                            <div class="text-center p-3 bg-blue-50 rounded-lg">
                                <span class="block text-xl font-bold text-blue-600"><?php echo $completedLessons; ?>/<?php echo count($lessons); ?></span>
                                <span class="text-xs text-blue-600/80">Lessons</span>
                            </div>
                            <div class="text-center p-3 bg-purple-50 rounded-lg">
                                <span class="block text-xl font-bold text-purple-600"><?php echo round($totalTimeSpent / 60, 1); ?>h</span>
                                <span class="text-xs text-purple-600/80">Time Spent</span>
                            </div>
                        </div>

                        <div class="space-y-3">
                            <div class="flex items-center justify-between text-sm">
                                <div class="flex items-center gap-2">
                                    <div class="w-2 h-2 rounded-full bg-green-500"></div>
                                    <span class="text-gray-600">Completed</span>
                                </div>
                                <span class="font-medium text-gray-900"><?php echo $completedLessons; ?></span>
                            </div>
                            <div class="flex items-center justify-between text-sm">
                                <div class="flex items-center gap-2">
                                    <div class="w-2 h-2 rounded-full bg-blue-500"></div>
                                    <span class="text-gray-600">In Progress</span>
                                </div>
                                <span class="font-medium text-gray-900"><?php echo count(array_filter($lessons, fn($l) => $l['progress_status'] === 'in_progress')); ?></span>
                            </div>
                            <div class="flex items-center justify-between text-sm">
                                <div class="flex items-center gap-2">
                                    <div class="w-2 h-2 rounded-full bg-gray-300"></div>
                                    <span class="text-gray-600">Not Started</span>
                                </div>
                                <span class="font-medium text-gray-900"><?php echo count(array_filter($lessons, fn($l) => $l['progress_status'] === 'not_started')); ?></span>
                            </div>
                        </div>
                    </div>

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

<!-- Assignment Modal -->
<div class="modal fade" id="assignmentModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Submit Assignment</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="assignmentForm" enctype="multipart/form-data">
                    <div class="mb-3">
                        <label class="form-label">Assignment Submission</label>
                        <textarea class="form-control" name="submission_text" rows="4" placeholder="Enter your assignment submission..."></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Attach Files (Optional)</label>
                        <input type="file" class="form-control" name="attachment" multiple>
                    </div>
                    <div class="text-end">
                        <button type="submit" class="btn btn-primary">Submit Assignment</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<style>
/* Additional styles for better appearance */
.prose {
    max-width: none;
}

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

.prose p {
    margin-bottom: 1rem;
}

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

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

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

.prose a:hover {
    text-decoration: underline;
}
</style>

<script>
let currentLessonId = <?php echo $currentLesson['id']; ?>;
let enrollmentId = <?php echo $enrollment['id']; ?>;
let lessonStartTime = Date.now();

document.addEventListener('DOMContentLoaded', function() {
    initializeLessonPlayer();
});

function initializeLessonPlayer() {
    // Track lesson start
    trackLessonStart(currentLessonId);

    // Auto-save notes
    const notesTextarea = document.getElementById('lesson-notes');
    if (notesTextarea) {
        let notesTimeout;
        notesTextarea.addEventListener('input', function() {
            clearTimeout(notesTimeout);
            notesTimeout = setTimeout(() => saveNotes(), 2000);
        });
    }
}

function navigateLesson(lessonId) {
    if (!lessonId) return;

    // Save current progress before navigating
    saveNotes();

    // Navigate to new lesson
    window.location.href = `?id=<?php echo $courseId; ?>&lesson=${lessonId}`;
}

function markLessonComplete(lessonId) {
    fetch('../api/lesson_progress.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            lesson_id: lessonId,
            enrollment_id: enrollmentId,
            action: 'complete',
            time_spent: Math.floor((Date.now() - lessonStartTime) / 1000)
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Update UI
            location.reload();
        } else {
            alert('Error updating progress: ' + data.error);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('An error occurred. Please try again.');
    });
}

function trackLessonStart(lessonId) {
    lessonStartTime = Date.now();

    fetch('../api/lesson_progress.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            lesson_id: lessonId,
            enrollment_id: enrollmentId,
            action: 'start'
        })
    });
}

function saveNotes() {
    const notes = document.getElementById('lesson-notes').value;

    fetch('../api/lesson_notes.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            lesson_id: currentLessonId,
            enrollment_id: enrollmentId,
            notes: notes
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification('Notes saved successfully!', 'success');
        }
    })
    .catch(error => {
        console.error('Error saving notes:', error);
    });
}

function toggleNotes() {
    // Notes are always visible in this design
    const notesTextarea = document.getElementById('lesson-notes');
    if (notesTextarea) {
        notesTextarea.focus();
    }
}

function showAssignmentModal() {
    const modal = new bootstrap.Modal(document.getElementById('assignmentModal'));
    modal.show();
}

function showNotification(message, type) {
    const notification = document.createElement('div');
    notification.className = `alert alert-${type === 'success' ? 'success' : 'danger'} alert-dismissible fade show position-fixed`;
    notification.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    notification.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;

    document.body.appendChild(notification);

    setTimeout(() => {
        notification.remove();
    }, 5000);
}

// Assignment form submission
document.getElementById('assignmentForm').addEventListener('submit', function(e) {
    e.preventDefault();

    const formData = new FormData(this);

    fetch('../api/assignments.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            bootstrap.Modal.getInstance(document.getElementById('assignmentModal')).hide();
            showNotification('Assignment submitted successfully!', 'success');
            markLessonComplete(currentLessonId);
        } else {
            showNotification('Error submitting assignment: ' + data.error, 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showNotification('An error occurred. Please try again.', 'error');
    });
});
</script>

<?php include '../includes/footer.php'; ?>