<?php
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/db.php';
$db = DB();

$students = $db->fetchAll("SELECT id, course_id, full_name FROM students WHERE approval_status = 'approved' ORDER BY RAND() LIMIT 8");

$count = 0;
foreach ($students as $s) {
    $sid = $s['id'];
    $cid = $s['course_id'];
    
    $subjects = $db->fetchAll("SELECT * FROM subjects WHERE course_id = ?", [$cid]);
    if (empty($subjects)) continue; // skip if no subjects configured

    $totalMax = 0;
    $totalObtained = 0;
    $isFail = false;

    foreach ($subjects as $sub) {
        $pass = $sub['pass_marks'];
        $max = $sub['max_marks'];
        $obtained = rand($pass + 2, $max - 5);

        if ($obtained > $max) $obtained = $max;
        if ($obtained < $pass) $isFail = true;

        $totalMax += $max;
        $totalObtained += $obtained;

        $db->query("INSERT INTO marks_entry (student_id, subject_id, obtained_marks) 
                    VALUES (?, ?, ?) 
                    ON DUPLICATE KEY UPDATE obtained_marks = ?", 
                    [$sid, $sub['id'], $obtained, $obtained]);
    }

    $percentage = ($totalMax > 0) ? ($totalObtained / $totalMax) * 100 : 0;
    $division = 'Fail';
    if (!$isFail) {
        if ($percentage >= 60) $division = '1st Division';
        elseif ($percentage >= 45) $division = '2nd Division';
        elseif ($percentage >= 33) $division = '3rd Division';
    } else {
        $division = 'FAIL';
    }

    $db->update('students', [
        'marks_obtained' => $totalObtained,
        'total_marks' => $totalMax,
        'percentage' => $percentage,
        'division' => $division,
        'result_declared' => 1,
        'status' => ($division == 'FAIL') ? 'failed' : 'passed'
    ], ['id' => $sid]);
    
    $count++;
}
echo "Marks repopulated for $count students.\n";
