<?php
header('Content-Type: application/json');
include('last_db_config.php');

$response = [
    'evaluated'    => 0,
    'notEvaluated' => 0,
    'absentCount'  => 0,
    'options'      => []
];

if (isset($_POST['SchoolID'], $_POST['Class']) && $_POST['SchoolID'] !== '' && $_POST['Class'] !== '') {
    $school_id = $_POST['SchoolID'];
    $class     = $_POST['Class'];

    // 1) Count evaluated students (present only)
    $res1 = mysqli_query($conn, "
      SELECT COUNT(DISTINCT t.StudentID) AS cnt
      FROM testresult t
      JOIN student s ON s.StudentID = t.StudentID
      WHERE s.SchoolID='$school_id' AND s.Class='$class' AND s.absent = 0
    ");
    $row1 = mysqli_fetch_assoc($res1) ?: ['cnt'=>0];
    $response['evaluated'] = intval($row1['cnt']);

    // 2) Count absent students for this class
    $resAbsent = mysqli_query($conn, "
      SELECT COUNT(*) AS cnt
      FROM student s
      WHERE s.SchoolID='$school_id' AND s.Class='$class' AND s.absent = 1
    ");
    $rowAbsent = mysqli_fetch_assoc($resAbsent) ?: ['cnt'=>0];
    $response['absentCount'] = intval($rowAbsent['cnt']);

    // 3) Get students NOT evaluated AND NOT absent (students who need evaluation)
    $res2 = mysqli_query($conn, "
      SELECT s.StudentID, s.Name
      FROM student s
      LEFT JOIN testresult t ON s.StudentID = t.StudentID
      WHERE s.SchoolID='$school_id' AND s.Class='$class' 
      AND t.StudentID IS NULL 
      AND s.evaluated = 0
      AND (s.absent = 0 OR s.absent IS NULL)
      ORDER BY s.Name
    ");
    $not = [];
    while ($r = mysqli_fetch_assoc($res2)) {
        $not[] = ['StudentID'=>$r['StudentID'],'Name'=>$r['Name']];
    }
    $response['notEvaluated'] = count($not);
    $response['options']      = $not;
}

echo json_encode($response);
?>