<?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' => [],
    'edu_year_remarks' => ''
];

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

    if (empty($darja) || empty($promotionDate) || empty($dateEnd) || empty($resultTerm)) {
        $response['message'] = 'تمام ضروری معلومات فراہم کریں';
        echo json_encode($response);
        exit;
    }

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

        // 2. Fetch all result entries for this criteria
        $sqlResults = "SELECT rs.sno as resultSno, rs.stdSno, r.stdName, r.fatherName, rs.subjectsno, rs.obtmarks, rs.edu_year_remarks
                       FROM result rs
                       INNER JOIN registrationinfo r ON rs.stdSno = r.sno
                       WHERE rs.darjasno = :darja
                         AND rs.promotionDate = :pDate
                         AND rs.dateEnd = :dEnd
                         AND rs.resultTerm = :term
                       ORDER BY r.stdName ASC, rs.subjectsno ASC";
        
        $allResults = $db->getRecordSet($sqlResults, [
            'darja' => $darja,
            'pDate' => $promotionDate,
            'dEnd' => $dateEnd,
            'term' => $resultTerm
        ]);

        if (empty($allResults)) {
            $response['message'] = 'اس معیار کے مطابق کوئی نتیجہ نہیں ملا';
            echo json_encode($response);
            exit;
        }

        // 3. Process results into student-grouped format
        $studentsMap = [];
        $remarks = '';

        foreach ($allResults as $res) {
            $stdSno = $res['stdSno'];
            if (!isset($studentsMap[$stdSno])) {
                $studentsMap[$stdSno] = [
                    'stdSno' => $stdSno,
                    'stdName' => $res['stdName'],
                    'fatherName' => $res['fatherName'],
                    'marks' => []
                ];
            }
            $studentsMap[$stdSno]['marks'][$res['subjectsno']] = [
                'resultSno' => $res['resultSno'],
                'obtMarks' => $res['obtmarks']
            ];
            
            if (empty($remarks) && !empty($res['edu_year_remarks'])) {
                $remarks = $res['edu_year_remarks'];
            }
        }

        $response['success'] = true;
        $response['students'] = array_values($studentsMap);
        $response['edu_year_remarks'] = $remarks;

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

echo json_encode($response);
