<?php
header('Content-Type: application/json');
header('X-Content-Type-Options: nosniff');

session_start();
if (!isset($_SESSION['userid']) || empty($_SESSION['key'])) {
    echo json_encode(['success' => false, 'message' => 'غیر مجاز رسائی']);
    exit;
}

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

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

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $response['message'] = 'صرف POST درخواست قبول ہوتی ہے';
    echo json_encode($response);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);

$darja = (int) ($input['darja'] ?? 0);
$pDate = trim($input['promotionDate'] ?? '');
$dEnd = trim($input['dateEnd'] ?? '');

if (!$darja || empty($pDate) || empty($dEnd)) {
    $response['message'] = 'برائے مہربانی تمام معلومات فراہم کریں';
    echo json_encode($response);
    exit;
}

try {
    $sql = "SELECT r.sno, CONCAT(r.stdName ,' ولدِ ', r.fatherName) as stdFullName 
            FROM registrationinfo r
            JOIN stddarjaat std ON std.stdSno = r.sno 
            WHERE std.darja = :darja 
              AND std.promotionDate = :pDate 
              AND std.dateEnd = :dEnd 
              AND r.isActive = 1
            ORDER BY r.stdName ASC";

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

    $students = [];
    foreach ($rows as $row) {
        $students[] = [
            'sno' => $row['sno'],
            'name' => htmlspecialchars($row['stdFullName'])
        ];
    }

    $response['success'] = true;
    $response['data'] = $students;

} catch (Exception $e) {
    $response['message'] = 'ڈیٹابیس میں خرابی: ' . $e->getMessage();
}

echo json_encode($response);
