<?php
if (!defined('ENGLISHSPEAK')) {
    define('ENGLISHSPEAK', true);
}

/**
 * Lấy Lesson học tiếp theo của học sinh
 * Nếu tất cả lesson hoàn thành thì trả lesson cuối để ôn lại
 */
function getCurrentLesson(mysqli $conn, int $student_id)
{
    // Lesson chưa hoàn thành
    $sql = "
        SELECT
            l.id,
            l.title,
            l.unit_id,
            u.title AS unit_title,
            lv.id AS level_id,
            b.id AS book_id
        FROM lessons l
        JOIN units u ON u.id=l.unit_id
        JOIN levels lv ON lv.id=u.level_id
        JOIN books b ON b.id=lv.book_id
        LEFT JOIN student_lesson_progress slp
            ON slp.lesson_id=l.id
            AND slp.student_id=?
        WHERE IFNULL(slp.status,'')<>'completed'
        ORDER BY
            b.sort_order,
            lv.sort_order,
            u.sort_order,
            l.sort_order
        LIMIT 1
    ";

    $stmt=$conn->prepare($sql);
    $stmt->bind_param("i",$student_id);
    $stmt->execute();

    $lesson=$stmt->get_result()->fetch_assoc();

    if($lesson){
        return $lesson;
    }

    // Nếu hoàn thành hết
    $sql="
        SELECT
            l.id,
            l.title,
            l.unit_id,
            u.title AS unit_title,
            lv.id ASlevel_id,
            b.id AS book_id
        FROM lessons l
        JOIN units u ON u.id=l.unit_id
        JOIN levels lv ON lv.id=u.level_id
        JOIN books b ON b.id=lv.book_id
        ORDER BY
            b.sort_order DESC,
            lv.sort_order DESC,
            u.sort_order DESC,
            l.sort_order DESC
        LIMIT 1
    ";

    return $conn->query($sql)->fetch_assoc();
}


/**
 * Tính % hoàn thành Lesson
 */
function getLessonProgress(mysqli $conn,int $student_id,int $lesson_id)
{
    $sql="
        SELECT
            COUNT(*) total,
            SUM(status='completed') done
        FROM student_content_progress
        WHERE
            student_id=?
            AND lesson_id=?
            AND content_type='activity'
    ";

    $stmt=$conn->prepare($sql);
    $stmt->bind_param("ii",$student_id,$lesson_id);
    $stmt->execute();

    $r=$stmt->get_result()->fetch_assoc();

    if(!$r['total']){
        return 0;
    }

    return round($r['done']*100/$r['total']);
}