<?php
require_once '../../../config.php';
$conn = getDBConnection();

$student_id = $_POST['student_id'] ?? 0;
$term = $_POST['term'] ?? '';
$academic_year = $_POST['academic_year'] ?? '';

// Get student's class
$stmt = $conn->prepare("SELECT class FROM students WHERE id = ?");
$stmt->bind_param("i", $student_id);
$stmt->execute();
$result = $stmt->get_result();
$student = $result->fetch_assoc();
$class_name = $student['class'];
$stmt->close();

// Get subjects configured for this class
$query = "
    SELECT cs.*, s.subject_name, s.subject_code 
    FROM class_subjects cs
    JOIN subjects s ON cs.subject_id = s.id
    WHERE cs.class_name = ?
    ORDER BY cs.display_order, s.subject_name
";

$stmt = $conn->prepare($query);
$stmt->bind_param("s", $class_name);
$stmt->execute();
$subjects = $stmt->get_result();
$stmt->close();

// Get existing scores
$scores = [];
$stmt = $conn->prepare("SELECT * FROM scores WHERE student_id = ? AND term = ? AND academic_year = ?");
$stmt->bind_param("iss", $student_id, $term, $academic_year);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    $scores[$row['subject_id']] = $row;
}
$stmt->close();

$conn->close();

// Generate subject cards
$output = '';

if ($subjects->num_rows === 0) {
    $output = '<div class="alert alert-warning">No subjects configured for this class. Please configure subjects first.</div>';
} else {
    while ($subject = $subjects->fetch_assoc()) {
        $score = $scores[$subject['subject_id']] ?? null;
        $raw_class = $score ? $score['raw_class_score'] : '';
        $raw_exam = $score ? $score['raw_exam_score'] : '';
        $weighted_class = $score ? $score['weighted_class_score'] : 0;
        $weighted_exam = $score ? $score['weighted_exam_score'] : 0;
        $total = $score ? $score['total_score'] : 0;
        $grade = $score ? $score['grade'] : 'W';
        $remark = $score ? $score['remark'] : 'Weak';
        
        $gradeClass = 'grade-w';
        if ($grade == 'A') $gradeClass = 'grade-a';
        elseif ($grade == 'B') $gradeClass = 'grade-b';
        elseif ($grade == 'C') $gradeClass = 'grade-c';
        elseif ($grade == 'D') $gradeClass = 'grade-d';
        elseif ($grade == 'E') $gradeClass = 'grade-e';
        
        $output .= '
        <div class="subject-score-card" data-subject-id="' . $subject['subject_id'] . '"
             data-max-class-score="' . $subject['max_class_score'] . '"
             data-max-exam-score="' . $subject['max_exam_score'] . '"
             data-class-score-percent="' . $subject['class_score_percent'] . '"
             data-exam-score-percent="' . $subject['exam_score_percent'] . '">
            <div class="subject-name">
                ' . htmlspecialchars($subject['subject_name']) . ' (' . htmlspecialchars($subject['subject_code']) . ')
                <span class="grade-badge ' . $gradeClass . '">' . $grade . '</span>
                <small class="subject-remark text-muted ms-2">' . $remark . '</small>
            </div>
            <div class="score-info mb-2">
                <small class="text-muted">
                    Weighting: Class ' . $subject['class_score_percent'] . '% (Max: ' . $subject['max_class_score'] . '), 
                    Exam ' . $subject['exam_score_percent'] . '% (Max: ' . $subject['max_exam_score'] . ')
                </small>
            </div>
            <div class="score-inputs">
                <div class="score-input">
                    <label>Class Score (Max: ' . $subject['max_class_score'] . ')</label>
                    <input type="number" class="class-score" value="' . $raw_class . '" 
                           min="0" max="' . $subject['max_class_score'] . '" step="0.01" 
                           onchange="calculateSubjectTotal(this)" 
                           placeholder="0-' . $subject['max_class_score'] . '">
                    <small class="text-muted d-block">Weighted: ' . round($weighted_class, 2) . '</small>
                </div>
                <div class="score-input">
                    <label>Exam Score (Max: ' . $subject['max_exam_score'] . ')</label>
                    <input type="number" class="exam-score" value="' . $raw_exam . '" 
                           min="0" max="' . $subject['max_exam_score'] . '" step="0.01" 
                           onchange="calculateSubjectTotal(this)" 
                           placeholder="0-' . $subject['max_exam_score'] . '">
                    <small class="text-muted d-block">Weighted: ' . round($weighted_exam, 2) . '</small>
                </div>
                <div class="score-total">
                    <span>Total: <strong class="subject-total">' . round($total, 2) . '</strong></span>
                    <br><small class="text-muted">(Weighted)</small>
                </div>
            </div>
        </div>';
    }
}

echo $output;