<?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');

// Auth guard
if (!isset($_SESSION['userid'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$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;
$year      = isset($data['year'])      ? trim($data['year'])      : '';
$exam_type = isset($data['exam_type']) ? (int)$data['exam_type']  : 0;

if (!$darja_sno || !$year) {
    echo json_encode(['success' => false, 'message' => 'برائے مہربانی درجہ اور سال مہیا کریں']);
    exit;
}

// Extract year for query (assuming year is YYYY-MM-DD or just YYYY)
$yearParts = explode('-', $year);
$yearOnly  = $yearParts[0];

// Madrasa config
$config      = $db->getRecordSet("SELECT * FROM config LIMIT 1");
$madrasaName = 'مدرسہ';
if ($config && count($config) > 0) {
    $c           = $config[0];
    $madrasaName = ($c['M_Name'] && $c['M_Name'] !== 'جامعہ کا نام یہاں لکھیں') ? $c['M_Name'] : 'مدرسہ';
}

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

// Exam name
$examNames = [
    1 => 'سہ ماہی',
    2 => 'ششماہی',
    3 => 'سالانہ'
];
$examName = $examNames[$exam_type] ?? 'امتحان';

// Fetch students
// Note: The original query used registrationDate or promotionDate range. 
// Based on the original page: std.promotionDate between '$date' AND '$endDate'
// I'll use the year provided and search within that year's promotion dates.
$sql = "SELECT r.sno, r.stdName, r.fatherName 
        FROM registrationinfo r
        JOIN stddarjaat std ON std.stdSno = r.sno
        WHERE YEAR(std.promotionDate) = ?
          AND std.darja = ?
          AND r.isActive = 1
          AND std.isCurrent = 1
        ORDER BY r.stdName ASC";

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

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

echo json_encode([
    'success'     => true,
    'madrasaName' => $madrasaName,
    'darjaName'   => $darjaName,
    'year'        => $yearOnly,
    'examName'    => $examName,
    'students'    => $students,
]);
