<?php
require_once __DIR__ . '/../config/database.php';
requireLogin();
$db = Database::getInstance();
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$lesson = $db->get("SELECT cl.*, c.title as course_title, c.id as course_id, c.instructor_id FROM course_lessons cl JOIN courses c ON cl.course_id = c.id WHERE cl.id = ?", [$id]);
if (!$lesson) redirect('courses.php');
$user = getCurrentUser();

// Agreement info is only relevant for students viewing the lesson
$lessonAgreement = null;

// Check access: students must be enrolled or lesson is free, or instructor
if (!hasRole('instructor') || (int)$lesson['instructor_id'] !== (int)$user['id']) {
    $enrolled = $db->get("SELECT id FROM course_enrollments WHERE course_id = ? AND student_id = ? AND status = 'active'", [$lesson['course_id'], $user['id']]);
    if (!$enrolled && !$lesson['is_free'] && !hasRole('instructor')) {
        // not enrolled
        header('Location: ' . APP_URL . '/lms/courses.php?course_id=' . (int)$lesson['course_id']);
        exit;
    }

    if (isset($_SESSION['role']) && $_SESSION['role'] === 'student') {
        $lessonAgreement = $db->get(
            "SELECT ce.id AS enrollment_id, a.id AS agreement_id
               FROM course_enrollments ce
          LEFT JOIN course_enrollment_agreements a ON a.enrollment_id = ce.id AND a.status = 'signed'
              WHERE ce.course_id = ? AND ce.student_id = ?
           ORDER BY ce.enrollment_date DESC
              LIMIT 1",
            [$lesson['course_id'], $user['id']]
        );
    }
}

$pageTitle = 'Lesson - ' . htmlspecialchars($lesson['title']);

// Get media metadata if any
$media = $db->get("SELECT * FROM course_media WHERE lesson_id = ? ORDER BY id DESC LIMIT 1", [$id]);
$thumbnail = $media['thumbnail_path'] ?? null;

include __DIR__ . '/includes/header.php';
?>

<div class="row">
    <div class="col-md-8">
        <div class="card">
            <div class="card-header"><h5 class="m-0"><?php echo htmlspecialchars($lesson['title']); ?></h5></div>
            <div class="card-body">
                <p class="text-muted">Course: <a href="<?php echo APP_URL; ?>/lms/courses.php?course_id=<?php echo (int)$lesson['course_id']; ?>"><?php echo htmlspecialchars($lesson['course_title']); ?></a></p>

                <?php if ($lessonAgreement && !empty($lessonAgreement['agreement_id'])): ?>
                    <p class="mb-3">
                        <a href="<?php echo APP_URL; ?>/lms/view_agreement.php?enrollment_id=<?php echo (int)$lessonAgreement['enrollment_id']; ?>" class="btn btn-sm btn-outline-secondary">
                            View Agreement
                        </a>
                    </p>
                <?php endif; ?>

                <?php if ($lesson['content_type'] === 'text'): ?>
                    <div><?php echo nl2br(htmlspecialchars($lesson['content_text'])); ?></div>
                <?php elseif ($lesson['content_type'] === 'video'): ?>
                    <?php if ($lesson['content_url']): ?>
                        <?php
                            $videoSrc = APP_URL . '/lms/file_view.php?path=' . urlencode($lesson['content_url']);
                            $posterAttr = '';
                            if ($thumbnail) {
                                $posterUrl = APP_URL . '/lms/file_view.php?path=' . urlencode($thumbnail);
                                $posterAttr = ' poster="' . htmlspecialchars($posterUrl) . '"';
                            }
                        ?>
                        <video controls width="100%" src="<?php echo htmlspecialchars($videoSrc); ?>"<?php echo $posterAttr; ?>></video>
                    <?php else: ?>
                        <p class="text-muted">No video uploaded yet.</p>
                    <?php endif; ?>
                <?php elseif ($lesson['content_type'] === 'slides'): ?>
                    <?php if ($lesson['content_url']): ?>
                        <a class="btn btn-primary" href="<?php echo APP_URL; ?>/lms/file_view.php?path=<?php echo urlencode($lesson['content_url']); ?>" target="_blank">Open Slides</a>
                    <?php else: ?>
                        <p class="text-muted">No slides uploaded yet.</p>
                    <?php endif; ?>
                <?php elseif ($lesson['content_type'] === 'quiz'): ?>
                    <p class="text-muted">This lesson is a quiz. <a href="<?php echo APP_URL; ?>/lms/assessments.php">Open Assessments</a></p>
                <?php elseif ($lesson['content_type'] === 'live_session'): ?>
                    <?php
                        $start = $lesson['zoom_start_time'] ?? null;
                        $joinUrl = $lesson['zoom_join_url'] ?? $lesson['content_url'] ?? null;
                    ?>
                    <?php if ($start): ?>
                        <p><strong>Session Time:</strong> <?php echo htmlspecialchars(date('Y-m-d H:i', strtotime($start))); ?> (<?php echo date_default_timezone_get(); ?>)</p>
                    <?php endif; ?>
                    <?php if ($joinUrl): ?>
                        <a href="<?php echo htmlspecialchars($joinUrl); ?>" target="_blank" class="btn btn-primary">Join Zoom Session</a>
                        <p class="text-muted mt-2 mb-0">The session will be recorded automatically. The recording will appear in this course after it is processed.</p>
                    <?php else: ?>
                        <p class="text-muted">Zoom meeting details are not available for this live session.</p>
                    <?php endif; ?>
                <?php else: ?>
                    <p class="text-muted">Content type: <?php echo htmlspecialchars($lesson['content_type']); ?></p>
                <?php endif; ?>

                <?php if (!empty($lesson['downloadable_resources'])): $resources = json_decode($lesson['downloadable_resources'], true); ?>
                    <hr />
                    <h6>Resources</h6>
                    <ul>
                        <?php foreach ($resources as $r): ?>
                            <li>
                                <a href="<?php echo APP_URL; ?>/lms/view_resource.php?path=<?php echo urlencode($r); ?>" target="_blank">
                                    <?php echo basename($r); ?>
                                </a>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php endif; ?>

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

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