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

if (!isset($_SESSION['userid'])) {
    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'] ?? '';
$year = $data['year'] ?? '';

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

// First, get the sessions (promotionDate and dateEnd) for this darja and year
$session_sql = "SELECT DISTINCT promotionDate, dateEnd 
                FROM stddarjaat 
                WHERE darja = :darja AND YEAR(promotionDate) = :year";
$sessions = $db->getRecordSet($session_sql, ['darja' => $darja, 'year' => $year]);

if (empty($sessions)) {
    echo json_encode(['success' => false, 'message' => 'No sessions found for this year']);
    exit();
}

// For simplicity, we assume there is typically one session per year per darja in this context, 
// or we fetch students from all matching sessions.
$students = [];
foreach ($sessions as $session) {
    $sql = "SELECT r.sno, CONCAT(r.stdName, ' ولدِ ', r.fatherName) as stdName, 
                   std.promotionDate, std.dateEnd
            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";

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

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