<?php
header('Content-Type: application/json; charset=utf-8');
session_start();
require_once('../libs/classes/DbPathsArray.php');
require_once('../libs/classes/App_DB.php');
require_once('../libs/classes/MyMethods.php');

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

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

$darja_sno = isset($data['darja_sno']) ? (int) $data['darja_sno'] : 0;
$date_start = isset($data['date_start']) ? $data['date_start'] : '';
$date_end = isset($data['date_end']) ? $data['date_end'] : '';

if (!$darja_sno || !$date_start || !$date_end) {
    echo json_encode(['success' => false, 'message' => 'نامکمل پیرامیٹرز']);
    exit;
}

// Fetch Madrasa Config
$config = $db->getRecordSet("SELECT * FROM config LIMIT 1");
$madrasaName = "مدرسہ";
$madrasaAddress = "";
$madrasaAddressL = "";
$madrasaPhone = "";

if ($config && count($config) > 0) {
    $c = $config[0];
    $madrasaName = ($c['M_Name'] && $c['M_Name'] != "جامعہ کا نام یہاں لکھیں") ? $c['M_Name'] : "مدرسہ";
    $madrasaAddress = ($c['M_Address'] && $c['M_Address'] != "مزید پتہ یہاں لکھیں") ? $c['M_Address'] : "";
    $madrasaAddressL = ($c['L_Address'] && $c['L_Address'] != "مقامی پتہ یہاں لکھیں" && $c['L_Address'] != "مزید پتہ یہاں لکھیں") ? $c['L_Address'] : "";
    $madrasaPhone = $c['P_Number'];
}

// Fetch Darja Name
$darjaData = $db->getRecordSet("SELECT darja FROM darjaat WHERE derjaCode = ?", [$darja_sno]);
$darjaName = ($darjaData && count($darjaData) > 0) ? $darjaData[0]['darja'] : 'نامعلوم';

// Fetch Registered Students
$sql = "SELECT r.sno, r.stdName, r.fatherName, r.dob, r.permanentAddress, std.promotionDate, r.cellNo,
               n.RollNumber, n.registrationNo, d.darja 
        FROM registrationinfo r
        JOIN regnumbers n ON r.sno = n.regSno
        JOIN stddarjaat std ON std.stdSno = r.sno
        JOIN darjaat d ON std.darja = d.derjaCode
        WHERE std.darja = ? 
          AND std.promotionDate BETWEEN ? AND ? 
          AND std.isCurrent = 1 
          AND r.isActive = 1 
        ORDER BY n.RollNumber ASC";

$students = $db->getRecordSet($sql, [$darja_sno, $date_start, $date_end]);

if ($students) {
    foreach ($students as &$s) {
        $s['sno'] = $met->encrypt_id($s['sno']);
    }
}

if (!$students || count($students) === 0) {
    echo json_encode(['success' => false, 'message' => 'اس عرصہ میں کوئی طالب علم نہیں ملا']);
    exit;
}

echo json_encode([
    'success' => true,
    'madrasaName' => $madrasaName,
    'madrasaAddress' => $madrasaAddress,
    'madrasaAddressL' => $madrasaAddressL,
    'madrasaPhone' => $madrasaPhone,
    'darjaName' => $darjaName,
    'dateStart' => $date_start,
    'dateEnd' => $date_end,
    'students' => $students
]);
