<?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'])      : '';
$type      = isset($data['type'])      ? (int)$data['type']       : 1; // 1=داخل, 0=خارج

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

// Validate year format (YYYY-MM-DD)
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $year)) {
    echo json_encode(['success' => false, 'message' => 'تاریخ کا فارمیٹ درست نہیں ہے']);
    exit;
}

// Madrasa config
$config      = $db->getRecordSet("SELECT * FROM config LIMIT 1");
$madrasaName = 'مدرسہ';
$madrasaAddr = '';
$madrasaAdr2 = '';
$elhaq       = '';
$regNumber   = '';

if ($config && count($config) > 0) {
    $c           = $config[0];
    $madrasaName = ($c['M_Name']   && $c['M_Name']   !== 'جامعہ کا نام یہاں لکھیں')   ? $c['M_Name']   : 'مدرسہ';
    $madrasaAddr = ($c['M_Address'] && $c['M_Address'] !== 'مزید پتہ یہاں لکھیں')       ? $c['M_Address'] : '';
    $madrasaAdr2 = ($c['L_Address'] && $c['L_Address'] !== 'مقامی پتہ یہاں لکھیں')      ? $c['L_Address'] : '';
    $elhaq       = $c['Elhaq']      ?? '';
    $regNumber   = $c['Reg_Number'] ?? '';
}

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

// Fetch students — isActive: 1=داخل, 0=خارج
$sql = "SELECT r.sno, r.stdName, r.fatherName, r.dob,
               r.stdNic, r.guirdianNic, r.formB,
               r.permanentAddress, r.presentAddress,
               r.cellNo, r.gurdianCellNo,
               r.guirdianNameAuth,
               n.RollNumber, n.registrationNo,
               std.promotionDate
        FROM registrationinfo r
        JOIN stddarjaat std ON std.stdSno = r.sno
        LEFT JOIN regnumbers n ON r.sno = n.regSno
        WHERE std.darja = ?
          AND std.promotionDate = ?
          AND r.isActive = ?
        ORDER BY r.stdName ASC";

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

if (!$students || count($students) === 0) {
    $typeLabel = $type === 1 ? 'داخل' : 'خارج';
    echo json_encode(['success' => false, 'message' => "سال {$year} میں درجہ {$darjaName} میں کوئی {$typeLabel} طالب علم نہیں ملا"]);
    exit;
}

// Format dob and determine NIC type
foreach ($students as &$s) {
    // Format date
    if (!empty($s['dob']) && $s['dob'] !== '0000-00-00') {
        try {
            $dob = new DateTime($s['dob']);
            $s['dob'] = $dob->format('d-m-Y');
        } catch (Exception $e) {
            $s['dob'] = '-';
        }
    } else {
        $s['dob'] = '-';
    }

    // NIC type and value
    if (!empty($s['stdNic']) && $s['stdNic'] !== '0') {
        $s['nicType']  = 'طالب';
        $s['nicValue'] = $s['stdNic'];
    } elseif (!empty($s['guirdianNic']) && $s['guirdianNic'] !== '0') {
        $s['nicType']  = 'والد';
        $s['nicValue'] = $s['guirdianNic'];
    } elseif (!empty($s['formB']) && $s['formB'] !== '0') {
        $s['nicType']  = 'فارم ب';
        $s['nicValue'] = $s['formB'];
    } else {
        $s['nicType']  = '-';
        $s['nicValue'] = '-';
    }

    // Phone (prefer student, fallback guardian)
    $s['phone'] = (!empty($s['cellNo'])) ? $s['cellNo'] : ($s['gurdianCellNo'] ?? '-');

    // Encrypt sno
    $s['sno'] = $met->encrypt_id($s['sno']);

    // Clean up raw fields
    unset($s['stdNic'], $s['guirdianNic'], $s['formB'], $s['cellNo'], $s['gurdianCellNo']);
}
unset($s);

echo json_encode([
    'success'     => true,
    'madrasaName' => $madrasaName,
    'madrasaAddr' => $madrasaAddr,
    'madrasaAdr2' => $madrasaAdr2,
    'elhaq'       => $elhaq,
    'regNumber'   => $regNumber,
    'darjaName'   => $darjaName,
    'year'        => $year,
    'type'        => $type,
    'students'    => $students,
]);
