<?php
session_start();
require_once '../includes/access_control.php';
require_once '../config/database.php';

if (!isset($_SESSION['user_id'])) { echo json_encode(['count' => 0]); exit; }

header('Content-Type: application/json; charset=utf-8');

$class_id = (int)($_GET['class_id'] ?? 0);
$session  = trim($_GET['session'] ?? '');

if (!$class_id) { echo json_encode(['count' => 0]); exit; }

$sql = "SELECT COUNT(*) FROM students WHERE class_id = ? AND (branch_id IS NULL OR branch_id = 0) AND status = 'active'";
$params = [$class_id];

if ($session !== '') {
    $sql .= ' AND session = ?';
    $params[] = $session;
}

$count = $pdo->prepare($sql);
$count->execute($params);
echo json_encode(['count' => (int)$count->fetchColumn()], JSON_UNESCAPED_UNICODE);
