<?php
header('Content-Type: application/json');
session_start();

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

if (!isset($_SESSION['userid'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);
$darja_sno = $input['darja_sno'] ?? null;
$date_start = $input['date_start'] ?? null;
$date_end = $input['date_end'] ?? null;
$exam_type = $input['exam_type'] ?? null;

if (!$darja_sno || !$date_start || !$date_end || !$exam_type) {
    echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
    exit;
}

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

// 1. Get Darja Name
$darja_res = $db->getRecordSet("SELECT darja FROM darjaat WHERE derjaCode = '$darja_sno'");
$darja_name = !empty($darja_res) ? $darja_res[0]['darja'] : 'Unknown';

// 2. Get Madrasa Info from config
$config_res = $db->getRecordSet("SELECT M_Name, L_Address, M_Address, P_Number FROM config LIMIT 1");
$conf = !empty($config_res) ? $config_res[0] : [];
$m_name = $conf['M_Name'] ?? '';
$m_address = $conf['M_Address'] ?? '';
$l_address = $conf['L_Address'] ?? '';
$p_number = $conf['P_Number'] ?? '';

// Sanitize placeholders
if ($m_name === 'مدرسہ کا نام یہاں لکھیں')
    $m_name = '';
if ($l_address === 'مزید پتہ یہاں لکھیں' || $l_address === 'مقامی پتہ یہاں لکھیں')
    $l_address = '';
if ($m_address === 'مزید پتہ یہاں لکھیں')
    $m_address = '';

// 3. Get Subjects for this Darja
$subjects_res = $db->getRecordSet("SELECT sno, subjectName, totalMarks FROM subjects WHERE darjaSno = '$darja_sno' ORDER BY sno ASC");
$subjects = [];
foreach ($subjects_res as $s) {
    $sbj = $s['subjectName'];
    $sbj = str_replace([",", "،"], "/", $sbj);
    $subjects[] = [
        'id' => $s['sno'],
        'name' => $sbj,
        'total' => $s['totalMarks']
    ];
}

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

// 4. Get Students and their marks
$result_all_sql = "SELECT DISTINCT r.sno, r.stdName, r.fatherName
                   FROM registrationinfo r
                   JOIN stddarjaat st ON st.stdSno = r.sno
                   JOIN result rs ON rs.stdSno = r.sno
                   WHERE st.darja = :darja 
                     AND rs.darjaSno = :darja 
                     AND rs.promotionDate = :promotionDate 
                     AND rs.dateEnd = :dateEnd 
                     AND rs.resultTerm = :resultTerm 
                     AND r.isActive = 1";

$students_res = $db->getRecordSet($result_all_sql, [
    'darja' => $darja_sno,
    'promotionDate' => $date_start,
    'dateEnd' => $date_end,
    'resultTerm' => $exam_type
]);
if (empty($students_res)) {
    echo json_encode(['success' => false, 'message' => 'منتخب سال اور درجہ کے لیے کوئی نتیجہ نہیں ملا']);
    exit;
}

$report_data = [];
$total_darja_marks = array_sum(array_column($subjects, 'total'));

foreach ($students_res as $std) {
    $std_id = $std['sno'];

    // Fetch marks for each subject
    $marks = [];
    $total_obtained = 0;
    foreach ($subjects as $sbj) {
        $sbj_id = $sbj['id'];
        $m_sql = "SELECT obtmarks FROM result 
                  WHERE stdSno = :stdSno 
                    AND darjaSno = :darjaSno 
                    AND subjectsno = :subjectsno 
                    AND resultTerm = :resultTerm 
                    AND promotionDate = :promotionDate 
                    AND dateEnd =   :dateEnd 
                  LIMIT 1";
        $m_res = $db->getRecordSet($m_sql, [
            'stdSno' => $std_id,
            'darjaSno' => $darja_sno,
            'subjectsno' => $sbj_id,
            'resultTerm' => $exam_type,
            'promotionDate' => $date_start,
            'dateEnd' => $date_end
        ]);
        $obt = !empty($m_res) ? $m_res[0]['obtmarks'] : 0;
        $marks[] = $obt;
        $total_obtained += $obt;
    }

    // Attendance Info
    $att_sql = "SELECT stdStatus FROM attendence 
                WHERE regSno = :regSno 
                  AND darjaSno = :darjaSno
                  AND attendanceDate BETWEEN :date_start AND :date_end";
    $att_res = $db->getRecordSet($att_sql, [
        'regSno' => $std_id,
        'darjaSno' => $darja_sno,
        'date_start' => $date_start,
        'date_end' => $date_end
    ]);

    $absence = ['G' => 0, 'B' => 0, 'R' => 0];
    foreach ($att_res as $a) {
        if ($a['stdStatus'] == 'غ')
            $absence['G']++;
        if ($a['stdStatus'] == 'ب')
            $absence['B']++;
        if ($a['stdStatus'] == 'ر')
            $absence['R']++;
    }

    // Average and Grade
    $avg = ($total_darja_marks > 0) ? round(($total_obtained * 100) / $total_darja_marks, 2) : 0;
    $grade = 'راسب';
    if ($avg >= 75)
        $grade = 'ممتاز';
    else if ($avg >= 65)
        $grade = 'جید جداً';
    else if ($avg >= 56)
        $grade = 'جید';
    else if ($avg >= 40)
        $grade = 'مقبول';

    $report_data[] = [
        'std_id' => $std_id,
        'name' => $std['stdName'],
        'father' => $std['fatherName'],
        'marks' => $marks,
        'total_obt' => $total_obtained,
        'avg' => $avg,
        'grade' => $grade,
        'attendance' => $absence
    ];
}

// 5. Calculate Positions
$pos_data = $report_data;
usort($pos_data, function ($a, $b) {
    return $b['total_obt'] <=> $a['total_obt'];
});

$positions = [
    'first' => $pos_data[0] ?? null,
    'second' => $pos_data[1] ?? null,
    'third' => $pos_data[2] ?? null
];

// 6. Hijri Label (Educational Year Remarks)
$rem_sql = "SELECT DISTINCT edu_year_remarks FROM result 
            WHERE promotionDate = '$date_start' 
              AND dateEnd = '$date_end' 
              AND resultTerm = '$exam_type' 
              AND darjasno = '$darja_sno' 
            LIMIT 1";
$rem_res = $db->getRecordSet($rem_sql);
$edu_year_remarks = !empty($rem_res) ? $rem_res[0]['edu_year_remarks'] : '';

echo json_encode([
    'success' => true,
    'madrasaName' => $m_name,
    'madrasaAddress' => $m_address,
    'madrasaAddressL' => $l_address,
    'madrasaPhone' => $p_number,
    'darjaName' => $darja_name,
    'totalDarjaMarks' => $total_darja_marks,
    'subjects' => $subjects,
    'students' => $report_data,
    'positions' => $positions,
    'eduYearRemarks' => $edu_year_remarks,
    'examTypeLabel' => ($exam_type == 1 ? 'سہ ماہی' : ($exam_type == 2 ? 'ششماہی' : 'سالانہ'))
]);
