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

$db = new App_DB(DBU::$dba_user);
$method = new MyMethods();
$hijri = new Hijri_GregorianConvert();

$crud = $db;
require_once('../includes/configuration.php');

$response = [
    'success' => false,
    'message' => '',
    'data' => [],
    'p_number' => P_Number,
    'm_name' => M_Name,
    'm_address' => M_Address,
    'e_address' => E_Address,
    'reg_number' => Reg_Number
];

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

    if (empty($darja) || empty($fromDat) || empty($toDate)) {
        $response['message'] = 'درجہ اور تاریخوں کا ہونا ضروری ہے';
        echo json_encode($response);
        exit;
    }

    $sql = "SELECT DISTINCT r.stdName, reg.RollNumber, r.fatherName, std.darja, 
                   r.presentAddress, r.permanentAddress, r.stdNic, r.guirdianNic, 
                   std.promotionDate, std.dateEnd, r.admissionNo, reg.registrationNo, 
                   r.formB, r.dob, r.signNazim, r.stdPhoto
            FROM registrationinfo r
            INNER JOIN regnumbers reg ON r.sno = reg.regSno
            INNER JOIN stddarjaat std ON r.sno = std.stdSno
            WHERE std.darja = :darja 
              AND r.isActive = 1 
              AND std.isCurrent = 1
              AND YEAR(std.promotionDate) BETWEEN YEAR(:from) AND YEAR(:to)";

    try {
        $results = $db->getRecordSet($sql, [
            'darja' => $darja,
            'from' => $fromDat,
            'to' => $toDate
        ]);

        if (!empty($results)) {
            foreach ($results as &$row) {
                // Formatting data for the frontend
                $regNumParts = explode("-", $row['registrationNo']);
                $row['registrationNoShort'] = isset($regNumParts[2]) ? intval($regNumParts[2]) : '';

                // Date Conversions (Hijri to Gregorian for display)
                if ($row['promotionDate']) {
                    $row['dateIssued'] = $hijri->HijriToGregorian($row['promotionDate'], "YYYY-MM-DD");
                }
                else {
                    $row['dateIssued'] = '';
                }

                if ($row['dateEnd']) {
                    $row['dateEndFormatted'] = $hijri->HijriToGregorian($row['dateEnd'], "YYYY-MM-DD");
                }
                else {
                    $row['dateEndFormatted'] = '';
                }

                if ($row['dob']) {
                    $dbr = new DateTime($row['dob']);
                    $row['dobFormatted'] = $dbr->format("Y-m-d");
                }
                else {
                    $row['dobFormatted'] = '';
                }

                // Determine which ID to show
                $row['idLabel'] = 'شناختی کارڈ نمبر';
                $row['idValue'] = $row['stdNic'];
                if ($row['stdNic'] == "0" || empty($row['stdNic'])) {
                    if ($row['guirdianNic'] != "0" && !empty($row['guirdianNic'])) {
                        $row['idLabel'] = 'سرپرست کارڈ';
                        $row['idValue'] = $row['guirdianNic'];
                    }
                    else if ($row['formB'] != "0" && !empty($row['formB'])) {
                        $row['idLabel'] = 'فارم "ب"';
                        $row['idValue'] = $row['formB'];
                    }
                }

                // Darja Name
                $row['darjaName'] = $db->getValue("SELECT darja FROM darjaat WHERE derjaCode = :code", ['code' => $row['darja']]);
            }
            $response['success'] = true;
            $response['data'] = $results;
        }
        else {
            $response['message'] = 'اس درجہ میں کوئی طالب علم نہیں ملا';
        }
    }
    catch (Exception $e) {
        $response['message'] = 'ڈیٹا بیس کی خرابی: ' . $e->getMessage();
    }
}

echo json_encode($response);