<?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);
$crud = $db; // required by configuration.php to load constants from DB

require_once('../includes/configuration.php');

$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);

$darjaSno = (int) ($input['darja_sno'] ?? 0);
$dateStart = trim($input['date_start'] ?? '');
$dateEnd = trim($input['date_end'] ?? '');

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

// Validate year format
if (!preg_match('/^\d{4}$/', $dateStart) || !preg_match('/^\d{4}$/', $dateEnd)) {
    $response['message'] = 'سال کی درست قدر فراہم کریں';
    echo json_encode($response);
    exit;
}

try {
    // Get darja name
    $darjaSql = "SELECT darja FROM darjaat WHERE derjaCode = :code LIMIT 1";
    $darjaRows = $db->getRecordSet($darjaSql, ['code' => $darjaSno]);
    $darjaName = $darjaRows[0]['darja'] ?? '';

    // Get students
    $sql = "SELECT DISTINCT
                r.stdName,
                r.fatherName,
                r.dob,
                r.permanentAddress,
                r.cellNo,
                n.RollNumber,
                n.registrationNo,
                std.promotionDate
            FROM registrationinfo r
            JOIN regnumbers n    ON n.regSno = r.sno
            JOIN stddarjaat std  ON std.stdSno = r.sno
            WHERE r.isActive = 1
              AND std.darja = :darja
              AND YEAR(std.promotionDate) BETWEEN :dateStart AND :dateEnd
            ORDER BY CAST(n.RollNumber AS SIGNED) ASC";

    $rows = $db->getRecordSet($sql, [
        'darja' => $darjaSno,
        'dateStart' => (int) $dateStart,
        'dateEnd' => (int) $dateEnd,
    ]);

    if (empty($rows)) {
        $response['message'] = 'اس درجہ اور مدت میں کوئی طالب علم نہیں ملا';
        echo json_encode($response);
        exit;
    }

    // Format dates for output
    $students = [];
    foreach ($rows as $row) {
        $dob = $row['dob'] ? (new DateTime($row['dob']))->format('d-m-Y') : '-';
        $admission = $row['promotionDate'] ? (new DateTime($row['promotionDate']))->format('d-m-Y') : '-';
        $students[] = [
            'stdName' => htmlspecialchars($row['stdName']),
            'fatherName' => htmlspecialchars($row['fatherName']),
            'dob' => $dob,
            'address' => htmlspecialchars($row['permanentAddress']),
            'cell' => htmlspecialchars($row['cellNo']),
            'rollNo' => htmlspecialchars($row['RollNumber']),
            'registrationNo' => htmlspecialchars($row['registrationNo']),
            'admissionDate' => $admission,
        ];
    }

    $response['success'] = true;
    $response['data'] = $students;
    $response['darjaName'] = htmlspecialchars($darjaName);

    // Read madrasa name & address directly from config table
    $configRow = $db->getRecordSet("SELECT M_Name, M_Address FROM config LIMIT 1");
    $response['madrasaName'] = htmlspecialchars($configRow[0]['M_Name'] ?? '');
    $response['madrasaAddress'] = htmlspecialchars($configRow[0]['M_Address'] ?? '');

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

echo json_encode($response);
