<?php
header('Content-Type: application/json');
require_once('../libs/classes/DbPathsArray.php');
require_once('../libs/classes/App_DB.php');

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

$response = [
    'success' => false,
    'message' => '',
    'student' => null,
    'subjects' => [],
    'dates' => null
];

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $registrationNo = $_GET['registrationNo'] ?? '';
    $darja = $_GET['darja'] ?? '';

    if (empty($registrationNo) || empty($darja)) {
        $response['message'] = 'رجسٹریشن نمبر اور درجہ فراہم کریں';
        echo json_encode($response);
        exit;
    }

    try {
        // 1. Fetch Student Details - Using loose matching for registration number
        // This handles cases like '6', '000006', and potential '1445-1-000006'
        $sqlStd = "SELECT r.sno, reg.registrationNo, r.stdName, r.fatherName, st.promotionDate, st.dateEnd
                   FROM registrationinfo r
                   INNER JOIN regnumbers reg ON r.sno = reg.regSno
                   INNER JOIN stddarjaat st ON r.sno = st.stdSno
                   WHERE (reg.registrationNo = :regNo OR reg.registrationNo LIKE :regPattern)
                     AND st.darja = :darja 
                     AND st.isCurrent = 1 
                     AND r.isActive = 1";
        
        $student = $db->getRecordSet($sqlStd, [
            'regNo' => $registrationNo,
            'regPattern' => '%' . $registrationNo,
            'darja' => $darja
        ]);

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

        $stdData = $student[0];
        $response['student'] = [
            'sno' => $stdData['sno'],
            'registrationNo' => $stdData['registrationNo'],
            'stdName' => $stdData['stdName'],
            'fatherName' => $stdData['fatherName']
        ];
        $response['dates'] = [
            'promotionDate' => $stdData['promotionDate'],
            'dateEnd' => $stdData['dateEnd']
        ];

        // 2. Fetch Subjects for this Darja
        $sqlSubjects = "SELECT sno, subjectName, totalMarks FROM subjects WHERE darjaSno = :darja ORDER BY sno ASC";
        $subjects = $db->getRecordSet($sqlSubjects, ['darja' => $darja]);
        $response['subjects'] = $subjects;

        $response['success'] = true;

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

echo json_encode($response);
