<?php
header('Content-Type: application/json');
require_once('../libs/classes/DbPathsArray.php');
require_once('../libs/classes/App_DB.php');

$db = new App_DB(DBU::$dba_user);

$response = [
    'success' => false,
    'message' => '',
    'students' => []
];

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $darja = $_GET['darja'] ?? '';
    $year = $_GET['year'] ?? ''; // Expecting YYYY-MM-DD or just a year that matches YEAR() check

    if (empty($darja) || empty($year)) {
        $response['message'] = 'درجہ اور سال فراہم کریں';
        echo json_encode($response);
        exit;
    }

    try {
        // Query to fetch active students with more details (Roll No, Reg No, Address)
        $sql = "SELECT rg.sno, rg.stdName, rg.fatherName, rg.dob, rg.permanentAddress,
                       n.RollNumber, n.registrationNo, d.darja as darjaName, d.derjaCode as darjaSno
                FROM registrationinfo rg
                INNER JOIN regnumbers n ON rg.sno = n.regSno
                INNER JOIN stddarjaat std ON rg.sno = std.stdSno
                INNER JOIN darjaat d ON std.darja = d.derjaCode
                WHERE std.darja = :darja 
                  AND std.isCurrent = 1 
                  AND rg.isActive = 1
                  AND YEAR(std.promotionDate) = YEAR(:year)
                ORDER BY n.RollNumber ASC";

        $students = $db->getRecordSet($sql, [
            'darja' => $darja,
            'year' => $year
        ]);

        if (!empty($students)) {
            $response['success'] = true;
            $response['students'] = $students;
        }
        else {
            $response['message'] = 'اس درجہ اور سال میں کوئی طالب علم نہیں ملا';
        }
    }
    catch (Exception $e) {
        $response['message'] = 'ڈیٹابیس کی خرابی: ' . $e->getMessage();
    }
}

echo json_encode($response);