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

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

$response = [
    'success' => false,
    'message' => '',
    'subjects' => [],
    'students' => []
];

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

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

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

        // 2. Fetch Students for this Darja and Date Range
        $sqlStudents = "SELECT r.sno, r.stdName, r.fatherName 
                        FROM registrationinfo r
                        INNER JOIN stddarjaat std ON r.sno = std.stdSno
                        WHERE std.darja = :darja 
                          AND std.promotionDate = :promotionDate 
                          AND std.dateEnd = :dateEnd 
                          AND std.isCurrent = 1
                          AND r.isActive = 1
                        ORDER BY r.stdName ASC";
        $students = $db->getRecordSet($sqlStudents, [
            'darja' => $darja,
            'promotionDate' => $promotionDate,
            'dateEnd' => $dateEnd
        ]);

        if (empty($subjects)) {
            $response['message'] = 'اس درجہ کے لیے کوئی مضامین نہیں ملے';
        }
        else if (empty($students)) {
            $response['message'] = 'اس درجہ میں کوئی طالب علم نہیں ملا';
        }
        else {
            $response['success'] = true;
            $response['subjects'] = $subjects;
            $response['students'] = $students;
        }
    }
    catch (Exception $e) {
        $response['message'] = 'ڈیٹابیس کی خرابی: ' . $e->getMessage();
    }
}

echo json_encode($response);