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

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);
$encrypted_sno = isset($data['sno']) ? $data['sno'] : '';
$sno = (int) $met->decrypt_id($encrypted_sno);

if (!$sno) {
    echo json_encode(['success' => false, 'message' => 'طالب علم کا انتخاب نہیں کیا گیا']);
    exit;
}

// 1. Fetch Madrasa Config
$config = $db->getRecordSet("SELECT * FROM config LIMIT 1");
$m_info = [
    'name' => 'مدرسہ',
    'address' => '',
    'addressL' => '',
    'elhaq' => '',
    'regNumber' => ''
];

if (!empty($config)) {
    $c = $config[0];
    $m_info['name'] = ($c['M_Name'] != "جامعہ کا نام یہاں لکھیں") ? $c['M_Name'] : "مدرسہ";
    $m_info['address'] = ($c['M_Address'] != "مزید پتہ یہاں لکھیں") ? $c['M_Address'] : "";
    $m_info['addressL'] = ($c['L_Address'] != "مقامی پتہ یہاں لکھیں" && $c['L_Address'] != "مزید پتہ یہاں لکھیں") ? $c['L_Address'] : "";
    $m_info['elhaq'] = $c['Elhaq'] ?? '';
    $m_info['regNumber'] = $c['Reg_Number'] ?? '';
}

// 2. Fetch Student Data (Joining registrationinfo, regnumbers, stddarjaat, darjaat, shobajaat)
$sql = "SELECT r.*, 
               reg.registrationNo, reg.RollNumber,
               st.darja as darjaSno, st.promotionDate, st.dateEnd, st.shoba_sno,
               d.darja as darjaName,
               sh.shoba as shobaName
        FROM registrationinfo r
        LEFT JOIN regnumbers reg ON r.sno = reg.regSno
        LEFT JOIN stddarjaat st ON r.sno = st.stdSno AND st.isCurrent = 1
        LEFT JOIN darjaat d ON st.darja = d.derjaCode
        LEFT JOIN shobajaat sh ON st.shoba_sno = sh.sno
        WHERE r.sno = ?
        LIMIT 1";

$studentData = $db->getRecordSet($sql, [$sno]);

if (empty($studentData)) {
    echo json_encode(['success' => false, 'message' => 'طالب علم کا ریکارڈ نہیں ملا']);
    exit;
}

$s = $studentData[0];

// Sanitize photo path
$photo = $s['stdPhoto'];
if (!$photo || !file_exists('../uploaded/' . $photo)) {
    $photo = 'default.png'; // Fallback if exists, or handled in JS
}

echo json_encode([
    'success' => true,
    'madrasa' => $m_info,
    'student' => [
        'sno' => $s['sno'],
        'stdName' => $s['stdName'],
        'fatherName' => $s['fatherName'],
        'nationality' => $s['nationality'] ?: 'پاکستانی',
        'dob' => $s['dob'],
        'qualification' => $s['qualification'],
        'guirdianName' => $s['guirdianName'],
        'cellNo' => $s['cellNo'],
        'fatherProfession' => $s['fatherProfession'],
        'gurdianCellNo' => $s['gurdianCellNo'],
        'permanentAddress' => $s['permanentAddress'],
        'presentAddress' => $s['presentAddress'],
        'guirdianNameAuth' => $s['guirdianNameAuth'],
        'guirdianFNameAuth' => $s['guirdianFNameAuth'],
        'stdNic' => $s['stdNic'],
        'guirdianNic' => $s['guirdianNic'],
        'formB' => $s['formB'],
        'relationWithGuirdian' => $s['relationShipWithGuirdian'],
        'admissionDate' => $s['promotionDate'],
        'dateEnd' => $s['dateEnd'],
        'admissionNo' => $s['admissionNo'],
        'RollNumber' => $s['RollNumber'],
        'registrationNo' => $s['registrationNo'],
        'photo' => $photo,
        'isLocal' => $s['isLocal'],
        'darjaName' => $s['darjaName'],
        'shobaName' => $s['shobaName'],
        'signNazim' => $s['signNazim']
    ]
]);
