<?php
session_start();
require_once 'config.php';

header('Content-Type: application/json');

if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$activity_id = $_POST['activity_id'] ?? 0;
$stream_id = $_POST['stream_id'] ?? 0;
$subject_id = $_POST['subject_id'] ?? 0;
$school_id = $_POST['school_id'] ?? 0;

if ($activity_id == 0 || $stream_id == 0 || $subject_id == 0 || $school_id == 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid parameters']);
    exit;
}

try {
    // Get all students in this stream
    $sql = "SELECT 
                u.id as user_id,
                u.username,
                iam.marks as current_mark
            FROM users u
            LEFT JOIN integration_activity_marks iam ON u.id = iam.student_id AND iam.activity_id = ?
            WHERE u.stream_id = ? AND u.school_id = ? AND u.role = 3
            ORDER BY u.username";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("iii", $activity_id, $stream_id, $school_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $students = [];
    while ($row = $result->fetch_assoc()) {
        $students[] = $row;
    }
    
    echo json_encode(['success' => true, 'students' => $students]);
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>