<?php
session_start();
require_once('../libs/classes/DbPathsArray.php');
require_once('../libs/classes/App_DB.php');

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

$db = new App_DB(DBU::$dba_user);
$data = json_decode(file_get_contents('php://input'), true);

$darja = $data['darja_sno'] ?? '';
$promotionDate = $data['date_start'] ?? '';
$dateEnd = $data['date_end'] ?? '';

if (empty($darja) || empty($promotionDate) || empty($dateEnd)) {
    echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
    exit();
}

$sql = "SELECT DISTINCT r.sno, CONCAT(r.stdName, ' ولدِ ', r.fatherName) as stdName 
        FROM registrationinfo r
        INNER JOIN stdDarjaat std ON std.stdSno = r.sno 
        WHERE std.darja = :darja 
          AND std.promotionDate = :start 
          AND std.dateEnd = :end 
          AND r.isActive = 1 
        ORDER BY r.stdName ASC";

$students = $db->getRecordSet($sql, [
    'darja' => $darja,
    'start' => $promotionDate,
    'end' => $dateEnd
]);

echo json_encode(['success' => true, 'students' => $students]);
