<?php
ob_start();
header('Content-Type: application/json');

require_once("../../includes/config.php");
require_once("../../includes/auth_check.php");

$class_id   = filter_input(INPUT_GET, 'class_id', FILTER_VALIDATE_INT);
$section_id = filter_input(INPUT_GET, 'section_id', FILTER_VALIDATE_INT);
$term_id    = filter_input(INPUT_GET, 'term_id', FILTER_VALIDATE_INT);
$medium_id  = filter_input(INPUT_GET, 'medium_id', FILTER_VALIDATE_INT); 

if (!$class_id || !$term_id || !$medium_id || APP_YEAR_ID == 0) {
    ob_clean();
    echo json_encode(['status' => 'error', 'message' => 'Missing required filters']);
    exit;
}

try {
    /* 1️⃣ FETCH METADATA */
    $stmtMed = $pdo->prepare("SELECT medium_name FROM mediums WHERE id = ?");
    $stmtMed->execute([$medium_id]);
    $medium_name = $stmtMed->fetchColumn() ?: '';

    $stmtClass = $pdo->prepare("SELECT class_name FROM classes WHERE id = ?");
    $stmtClass->execute([$class_id]);
    $class_name = $stmtClass->fetchColumn() ?: '';

    /* 2️⃣ SUBJECTS */
    $stmtSub = $pdo->prepare("SELECT id, subject_name FROM subjects WHERE class_id = ? ORDER BY id ASC");
    $stmtSub->execute([$class_id]);
    $subjects = $stmtSub->fetchAll(PDO::FETCH_ASSOC);

    /* 3️⃣ EXAM TERM MAX & PASS LOGIC */
    $stmtTerm = $pdo->prepare("SELECT term_name, max_marks FROM exam_terms WHERE id = ?");
    $stmtTerm->execute([$term_id]);
    $term_data = $stmtTerm->fetch(PDO::FETCH_ASSOC);
    
    $term_max = (int)($term_data['max_marks'] ?? 100);
    $isAnnual = ($term_max === 100);
    
    // Logic: Pass mark is strictly 30% of the Exam Max (e.g., 7.5 for 25, 30 for 100)
    $pass_threshold = $term_max * 0.3;

    /* 4️⃣ STUDENT + MARKS */
    $sectionFilter = ($section_id && $section_id > 0) ? " AND e.section_id = :section " : "";
    $sql = "
        SELECT s.id AS student_id, e.roll_no, s.student_name, s.father_name, sub.id AS subject_id,
               IFNULL(m.theory_marks, 0) AS theory_marks, IFNULL(m.practical_marks, 0) AS practical_marks
        FROM enrollments e
        INNER JOIN students s ON s.id = e.student_id
        INNER JOIN subjects sub ON sub.class_id = e.class_id 
        LEFT JOIN marks_entry m ON m.student_id = s.id AND m.subject_id = sub.id
            AND m.exam_term_id = :term AND m.academic_year_id = :year
        WHERE e.class_id = :class AND e.medium_id = :medium $sectionFilter
            AND e.academic_year_id = :year AND s.status = 1
        ORDER BY CAST(e.roll_no AS UNSIGNED) ASC";

    $stmt = $pdo->prepare($sql);
    $params = [':term' => $term_id, ':year' => APP_YEAR_ID, ':class' => $class_id, ':medium' => $medium_id];
    if ($section_id > 0) $params[':section'] = $section_id;
    $stmt->execute($params);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    /* 5️⃣ MATRIX BUILDING & SUBJECT-WISE PASS CHECK */
    $students = [];
    foreach ($rows as $row) {
        $sid = $row['student_id'];
        if (!isset($students[$sid])) {
            $students[$sid] = [
                'sid' => $sid, 'roll' => $row['roll_no'], 'name' => $row['student_name'],
                'father_name' => $row['father_name'], 'marks' => new stdClass(),
                'grand_total' => 0, 'percentage' => 0,
                'is_failed_any' => false, // New flag for subject-wise failure
                'result_division' => 'Failed', 'honors_badge' => ''
            ];
        }

        $tot = (float)$row['theory_marks'] + (float)$row['practical_marks'];
        
        // Mark student as failed if ANY subject is below 30%
        if ($tot < $pass_threshold) {
            $students[$sid]['is_failed_any'] = true;
        }

        $l_label = ($isAnnual && ($tot >= 80)) ? " (L)" : "";

        $students[$sid]['marks']->{$row['subject_id']} = [
            'th' => $row['theory_marks'], 'pr' => $row['practical_marks'], 'tot' => $tot,
            'is_pass' => ($tot >= $pass_threshold),
            'display_tot' => (int)$tot . $l_label
        ];
        $students[$sid]['grand_total'] += $tot;
    }

    /* 6️⃣ FINAL DIVISION & HONORS CALCULATION */
    $totalPossible = count($subjects) * $term_max;

    foreach ($students as &$st) {
        $perc = ($totalPossible > 0) ? ($st['grand_total'] / $totalPossible) * 100 : 0;
        $st['percentage'] = round($perc, 2);

        // ONLY calculate Division/Honors if they passed EVERY subject
        if ($st['is_failed_any'] === false) {
            if ($perc >= 60) $st['result_division'] = "1st Division";
            elseif ($perc >= 45) $st['result_division'] = "2nd Division";
            elseif ($perc >= 30) $st['result_division'] = "3rd Division";
            else $st['result_division'] = "Failed";

            // Honors ONLY if Annual (100 marks) AND Passed all subjects
            if ($isAnnual) {
                if ($perc >= 95) $st['honors_badge'] = "STAND MARK";
                elseif ($perc >= 85) $st['honors_badge'] = "DISTINCTION";
                elseif ($perc >= 75) $st['honors_badge'] = "STAR MARK";
            }
        } else {
            $st['result_division'] = "FAILED";
            $st['honors_badge'] = ""; // Disqualified from honors
        }
    }

    /* 7️⃣ RESPONSE */
    ob_clean();
    echo json_encode([
        'status' => 'success',
        'term_max' => $term_max,
        'pass_threshold' => $pass_threshold,
        'is_annual' => $isAnnual,
        'subjects' => $subjects,
        'students' => array_values($students)
    ]);

} catch (PDOException $e) {
    ob_clean();
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}?>