<?php
// /elms/student/learn/index.php
declare(strict_types=1);

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../../includes/student_auth.php';
require_once __DIR__ . '/../../includes/db.php';

$mysqli = $mysqli ?? ($conn ?? null);

if (!$mysqli instanceof mysqli) {
    die('Database connection not found.');
}

$mysqli->set_charset('utf8mb4');

$PAGE_TITLE = 'Learning Materials';
$ACTIVE     = 'learn';

if (!function_exists('esc_learn')) {
    function esc_learn($value): string
    {
        return htmlspecialchars((string)$value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    }
}

if (!function_exists('learn_tbl_exists')) {
    function learn_tbl_exists(mysqli $db, string $table): bool
    {
        $stmt = $db->prepare("
            SELECT 1 
            FROM INFORMATION_SCHEMA.TABLES 
            WHERE TABLE_SCHEMA = DATABASE() 
              AND TABLE_NAME = ? 
            LIMIT 1
        ");
        $stmt->bind_param('s', $table);
        $stmt->execute();
        $ok = (bool)$stmt->get_result()->fetch_row();
        $stmt->close();
        return $ok;
    }
}

if (!function_exists('learn_col_exists')) {
    function learn_col_exists(mysqli $db, string $table, string $col): bool
    {
        $stmt = $db->prepare("
            SELECT 1 
            FROM INFORMATION_SCHEMA.COLUMNS 
            WHERE TABLE_SCHEMA = DATABASE() 
              AND TABLE_NAME = ? 
              AND COLUMN_NAME = ? 
            LIMIT 1
        ");
        $stmt->bind_param('ss', $table, $col);
        $stmt->execute();
        $ok = (bool)$stmt->get_result()->fetch_row();
        $stmt->close();
        return $ok;
    }
}

if (!function_exists('learn_first_col')) {
    function learn_first_col(mysqli $db, string $table, array $cols): ?string
    {
        foreach ($cols as $col) {
            if (learn_col_exists($db, $table, $col)) {
                return $col;
            }
        }
        return null;
    }
}

$studentId = (int)(
    $_SESSION['student_id']
    ?? $_SESSION['user_id']
    ?? $_SESSION['id']
    ?? 0
);

$course_id = (int)($_GET['course_id'] ?? 0);
$batch_id  = (int)($_GET['batch_id'] ?? 0);

$courses = [];
$batches = [];
$rows    = [];

/*
|--------------------------------------------------------------------------
| Courses assigned/enrolled to student
|--------------------------------------------------------------------------
*/
try {
    if (
        $studentId > 0 &&
        learn_tbl_exists($mysqli, 'enrollments') &&
        learn_tbl_exists($mysqli, 'batches') &&
        learn_tbl_exists($mysqli, 'courses') &&
        learn_col_exists($mysqli, 'enrollments', 'student_id') &&
        learn_col_exists($mysqli, 'enrollments', 'batch_id') &&
        learn_col_exists($mysqli, 'batches', 'course_id')
    ) {
        $courseTitleCol = learn_first_col($mysqli, 'courses', ['course_name', 'name', 'title']) ?? 'id';

        $stmt = $mysqli->prepare("
            SELECT DISTINCT c.id, c.`$courseTitleCol` AS title
            FROM enrollments e
            JOIN batches b ON b.id = e.batch_id
            JOIN courses c ON c.id = b.course_id
            WHERE e.student_id = ?
            ORDER BY title
        ");
        $stmt->bind_param('i', $studentId);
        $stmt->execute();
        $res = $stmt->get_result();

        while ($r = $res->fetch_assoc()) {
            $courses[(int)$r['id']] = (string)$r['title'];
        }

        $stmt->close();
    }

    if (!$courses && learn_tbl_exists($mysqli, 'courses')) {
        $courseTitleCol = learn_first_col($mysqli, 'courses', ['course_name', 'name', 'title']) ?? 'id';
        $res = $mysqli->query("SELECT id, `$courseTitleCol` AS title FROM courses ORDER BY title");

        while ($res && ($r = $res->fetch_assoc())) {
            $courses[(int)$r['id']] = (string)$r['title'];
        }
    }
} catch (Throwable $e) {
    $courses = [];
}

/*
|--------------------------------------------------------------------------
| Batches for selected course
|--------------------------------------------------------------------------
*/
try {
    if (
        $course_id > 0 &&
        learn_tbl_exists($mysqli, 'batches') &&
        learn_col_exists($mysqli, 'batches', 'course_id')
    ) {
        $batchLabelCol = learn_first_col($mysqli, 'batches', ['batch_name', 'batch_code', 'name', 'title']) ?? 'id';

        if (
            $studentId > 0 &&
            learn_tbl_exists($mysqli, 'enrollments') &&
            learn_col_exists($mysqli, 'enrollments', 'student_id') &&
            learn_col_exists($mysqli, 'enrollments', 'batch_id')
        ) {
            $stmt = $mysqli->prepare("
                SELECT DISTINCT b.id, b.`$batchLabelCol` AS title
                FROM enrollments e
                JOIN batches b ON b.id = e.batch_id
                WHERE e.student_id = ?
                  AND b.course_id = ?
                ORDER BY title
            ");
            $stmt->bind_param('ii', $studentId, $course_id);
        } else {
            $stmt = $mysqli->prepare("
                SELECT id, `$batchLabelCol` AS title
                FROM batches
                WHERE course_id = ?
                ORDER BY title
            ");
            $stmt->bind_param('i', $course_id);
        }

        $stmt->execute();
        $res = $stmt->get_result();

        while ($r = $res->fetch_assoc()) {
            $batches[(int)$r['id']] = (string)$r['title'];
        }

        $stmt->close();
    }
} catch (Throwable $e) {
    $batches = [];
}

/*
|--------------------------------------------------------------------------
| Released content
|--------------------------------------------------------------------------
*/
try {
    if (
        $course_id > 0 &&
        $batch_id > 0 &&
        learn_tbl_exists($mysqli, 'lms_content_release') &&
        learn_tbl_exists($mysqli, 'lms_content_items') &&
        learn_tbl_exists($mysqli, 'lms_units')
    ) {
        $stmt = $mysqli->prepare("
            SELECT 
                r.id AS rel_id,
                ci.id AS content_id,
                u.title AS unit_title,
                ci.title AS item_title,
                ci.type,
                ci.source_path_or_url,
                r.release_at,
                r.close_at
            FROM lms_content_release r
            JOIN lms_content_items ci ON ci.id = r.content_id
            JOIN lms_units u ON u.id = ci.unit_id
            WHERE r.batch_id = ?
              AND r.visible = 1
              AND r.release_at <= NOW()
              AND (r.close_at IS NULL OR r.close_at >= NOW())
              AND u.course_id = ?
            ORDER BY u.sort_order, ci.sort_order, r.release_at DESC
        ");
        $stmt->bind_param('ii', $batch_id, $course_id);
        $stmt->execute();
        $rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $stmt->close();
    }
} catch (Throwable $e) {
    $rows = [];
}

require_once __DIR__ . '/../../includes/student_layout_top.php';
?>

<style>
    .learn-page-grid {
        display: grid;
        grid-template-columns: 360px 1fr;
        gap: 18px;
    }

    .learn-filter-card,
    .learn-list-card,
    .learn-preview-card {
        background: #fff;
        border: 1px solid #e5e7eb;
        border-radius: 18px;
        box-shadow: 0 10px 28px rgba(15,23,42,.05);
    }

    .learn-filter-card {
        padding: 18px;
        margin-bottom: 18px;
    }

    .learn-list-card {
        overflow: hidden;
    }

    .learn-list-header,
    .learn-preview-header {
        padding: 16px 18px;
        border-bottom: 1px solid #e5e7eb;
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 10px;
    }

    .learn-list-body,
    .learn-preview-body {
        padding: 18px;
    }

    .learn-title {
        font-weight: 850;
        margin: 0;
        font-size: 1rem;
    }

    .learn-item {
        display: block;
        padding: 14px;
        border: 1px solid #e5e7eb;
        border-radius: 15px;
        text-decoration: none;
        color: #111827;
        margin-bottom: 10px;
        background: #fff;
        transition: .18s ease;
    }

    .learn-item:hover,
    .learn-item.active {
        border-color: #bfdbfe;
        background: #f8fbff;
        transform: translateY(-1px);
    }

    .learn-item-title {
        font-weight: 800;
        margin-bottom: 4px;
    }

    .learn-badge {
        display: inline-flex;
        align-items: center;
        gap: 5px;
        padding: 5px 9px;
        border-radius: 999px;
        background: #eff6ff;
        color: #1d4ed8;
        font-size: .75rem;
        font-weight: 800;
    }

    #learnViewer iframe,
    #learnViewer video {
        width: 100%;
        min-height: 68vh;
        border: 0;
        border-radius: 14px;
        background: #f8fafc;
    }

    #learnViewer img {
        max-width: 100%;
        border-radius: 14px;
    }

    .learn-empty {
        text-align: center;
        padding: 40px 20px;
        color: #64748b;
    }

    .learn-empty i {
        font-size: 2.4rem;
        color: #cbd5e1;
        display: block;
        margin-bottom: 10px;
    }

    @media (max-width: 992px) {
        .learn-page-grid {
            grid-template-columns: 1fr;
        }

        #learnViewer iframe,
        #learnViewer video {
            min-height: 55vh;
        }
    }
    @media (max-width: 768px) {
    .learn-filter-card .row > div {
        width: 100%;
    }

    .learn-item {
        padding: 12px;
    }

    #learnViewer iframe,
    #learnViewer video {
        min-height: 50vh;
    }
}
</style>
<div class="student-page-tabs">
    <a href="/elms/student/modules.php">My Courses</a>
    <a href="/elms/student/learn/index.php" class="active">Materials</a>
    <a href="/elms/student/assessments/assessments.php">Assessments</a>
    <a href="/elms/student/results.php">Results</a>
    <a href="/elms/student/games/games.php">Games</a>
</div>

<div class="learn-filter-card">
    <form class="row g-3 align-items-end" method="get">
        <div class="col-lg-5">
            <label class="form-label fw-bold">Course</label>
            <select name="course_id" class="form-select" required onchange="this.form.batch_id.value=''; this.form.submit()">
                <option value="">Select course...</option>
                <?php foreach ($courses as $cid => $ctitle): ?>
                    <option value="<?= (int)$cid ?>" <?= ((int)$cid === $course_id) ? 'selected' : '' ?>>
                        <?= esc_learn($ctitle) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="col-lg-5">
            <label class="form-label fw-bold">Batch</label>
            <select name="batch_id" class="form-select" required onchange="this.form.submit()">
                <option value="">Select batch...</option>
                <?php foreach ($batches as $bid => $btitle): ?>
                    <option value="<?= (int)$bid ?>" <?= ((int)$bid === $batch_id) ? 'selected' : '' ?>>
                        <?= esc_learn($btitle) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="col-lg-2">
            <button class="btn btn-primary w-100 rounded-pill fw-bold">
                Load
            </button>
        </div>
    </form>
</div>

<?php if ($course_id && $batch_id): ?>
    <div class="learn-page-grid">
        <div class="learn-list-card">
            <div class="learn-list-header">
                <div>
                    <h3 class="learn-title">Learning Materials</h3>
                    <div class="text-muted small"><?= count($rows) ?> item(s)</div>
                </div>
            </div>

            <div class="learn-list-body">
                <?php if ($rows): ?>
                    <?php foreach ($rows as $row): ?>
                        <?php
                        $href  = (string)($row['source_path_or_url'] ?? '');
                        $title = (string)($row['item_title'] ?? 'Untitled');
                        $unit  = (string)($row['unit_title'] ?? 'Unit');
                        $type  = (string)($row['type'] ?? 'Content');
                        $time  = !empty($row['release_at']) ? date('d M Y, h:i A', strtotime((string)$row['release_at'])) : '';
                        ?>
                        <a href="<?= esc_learn($href) ?>" class="learn-item open-learn">
                            <div class="learn-item-title"><?= esc_learn($title) ?></div>
                            <div class="text-muted small mb-2"><?= esc_learn($unit) ?></div>
                            <div class="d-flex align-items-center justify-content-between gap-2">
                                <span class="learn-badge">
                                    <i class="bi bi-play-circle"></i>
                                    <?= esc_learn($type) ?>
                                </span>
                                <?php if ($time): ?>
                                    <span class="text-muted small"><?= esc_learn($time) ?></span>
                                <?php endif; ?>
                            </div>
                        </a>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div class="learn-empty">
                        <i class="bi bi-journal-x"></i>
                        No materials released yet for this batch.
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <div class="learn-preview-card">
            <div class="learn-preview-header">
                <div>
                    <h3 class="learn-title">Preview</h3>
                    <div class="text-muted small">Select a released item to preview</div>
                </div>
            </div>

            <div class="learn-preview-body">
                <div id="learnViewer">
                    <div class="learn-empty">
                        <i class="bi bi-play-circle"></i>
                        Select an item from the left side.
                    </div>
                </div>
            </div>
        </div>
    </div>
<?php else: ?>
    <div class="learn-preview-card">
        <div class="learn-empty">
            <i class="bi bi-funnel"></i>
            Select course and batch to view released learning content.
        </div>
    </div>
<?php endif; ?>

<script>
(function () {
    const viewer = document.getElementById('learnViewer');

    document.addEventListener('click', function (e) {
        const a = e.target.closest('a.open-learn');
        if (!a || !viewer) return;

        e.preventDefault();

        document.querySelectorAll('.open-learn').forEach(function (x) {
            x.classList.remove('active');
        });
        a.classList.add('active');

        const url = a.getAttribute('href') || '';

        viewer.innerHTML = '<div class="learn-empty"><i class="bi bi-hourglass-split"></i>Loading...</div>';

        const yt = url.match(/(?:youtu\.be\/|youtube\.com\/(?:watch\?v=|embed\/|shorts\/))([\w\-]{6,})/i);
        if (yt) {
            const src = 'https://www.youtube.com/embed/' + encodeURIComponent(yt[1]) + '?rel=0';
            viewer.innerHTML = '<div class="ratio ratio-16x9"><iframe src="' + src + '" allowfullscreen></iframe></div>';
            return;
        }

        const vim = url.match(/vimeo\.com\/(?:video\/)?(\d+)/i);
        if (vim) {
            const src = 'https://player.vimeo.com/video/' + encodeURIComponent(vim[1]);
            viewer.innerHTML = '<div class="ratio ratio-16x9"><iframe src="' + src + '" allowfullscreen></iframe></div>';
            return;
        }

        if (/\.(pdf)(\?|$)/i.test(url)) {
            viewer.innerHTML = '<iframe src="' + url + '#toolbar=1&navpanes=0"></iframe>';
            return;
        }

        if (/\.(mp4|webm|ogg|mov|mkv)(\?|$)/i.test(url)) {
            viewer.innerHTML = '<video controls src="' + url + '"></video>';
            return;
        }

        if (/\.(jpg|jpeg|png|gif|webp|svg)(\?|$)/i.test(url)) {
            viewer.innerHTML = '<img src="' + url + '" alt="Learning content">';
            return;
        }

        viewer.innerHTML = `
    <iframe src="${url}" allowfullscreen></iframe>
    <div style="margin-top:10px;text-align:right;">
        <a href="${url}" target="_blank" class="btn btn-sm btn-outline-primary rounded-pill">
            Open in new tab
        </a>
    </div>
`;
    });
})();
</script>

<?php
require_once __DIR__ . '/../../includes/student_layout_bottom.php';
?>