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

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

    try {
        $sql = "SELECT r.sno, r.stdName, r.fatherName, r.dob, r.permanentAddress, 
                       std.promotionDate, n.RollNumber, n.registrationNo, 
                       d.darja as darjaName, d.derjaCode AS darjaSno, std.shoba_sno
                FROM registrationinfo r
                INNER JOIN regnumbers n ON r.sno = n.regSno
                INNER JOIN stddarjaat std ON r.sno = std.stdSno
                INNER JOIN darjaat d ON std.darja = d.derjaCode
                WHERE std.darja = :darja 
                  AND std.isCurrent = 1 
                  AND r.isActive = 1 
                  AND std.promotionDate = :pDate 
                  AND std.dateEnd = :eDate
                ORDER BY n.RollNumber ASC";

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

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

echo json_encode($response);
