<?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'] ?? '';
    $promotionDate = $_GET['promotionDate'] ?? '';
    $dateEnd = $_GET['dateEnd'] ?? '';

    if (empty($darja) || empty($promotionDate) || empty($dateEnd)) {
        $response['message'] = 'تمام معلومات فراہم کریں';
        echo json_encode($response);
        exit;
    }

    try {
        // Query to fetch active students in the selected class and date range
        $sql = "SELECT rg.sno, rg.stdName, rg.fatherName, r.registrationNo
                FROM registrationinfo rg
                INNER JOIN stddarjaat std ON std.stdSno = rg.sno
                INNER JOIN regnumbers r ON rg.sno = r.regSno
                WHERE std.darja = :darja 
                  AND std.isCurrent = 1 
                  AND rg.isActive = 1 
                  AND YEAR(std.promotionDate) BETWEEN YEAR(:pDate) AND YEAR(:dEnd)
                ORDER BY rg.stdName ASC";

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

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

echo json_encode($response);