<?php
header('Content-Type: application/json');
header('X-Content-Type-Options: nosniff');

session_start();
if (!isset($_SESSION['userid']) || empty($_SESSION['key'])) {
    echo json_encode(['success' => false, 'message' => 'غیر مجاز رسائی']);
    exit;
}

require_once('../libs/classes/DbPathsArray.php');
require_once('../libs/classes/App_DB.php');

$db = new App_DB(DBU::$dba_user);
$crud = $db;
require_once('../includes/configuration.php');

$response = ['success' => false, 'data' => null, 'message' => ''];

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $response['message'] = 'صرف POST درخواست قبول ہوتی ہے';
    echo json_encode($response);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);

$regSno = (int) ($input['regSno'] ?? 0);
$darja = (int) ($input['darja'] ?? 0);
$pDate = trim($input['promotionDate'] ?? '');
$dEnd = trim($input['dateEnd'] ?? '');

if (!$regSno || !$darja || empty($pDate) || empty($dEnd)) {
    $response['message'] = 'برائے مہربانی تمام ضروری معلومات فراہم کریں';
    echo json_encode($response);
    exit;
}

try {
    // 1. Fetch Student Details
    $sqlStd = "SELECT r.stdName, r.fatherName, r.dob, r.permanentAddress, 
                      reg.RollNumber, reg.registrationNo, d.darja as darjaName
               FROM registrationinfo r
               JOIN regnumbers reg ON r.sno = reg.regSno
               JOIN stddarjaat st ON r.sno = st.stdSno 
               JOIN darjaat d ON st.darja = d.derjaCode
               WHERE r.sno = :regSno AND st.darja = :darja AND r.isActive = 1 AND st.isCurrent = 1
               LIMIT 1";

    $stdData = $db->getRecordSet($sqlStd, ['regSno' => $regSno, 'darja' => $darja]);

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

    $student = $stdData[0];

    // 2. Fetch Subjects and Marks
    $resultTerm = "3"; // Annual
    $sqlMarks = "SELECT s.subjectName, s.totalMarks, r.obtmarks
                 FROM subjects s
                 LEFT JOIN result r ON r.subjectsno = s.sno 
                    AND r.stdSno = :regSno 
                    AND r.resultTerm = :term 
                    AND r.darjaSno = :darja
                    AND r.promotionDate = :pDate 
                    AND r.dateEnd = :dEnd
                 WHERE s.darjaSno = :darja
                 ORDER BY s.sno ASC";

    $marksData = $db->getRecordSet($sqlMarks, [
        'regSno' => $regSno,
        'darja' => $darja,
        'term' => $resultTerm,
        'pDate' => $pDate,
        'dEnd' => $dEnd
    ]);

    if (empty($marksData)) {
        $response['message'] = 'اس درجہ کے مضامین نہیں ملے';
        echo json_encode($response);
        exit;
    }

    $totalObtained = 0;
    $totalPossible = 0;
    $subjects = [];
    $hasResults = false;

    foreach ($marksData as $row) {
        $obt = ($row['obtmarks'] !== null) ? (int) $row['obtmarks'] : null;
        if ($obt !== null)
            $hasResults = true;

        $totalObtained += (int) $obt;
        $totalPossible += (int) $row['totalMarks'];

        $subjects[] = [
            'name' => htmlspecialchars($row['subjectName']),
            'total' => (int) $row['totalMarks'],
            'obtained' => $obt
        ];
    }

    if (!$hasResults) {
        $response['message'] = 'اس طالب علم کا سالانہ رزلٹ ابھی تک اپ لوڈ نہیں کیا گیا ہے';
        // We still return student info but success remains false or we sets a flag
    } else {
        $percent = ($totalPossible > 0) ? ($totalObtained / $totalPossible) * 100 : 0;
        $grade = 'راسب';
        if ($percent >= 75)
            $grade = 'ممتاز';
        else if ($percent >= 65)
            $grade = 'جید جداً';
        else if ($percent >= 56)
            $grade = 'جید';
        else if ($percent >= 40)
            $grade = 'مقبول';

        $response['success'] = true;
    }

    // Madrasa Config
    $grade = $grade ?? '-';
    $configRow = $db->getRecordSet("SELECT M_Name, M_Address, L_Address FROM config LIMIT 1");

    $response['data'] = [
        'student' => [
            'name' => htmlspecialchars($student['stdName']),
            'father' => htmlspecialchars($student['fatherName']),
            'dob' => $student['dob'],
            'address' => htmlspecialchars($student['permanentAddress']),
            'rollNo' => $student['RollNumber'],
            'regNo' => $student['registrationNo'],
            'darjaName' => htmlspecialchars($student['darjaName'])
        ],
        'subjects' => $subjects,
        'totals' => [
            'obtained' => $totalObtained,
            'possible' => $totalPossible
        ],
        'session' => explode("-", $pDate)[0] . ' - ' . explode("-", $dEnd)[0],
        'madrasa' => [
            'name' => htmlspecialchars($configRow[0]['M_Name'] ?? M_Name),
            'address' => htmlspecialchars($configRow[0]['M_Address'] ?? M_Address),
            'l_address' => htmlspecialchars($configRow[0]['L_Address'] ?? L_Address),
            'elhaq' => Elhaq
        ],
        'grade' => $grade
    ];

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

echo json_encode($response);
