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

$student_id = $_POST['student_id'] ?? 0;
$subject_id = $_POST['subject_id'] ?? 0;
$raw_class_score = floatval($_POST['class_score'] ?? 0);
$raw_exam_score = floatval($_POST['exam_score'] ?? 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 class-subject configuration
$stmt = $conn->prepare("
    SELECT * FROM class_subjects 
    WHERE class_name = ? AND subject_id = ?
");
$stmt->bind_param("si", $class_name, $subject_id);
$stmt->execute();
$result = $stmt->get_result();
$config = $result->fetch_assoc();
$stmt->close();

if (!$config) {
    // Use default configuration if not set
    $class_score_percent = 50;
    $exam_score_percent = 50;
    $max_class_score = 50;
    $max_exam_score = 50;
} else {
    $class_score_percent = $config['class_score_percent'];
    $exam_score_percent = $config['exam_score_percent'];
    $max_class_score = $config['max_class_score'];
    $max_exam_score = $config['max_exam_score'];
}

// Validate raw scores against the configured maximums BEFORE calculating
// weighted scores. Without this check, a raw score entered above its max
// (e.g. 59 entered where max_class_score = 50) gets divided/multiplied back
// to itself, silently producing a "weighted" score that's really just the
// raw number, and a total that can exceed 100%.
$errors = [];
if ($max_class_score <= 0 || $max_exam_score <= 0) {
    $conn->close();
    echo json_encode([
        'success' => false,
        'message' => 'This subject is misconfigured (max score is 0). Please fix the class-subject settings before entering scores.'
    ]);
    exit;
}
if ($raw_class_score < 0 || $raw_class_score > $max_class_score) {
    $errors[] = "Class score must be between 0 and {$max_class_score}";
}
if ($raw_exam_score < 0 || $raw_exam_score > $max_exam_score) {
    $errors[] = "Exam score must be between 0 and {$max_exam_score}";
}
if (!empty($errors)) {
    $conn->close();
    echo json_encode([
        'success' => false,
        'message' => implode('. ', $errors)
    ]);
    exit;
}

// Calculate weighted scores (convert to percentage of the max)
$weighted_class_score = ($raw_class_score / $max_class_score) * $class_score_percent;
$weighted_exam_score = ($raw_exam_score / $max_exam_score) * $exam_score_percent;
$total_score = $weighted_class_score + $weighted_exam_score;

// Get grade boundaries for this class
$stmt = $conn->prepare("
    SELECT * FROM grade_boundaries 
    WHERE class_name IN (?, 'ALL')
    ORDER BY min_score DESC
");
$stmt->bind_param("s", $class_name);
$stmt->execute();
$result = $stmt->get_result();

$grade = 'W';
$remark = 'Weak';
while ($row = $result->fetch_assoc()) {
    if ($total_score >= $row['min_score'] && $total_score <= $row['max_score']) {
        $grade = $row['grade'];
        $remark = $row['remark'];
        break;
    }
}
$stmt->close();

// Check if score exists
$stmt = $conn->prepare("SELECT id FROM scores WHERE student_id = ? AND subject_id = ? AND term = ? AND academic_year = ?");
$stmt->bind_param("iiss", $student_id, $subject_id, $term, $academic_year);
$stmt->execute();
$result = $stmt->get_result();
$exists = $result->num_rows > 0;
$stmt->close();

if ($exists) {
    // Update. class_name is refreshed too so rows written before the column
    // existed get stamped the next time a score is touched.
    $stmt = $conn->prepare("
        UPDATE scores
        SET raw_class_score = ?, raw_exam_score = ?,
            weighted_class_score = ?, weighted_exam_score = ?,
            total_score = ?, grade = ?, remark = ?, class_name = ?
        WHERE student_id = ? AND subject_id = ? AND term = ? AND academic_year = ?
    ");
    $stmt->bind_param("ddddssssiiss",
        $raw_class_score, $raw_exam_score,
        $weighted_class_score, $weighted_exam_score,
        $total_score, $grade, $remark, $class_name,
        $student_id, $subject_id, $term, $academic_year
    );
} else {
    // Insert
    $stmt = $conn->prepare("
        INSERT INTO scores (
            student_id, subject_id, class_name,
            raw_class_score, raw_exam_score,
            weighted_class_score, weighted_exam_score,
            total_score, grade, remark, term, academic_year
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");
    $stmt->bind_param("iisddddsssss",
        $student_id, $subject_id, $class_name,
        $raw_class_score, $raw_exam_score,
        $weighted_class_score, $weighted_exam_score,
        $total_score, $grade, $remark, $term, $academic_year
    );
}

$stmt->execute();
$stmt->close();
$conn->close();

echo json_encode([
    'success' => true, 
    'total' => round($total_score, 2),
    'weighted_class' => round($weighted_class_score, 2),
    'weighted_exam' => round($weighted_exam_score, 2),
    'grade' => $grade, 
    'remark' => $remark
]);