<?php
// learn_lesson.inc.php
// Affiche une lesson avec progression utilisateur
// Compatible YouTube + Lesson Pages + Progression + Auto-next-lesson

// Charger toutes les lessons du module pour navigation
try {
    $stmt = $dbh->prepare("
        SELECT * FROM mondialisa_formation_lessons
        WHERE module_ref=? AND statut=1
        ORDER BY position ASC
    ");
    $stmt->execute([$module['ref']]);
    $lessons = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Trouver la prochaine lesson
    $nextLessonRef = null;
    foreach ($lessons as $index => $l) {
        if ($l['ref'] == $lesson['ref'] && isset($lessons[$index + 1])) {
            $nextLessonRef = $lessons[$index + 1]['ref'];
            break;
        }
    }
} catch (PDOException $e) {
    error_log("Erreur PDO load lessons: ".$e->getMessage());
    addMsg('error', 'Impossible de charger les autres lessons.');
    $lessons = [];
    $nextLessonRef = null;
}

// Charger les pages si pas de vidéo
$pages = [];
if(empty($lesson['video_url'])){
    try {
        $stmt = $dbh->prepare("
            SELECT * FROM mondialisa_formation_lesson_pages
            WHERE lesson_ref=? AND statut=1
            ORDER BY page_number ASC
        ");
        $stmt->execute([$lesson['ref']]);
        $pages = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        error_log("Erreur PDO load lesson pages: ".$e->getMessage());
    }
}

// Déterminer le bouton
if ($progress >= 100) {
    $caption = "✅ Completed";
    $btnClass = "btn-success";
} elseif ($progress > 0) {
    $caption = "▶ Continuer ({$progress}%)";
    $btnClass = "btn-warning";
} else {
    $caption = "🚀 Start";
    $btnClass = "btn-primary";
}
?>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">

<div class="container my-5">

    <h2><?= htmlspecialchars($lesson['title']) ?></h2>
    <p class="text-muted">Module: <?= htmlspecialchars($module['title']) ?></p>

    <div class="border rounded p-4 mb-4 bg-light">

        <?php if (!empty($lesson['description'])): ?>
        <p><?= nl2br(htmlspecialchars($lesson['description'])) ?></p>
        <?php endif; ?>

        <?php if (!empty($lesson['content'])): ?>
        <div class="mt-3">
            <?= $lesson['content'] ?>
        </div>
        <?php endif; ?>

        <?php if (!empty($lesson['video_url'])): ?>
            <!-- YouTube Player -->
            <div id="player" class="mt-3"></div>
        <?php elseif(count($pages) > 0): ?>
            <!-- Lesson Pages Slideshow -->
            <div id="lessonSlides" class="mt-3">
                <?php foreach($pages as $index => $page): ?>
                    <div class="lesson-page" style="<?= $index==0?'display:block':'display:none' ?>">
                        <h4><?= htmlspecialchars($page['title'] ?? "Page ".$page['page_number']) ?></h4>
                        <p><?= nl2br(htmlspecialchars($page['content'])) ?></p>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

    </div>

    <!-- Progress -->
    <div class="mb-4">
        <strong>Progression :</strong>
        <div class="progress" style="height:25px;">
            <div id="progressBar" class="progress-bar <?= $btnClass ?>" role="progressbar" style="width: <?= $progress ?>%;"><?= $progress ?>%</div>
        </div>
    </div>

    <!-- Buttons -->
    <div class="mb-4">
        <a id="startstopBtn" href="index.php?p=learn_formation_module_lesson&ref=<?= $lesson['ref'] ?>" class="btn <?= $btnClass ?> me-2"><?= $caption ?></a>
        <?php if ($nextLessonRef): ?>
            <a id="nextLessonBtn" href="index.php?p=learn_formation_module_lesson&ref=<?= $nextLessonRef ?>" class="btn btn-outline-primary">➡ Next Lesson </a>
        <?php else: ?>
            <span class="text-success">🎉 Last lesson in this module !</span>
        <?php endif; ?>
    </div>

    <div class="mt-5">
        <a href="index.php?p=learn_formation_module&ref=<?= $module['ref'] ?>" class="btn btn-secondary">🔙 Lessons</a>
    </div>
</div>

<!-- JS Logic -->
<?php if (!empty($lesson['video_url'])): ?>
<!-- YouTube Video Tracking -->
<script src="https://www.youtube.com/iframe_api"></script>
<script>
let player;
let interval = null;
let lessonRef = "<?= $lesson['ref'] ?>";
let userRef = "<?= $user_ref ?>";
let lastSent = <?= $progress ?>;
let nextLessonRef = "<?= $nextLessonRef ?? '' ?>";

function extractYoutubeId(url) {
    let regExp = /(?:youtube\.com\/.*v=|youtu\.be\/)([^&]+)/;
    let match = url.match(regExp);
    return match ? match[1] : null;
}

function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
        height: '390',
        width: '100%',
        videoId: extractYoutubeId("<?= $lesson['video_url'] ?>"),
        events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
        }
    });
}

function onPlayerReady(event){
    let duration = player.getDuration();
    if(duration > 0){
        let startSeconds = Math.floor((<?= $progress ?> / 100) * duration);
        if(startSeconds > 0) player.seekTo(startSeconds, true);
    }
}

