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

$db = getDB();

$courseId = $_GET['id'] ?? 0;
$lessonId = $_GET['lesson'] ?? null;

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

// Get course details
$stmt = $db->prepare("
    SELECT c.*, cat.name as category_name,
           u.username as instructor_name, up.first_name, up.last_name
    FROM courses c
    LEFT JOIN course_categories cat ON c.category_id = cat.id
    LEFT JOIN users u ON c.instructor_id = u.id
    LEFT JOIN user_profiles up ON u.id = up.user_id
    WHERE c.id = ?
");
$stmt->execute([$courseId]);
$course = $stmt->fetch();

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

// Check if user has access to this course
$userId = $_SESSION['user_id'] ?? 0;
$hasAccess = false;
$enrollment = null;

if (isLoggedIn()) {
    $stmt = $db->prepare("SELECT * FROM course_enrollments WHERE course_id = ? AND student_id = ?");
    $stmt->execute([$courseId, $userId]);
    $enrollment = $stmt->fetch();

    if ($enrollment) {
        $hasAccess = true;
    } elseif (hasRole('instructor') || hasRole('admin')) {
        // Instructors and admins can view all courses
        $hasAccess = true;
    }
} elseif (hasRole('guest')) {
    // Allow preview access for non-logged-in users
    $hasAccess = true;
}

if (!$hasAccess) {
    header('Location: login.php?redirect=courses/course.php?id=' . $courseId);
    exit;
}

// Get course lessons
$stmt = $db->prepare("
    SELECT cl.*,
           clp.status as progress_status,
           clp.progress_percentage,
           clp.time_spent,
           clp.completed_at
    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 ASC
");
$stmt->execute([$enrollment ? $enrollment['id'] : null, $courseId]);
$lessons = $stmt->fetchAll();

// Get current lesson
$currentLesson = null;
if ($lessonId) {
    foreach ($lessons as $lesson) {
        if ($lesson['id'] == $lessonId) {
            $currentLesson = $lesson;
            break;
        }
    }
} elseif (!empty($lessons)) {
    // Get first accessible lesson
    foreach ($lessons as $lesson) {
        if ($lesson['is_preview'] || $hasAccess) {
            $currentLesson = $lesson;
            break;
        }
    }
}

// Calculate course progress
$totalLessons = count($lessons);
$completedLessons = 0;
$totalTimeSpent = 0;

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

$progressPercentage = $totalLessons > 0 ? round(($completedLessons / $totalLessons) * 100) : 0;

// Update course progress if enrolled
if ($enrollment) {
    $stmt = $db->prepare("UPDATE course_enrollments SET progress_percentage = ?, updated_at = NOW() WHERE id = ?");
    $stmt->execute([$progressPercentage, $enrollment['id']]);

    // Mark as completed if all lessons are done
    if ($progressPercentage === 100 && $enrollment['status'] !== 'completed') {
        $stmt = $db->prepare("UPDATE course_enrollments SET status = 'completed', completion_date = NOW() WHERE id = ?");
        $stmt->execute([$enrollment['id']]);
    }
}

$pageTitle = 'Course Content: ' . htmlspecialchars($course['title']);
include '../includes/header.php';
?>

<div class="container-fluid">
    <div class="row">
        <!-- Sidebar with lesson navigation -->
        <div class="col-lg-3 col-md-4">
            <div class="card sticky-top" style="top: 20px;">
                <div class="card-header">
                    <h5 class="mb-0"><?php echo htmlspecialchars($course['title']); ?></h5>
                    <div class="progress mt-2" style="height: 8px;">
                        <div class="progress-bar" role="progressbar" style="width: <?php echo $progressPercentage; ?>%"></div>
                    </div>
                    <small class="text-muted"><?php echo $completedLessons; ?>/<?php echo $totalLessons; ?> lessons completed</small>
                </div>
                <div class="card-body p-0">
                    <div class="list-group list-group-flush" style="max-height: 70vh; overflow-y: auto;">
                        <?php foreach ($lessons as $lesson): ?>
                            <?php
                            $isAccessible = $lesson['is_preview'] || $hasAccess;
                            $isCompleted = $lesson['progress_status'] === 'completed';
                            $isCurrent = $currentLesson && $currentLesson['id'] == $lesson['id'];
                            ?>
                            <a href="?id=<?php echo $courseId; ?>&lesson=<?php echo $lesson['id']; ?>"
                               class="list-group-item list-group-item-action <?php echo $isCurrent ? 'active' : ''; ?> <?php echo !$isAccessible ? 'disabled' : ''; ?>"
                               <?php echo !$isAccessible ? 'aria-disabled="true"' : ''; ?>>
                                <div class="d-flex align-items-center">
                                    <div class="me-2">
                                        <?php if ($isCompleted): ?>
                                            <i class="fas fa-check-circle text-success"></i>
                                        <?php elseif ($lesson['progress_status'] === 'in_progress'): ?>
                                            <i class="fas fa-play-circle text-primary"></i>
                                        <?php else: ?>
                                            <i class="far fa-circle text-muted"></i>
                                        <?php endif; ?>
                                    </div>
                                    <div class="flex-grow-1">
                                        <div class="fw-bold small"><?php echo htmlspecialchars($lesson['title']); ?></div>
                                        <div class="text-muted small">
                                            <?php echo ucfirst($lesson['lesson_type']); ?>
                                            <?php if ($lesson['estimated_time']): ?>
                                                • <?php echo $lesson['estimated_time']; ?> min
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    <?php if (!$isAccessible): ?>
                                        <i class="fas fa-lock text-muted small"></i>
                                    <?php endif; ?>
                                </div>
                            </a>
                        <?php endforeach; ?>
                    </div>
                </div>
                <div class="card-footer">
                    <a href="course.php?id=<?php echo $courseId; ?>" class="btn btn-outline-primary btn-sm w-100">
                        <i class="fas fa-arrow-left me-1"></i>Back to Course
                    </a>
                </div>
            </div>
        </div>

        <!-- Main content area -->
        <div class="col-lg-9 col-md-8">
            <?php if ($currentLesson): ?>
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <div>
                            <h4 class="mb-0"><?php echo htmlspecialchars($currentLesson['title']); ?></h4>
                            <small class="text-muted">
                                <?php echo ucfirst($currentLesson['lesson_type']); ?>
                                <?php if ($currentLesson['estimated_time']): ?>
                                    • <?php echo $currentLesson['estimated_time']; ?> minutes
                                <?php endif; ?>
                            </small>
                        </div>
                        <div>
                            <?php if ($enrollment && $hasAccess): ?>
                                <button class="btn btn-sm btn-outline-success me-2" onclick="markCompleted(<?php echo $currentLesson['id']; ?>)">
                                    <i class="fas fa-check me-1"></i>Mark Complete
                                </button>
                            <?php endif; ?>
                            <div class="dropdown d-inline">
                                <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
                                    <i class="fas fa-ellipsis-v"></i>
                                </button>
                                <ul class="dropdown-menu">
                                    <li><a class="dropdown-item" href="#" onclick="addNote(<?php echo $currentLesson['id']; ?>)"><i class="fas fa-sticky-note me-2"></i>Add Note</a></li>
                                    <li><a class="dropdown-item" href="#" onclick="downloadResource(<?php echo $currentLesson['id']; ?>)"><i class="fas fa-download me-2"></i>Download</a></li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <?php if ($currentLesson['description']): ?>
                            <div class="mb-4">
                                <h6>Description</h6>
                                <p><?php echo nl2br(htmlspecialchars($currentLesson['description'])); ?></p>
                            </div>
                        <?php endif; ?>

                        <!-- Lesson Content -->
                        <div class="lesson-content">
                            <?php if ($currentLesson['lesson_type'] === 'video'): ?>
                                <?php if ($currentLesson['video_url']): ?>
                                    <div class="ratio ratio-16x9 mb-4">
                                        <iframe src="<?php echo htmlspecialchars($currentLesson['video_url']); ?>" allowfullscreen></iframe>
                                    </div>
                                <?php else: ?>
                                    <div class="alert alert-info">
                                        <i class="fas fa-video me-2"></i>Video content will be available soon.
                                    </div>
                                <?php endif; ?>

                            <?php elseif ($currentLesson['lesson_type'] === 'text'): ?>
                                <div class="content-text">
                                    <?php echo nl2br(htmlspecialchars($currentLesson['content'])); ?>
                                </div>

                            <?php elseif ($currentLesson['lesson_type'] === 'quiz'): ?>
                                <div class="quiz-container">
                                    <div class="alert alert-info">
                                        <i class="fas fa-question-circle me-2"></i>Quiz functionality will be implemented soon.
                                    </div>
                                </div>

                            <?php elseif ($currentLesson['lesson_type'] === 'assignment'): ?>
                                <div class="assignment-container">
                                    <div class="alert alert-warning">
                                        <i class="fas fa-tasks me-2"></i>Assignment submission will be available soon.
                                    </div>
                                </div>

                            <?php elseif ($currentLesson['lesson_type'] === 'resource'): ?>
                                <div class="resource-container">
                                    <?php if ($currentLesson['attachment_url']): ?>
                                        <div class="d-flex align-items-center p-3 border rounded">
                                            <i class="fas fa-file fa-2x me-3 text-primary"></i>
                                            <div class="flex-grow-1">
                                                <h6 class="mb-1"><?php echo htmlspecialchars($currentLesson['attachment_name'] ?? 'Resource File'); ?></h6>
                                                <p class="mb-0 text-muted small">Click to download</p>
                                            </div>
                                            <a href="<?php echo htmlspecialchars($currentLesson['attachment_url']); ?>" class="btn btn-primary" download>
                                                <i class="fas fa-download me-1"></i>Download
                                            </a>
                                        </div>
                                    <?php else: ?>
                                        <div class="alert alert-info">
                                            <i class="fas fa-file me-2"></i>Resource file will be available soon.
                                        </div>
                                    <?php endif; ?>
                                </div>
                            <?php endif; ?>
                        </div>

                        <!-- Lesson Actions -->
                        <?php if ($enrollment && $hasAccess): ?>
                            <div class="mt-4 pt-4 border-top">
                                <div class="row">
                                    <div class="col-md-6">
                                        <?php
                                        $prevLesson = null;
                                        $nextLesson = null;
                                        $currentIndex = -1;

                                        foreach ($lessons as $index => $lesson) {
                                            if ($lesson['id'] == $currentLesson['id']) {
                                                $currentIndex = $index;
                                                break;
                                            }
                                        }

                                        if ($currentIndex > 0) {
                                            $prevLesson = $lessons[$currentIndex - 1];
                                        }
                                        if ($currentIndex < count($lessons) - 1) {
                                            $nextLesson = $lessons[$currentIndex + 1];
                                        }
                                        ?>

                                        <?php if ($prevLesson): ?>
                                            <a href="?id=<?php echo $courseId; ?>&lesson=<?php echo $prevLesson['id']; ?>" class="btn btn-outline-secondary">
                                                <i class="fas fa-arrow-left me-1"></i>Previous
                                            </a>
                                        <?php endif; ?>
                                    </div>
                                    <div class="col-md-6 text-end">
                                        <?php if ($nextLesson): ?>
                                            <a href="?id=<?php echo $courseId; ?>&lesson=<?php echo $nextLesson['id']; ?>" class="btn btn-primary">
                                                Next<i class="fas fa-arrow-right ms-1"></i>
                                            </a>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            <?php else: ?>
                <div class="text-center py-5">
                    <i class="fas fa-book-open fa-4x text-muted mb-4"></i>
                    <h3>Welcome to <?php echo htmlspecialchars($course['title']); ?></h3>
                    <p class="text-muted mb-4">Select a lesson from the sidebar to begin learning.</p>
                    <?php if (!empty($lessons)): ?>
                        <a href="?id=<?php echo $courseId; ?>&lesson=<?php echo $lessons[0]['id']; ?>" class="btn btn-primary btn-lg">
                            <i class="fas fa-play me-2"></i>Start Learning
                        </a>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
let lessonStartTime = Date.now();

function markCompleted(lessonId) {
    fetch('../api/lesson_progress.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            lesson_id: lessonId,
            action: 'complete'
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            location.reload();
        } else {
            alert('Error: ' + data.error);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('An error occurred. Please try again.');
    });
}

function addNote(lessonId) {
    const note = prompt('Add a note for this lesson:');
    if (note) {
        fetch('../api/lesson_progress.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                lesson_id: lessonId,
                action: 'add_note',
                note: note
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('Note added successfully!');
            } else {
                alert('Error: ' + data.error);
            }
        });
    }
}

function downloadResource(lessonId) {
    // This would trigger download of lesson resources
    alert('Download functionality will be implemented soon.');
}

// Track time spent on lesson
window.addEventListener('beforeunload', function() {
    <?php if ($currentLesson && $enrollment): ?>
    const timeSpent = Math.floor((Date.now() - lessonStartTime) / 1000);
    if (timeSpent > 10) { // Only track if spent more than 10 seconds
        navigator.sendBeacon('../api/lesson_progress.php', JSON.stringify({
            lesson_id: <?php echo $currentLesson['id']; ?>,
            action: 'track_time',
            time_spent: timeSpent
        }));
    }
    <?php endif; ?>
});
</script>

<style>
.lesson-content {
    min-height: 400px;
}

.lesson-content img {
    max-width: 100%;
    height: auto;
}

.list-group-item.disabled {
    opacity: 0.6;
    pointer-events: none;
}

.ratio {
    position: relative;
    width: 100%;
}

.ratio iframe {
    position: absolute;
    width: 100%;
    height: 100%;
    border: 0;
}
</style>

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