<?php
include("../includes/db.php");

$class_id = $_POST['class_id'] ?? '';
$section_id = $_POST['section_id'] ?? '';
$exam_id = $_POST['exam_id'] ?? '';
$subject_id = $_POST['subject_id'] ?? '';
$mark_type = $_POST['mark_type'] ?? '';

if (!$class_id || !$section_id || !$exam_id || !$subject_id || !$mark_type) {
    echo json_encode(['success' => false, 'message' => 'Missing parameters']);
    exit;
}

// Get class, section, subject, exam info
$info_query = "SELECT 
                c.class,
                sec.section_name,
                sub.subject_name,
                et.exam_type,
                et.exm_year
               FROM classes c
               JOIN sections sec ON 1=1
               JOIN subjects sub ON 1=1
               JOIN examination_type et ON 1=1
               WHERE c.class_id = ? 
                 AND sec.section_id = ?
                 AND sub.id = ?
                 AND et.id = ?";
$info_stmt = $conn->prepare($info_query);
$info_stmt->bind_param("iiii", $class_id, $section_id, $subject_id, $exam_id);
$info_stmt->execute();
$info_result = $info_stmt->get_result();
$info = $info_result->fetch_assoc();
$info_stmt->close();

// Get marks data
$query = "SELECT 
            m.id, 
            m.student_id,
            s.name as student_name,
            s.symbol_no,
            m.full_marks,
            m.marks,
            t1.name as entered_by_name,
            t2.name as updated_by_name,
            DATE_FORMAT(m.created_at, '%Y-%m-%d') as created_at,
            DATE_FORMAT(m.updated_at, '%Y-%m-%d %H:%i') as updated_at
          FROM marks m
          LEFT JOIN students s ON m.student_id = s.student_id
          LEFT JOIN teachers t1 ON m.entered_by = t1.teacher_id
          LEFT JOIN teachers t2 ON m.updated_by = t2.teacher_id
          WHERE m.class_id = ? 
            AND m.section_id = ? 
            AND m.exam_type = ? 
            AND m.subject_id = ? 
            AND m.mark_type = ?
          ORDER BY s.name";

$stmt = $conn->prepare($query);
$stmt->bind_param("iiiss", $class_id, $section_id, $exam_id, $subject_id, $mark_type);
$stmt->execute();
$result = $stmt->get_result();
$marks = $result->fetch_all(MYSQLI_ASSOC);
$stmt->close();

$response = [
    'success' => true,
    'info' => [
        'class' => $info['class'] ?? 'N/A',
        'section' => $info['section_name'] ?? 'N/A',
        'subject' => $info['subject_name'] ?? 'N/A',
        'exam' => ($info['exam_type'] ?? 'N/A') . ' (' . ($info['exm_year'] ?? 'N/A') . ')',
        'mark_type' => $mark_type
    ],
    'marks' => $marks
];

echo json_encode($response);
?>