function onPlayerStateChange(event) {
    let state = player.getPlayerState();
    if(interval) clearInterval(interval);

    if(state == YT.PlayerState.PLAYING){
        interval = setInterval(()=>{
            let current = player.getCurrentTime();
            let duration = player.getDuration();
            if(duration == 0) return;

            let progress = Math.floor((current/duration)*100);
            if(progress > 90 || player.getPlayerState() == YT.PlayerState.ENDED) progress = 100;

            let progressBar = document.getElementById('progressBar');
            progressBar.style.width = progress + '%';
            progressBar.textContent = progress + '%';

            if(progress - lastSent >= 10 || progress == 100){
                lastSent = progress;
                fetch('learn_update_progress.php', {
                    method:'POST',
                    headers:{'Content-Type':'application/json'},
                    body: JSON.stringify({lesson_ref: lessonRef, user_ref: userRef, progress: progress})
                });
            }

            if(progress == 100 && nextLessonRef){
                setTimeout(()=>window.location.href="index.php?p=learn_formation_module_lesson&ref="+nextLessonRef,1000);
            }

            if(progress == 100) clearInterval(interval);
        },1000);
    }
}
</script>
<?php elseif(count($pages) > 0): ?>
<script>
let pages = document.querySelectorAll('#lessonSlides .lesson-page');
let currentPage = 0;
let userRef = "<?= $user_ref ?>";
let lessonRef = "<?= $lesson['ref'] ?>";
let nextLessonRef = "<?= $nextLessonRef ?? '' ?>";
let progressBar = document.getElementById('progressBar');
let startstopBtn = document.getElementById('startstopBtn');
let isPlaying = false;
let synth = window.speechSynthesis;
let utter = null;
let lastSent = <?= $progress ?>;

// Wrap words in spans
function wrapWords(element){
    let text = element.textContent.trim();
    element.innerHTML = '';
    let words = text.split(/\s+/);
    words.forEach(word => {
        let span = document.createElement('span');
        span.textContent = word + ' ';
        element.appendChild(span);
    });
}

// Speak page text with highlight
function speakText(pEl){
    return new Promise(resolve => {
        if(!pEl) return resolve();
        if(synth.speaking) synth.cancel();

        let spans = pEl.querySelectorAll('span');
        if(spans.length === 0) wrapWords(pEl);
        spans = pEl.querySelectorAll('span');

        let fullText = pEl.textContent;
        let charIndex = 0;

        utter = new SpeechSynthesisUtterance(fullText);
        utter.lang = 'en-US';
        utter.rate = 1;

        utter.onboundary = function(event){
            charIndex = event.charIndex;
            let totalChars = 0;
            for(let i=0;i<spans.length;i++){
                totalChars += spans[i].textContent.length;
                if(totalChars >= charIndex){
                    spans.forEach(s => s.style.backgroundColor='');
                    spans[i].style.backgroundColor = 'yellow';
                    break;
                }
            }
        }

        utter.onend = function(){
            spans.forEach(s => s.style.backgroundColor='');
            resolve();
        }

        synth.speak(utter);
    });
}

// Show page
async function showPage(index){
    pages.forEach((p,i)=> p.style.display = i===index?'block':'none');

    let page = pages[index];
    let prog = Math.floor(((index+1)/pages.length)*100);
    progressBar.style.width = prog + '%';
    progressBar.textContent = prog + '%';

    // Update progress
    if(prog - lastSent >= 10 || prog==100){
        lastSent = prog;
        fetch('learn_update_progress.php', {
            method:'POST',
            headers:{'Content-Type':'application/json'},
            body: JSON.stringify({lesson_ref: lessonRef, user_ref: userRef, progress: prog})
        });
    }

    // Speak and wait if playing
    if(isPlaying){
        let pEl = page.querySelector('p');
        if(pEl){
            await speakText(pEl);
        }

        // Auto next
        if(isPlaying){
            currentPage++;
            if(currentPage < pages.length){
                showPage(currentPage);
            } else {
                isPlaying = false;
                startstopBtn.textContent = "▶ Play";
                if(nextLessonRef){
                    setTimeout(()=>window.location.href="index.php?p=learn_formation_module_lesson&ref="+nextLessonRef,1000);
                }
            }
        }
    }
}

// Manual next/back
function nextPage(){
    if(currentPage < pages.length-1){
        currentPage++;
        if(synth.speaking) synth.cancel();
        showPage(currentPage);
    }
}

function prevPage(){
    if(currentPage > 0){
        currentPage--;
        if(synth.speaking) synth.cancel();
        showPage(currentPage);
    }
}

// Start / stop
function startSlideshow(){
    if(isPlaying) return;
    isPlaying = true;
    startstopBtn.textContent = "⏸ Stop";
    showPage(currentPage);
}

function stopSlideshow(){
    isPlaying = false;
    startstopBtn.textContent = "▶ Play";
    if(synth.speaking) synth.cancel();
}

// Init
showPage(currentPage);

// Add buttons
let controls = document.createElement('div');
controls.style.marginTop = '15px';
controls.innerHTML = `
    <button id="prevBtn" class="btn btn-outline-secondary me-2">⬅ Previous</button>
    <button id="nextBtn" class="btn btn-outline-secondary">Next ➡</button>
`;
document.getElementById('lessonSlides').appendChild(controls);

document.getElementById('prevBtn').addEventListener('click', prevPage);
document.getElementById('nextBtn').addEventListener('click', nextPage);

startstopBtn.addEventListener('click', function(e){
    e.preventDefault();
    if(isPlaying) stopSlideshow();
    else startSlideshow();
});
</script>
<?php endif; ?>
