<?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');
require_once('../classes/Hijri_GregorianConvert.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;

if (!$darja_sno || !$date_start || !$date_end) {
    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 = :code", ['code' => $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 = '';

// 3. Get Subjects for this Darja
$subjects_res = $db->getRecordSet("SELECT sno, subjectName, totalMarks FROM subjects WHERE darjaSno = :darja ORDER BY sno ASC", ['darja' => $darja_sno]);
$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;
}

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

// 4. Get Students who have results in this period
$students_res = $db->getRecordSet("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 r.isActive = 1", [
    'darja' => $darja_sno,
    'promotionDate' => $date_start,
    'dateEnd' => $date_end
]);

if (empty($students_res)) {
    echo json_encode(['success' => false, 'message' => 'منتخب سال اور درجہ کے لیے کوئی ریکارڈ نہیں ملا']);
    exit;
}

$report_data = [];
$term_results = [1 => [], 2 => [], 3 => []]; // For positions

// Attendance months to check (Shawwal to Ramadan)
$att_months = ['10', '11', '12', '01', '02', '03', '04', '05', '06', '07', '08', '09'];

foreach ($students_res as $std) {
    $std_id = $std['sno'];
    $student_info = [
        'std_id' => $std_id,
        'name' => $std['stdName'],
        'father' => $std['fatherName'],
        'terms' => [],
        'monthly_attendance' => [],
        'total_absence' => 0
    ];

    // Fetch marks for each term
    for ($term = 1; $term <= 3; $term++) {
        $marks = [];
        $total_obtained = 0;
        $has_result = false;

        foreach ($subjects as $sbj) {
            $sbj_id = $sbj['id'];
            $m_res = $db->getRecordSet("SELECT obtmarks FROM result 
                      WHERE stdSno = :stdSno 
                        AND darjaSno = :darjaSno 
                        AND subjectsno = :subjectsno 
                        AND resultTerm = :resultTerm 
                        AND promotionDate = :promotionDate 
                        AND dateEnd = :dateEnd 
                      LIMIT 1", [
                'stdSno' => $std_id,
                'darjaSno' => $darja_sno,
                'subjectsno' => $sbj_id,
                'resultTerm' => $term,
                'promotionDate' => $date_start,
                'dateEnd' => $date_end
            ]);

            if (!empty($m_res)) {
                $has_result = true;
                $obt = $m_res[0]['obtmarks'];
            } else {
                $obt = 0;
            }
            $marks[] = $obt;
            $total_obtained += $obt;
        }

        if ($has_result) {
            $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 = 'مقبول';

            $student_info['terms'][$term] = [
                'marks' => $marks,
                'total_obt' => $total_obtained,
                'avg' => $avg,
                'grade' => $grade
            ];

            // Add to term_results for position calculation
            $term_results[$term][] = [
                'name' => $std['stdName'],
                'father' => $std['fatherName'],
                'total_obt' => $total_obtained
            ];
        } else {
            $student_info['terms'][$term] = null;
        }
    }

    // Monthly Attendance Summary (Hijri Mapping Based)
    $hijriConv = new Hijri_GregorianConvert();

    $hStartYear = explode('-', $date_start)[0];
    $hEndYear = explode('-', $date_end)[0];

    // Fetch all attendance records (Date & Status) for the student within the relevant years
    $attendance_records = $db->getRecordSet("SELECT attendanceDate, stdStatus 
                                            FROM attendence 
                                            WHERE darjaSno = :darja 
                                              AND regSno = :regSno 
                                              AND (attendanceDate LIKE :year1 OR attendanceDate LIKE :year2)", [
        'darja' => $darja_sno,
        'regSno' => $std_id,
        'year1' => $hStartYear . '%',
        'year2' => $hEndYear . '%'
    ]);

    $monthly_map = [];
    $total_abs = 0;

    foreach ($attendance_records as $row) {
        $hDate = $row['attendanceDate']; // YYYY-MM-DD (Hijri)
        $status = $row['stdStatus'];

        // Extract Hijri month directly from the date string
        $hParts = explode('-', $hDate);
        if (count($hParts) === 3) {
            $hMonth = $hParts[1]; // MM (Hijri)

            if (!isset($monthly_map[$hMonth])) {
                $monthly_map[$hMonth] = ['ح' => 0, 'غ' => 0, 'ر' => 0, 'ب' => 0];
            }
            if (isset($monthly_map[$hMonth][$status])) {
                $monthly_map[$hMonth][$status]++;
            }

            // Total Absence (standard logic: غ + ر + ب counts as missed days)
            if (in_array($status, ['غ', 'ر', 'ب'])) {
                $total_abs++;
            }
        }
    }

    foreach ($att_months as $mon) {
        $stats = $monthly_map[$mon] ?? ['ح' => 0, 'غ' => 0, 'ر' => 0, 'ب' => 0];
        $student_info['monthly_attendance'][$mon] = $stats;
    }
    $student_info['total_absence'] = $total_abs;
    $student_info['is_sahib_tarteeb'] = (!empty($attendance_records) && $total_abs === 0);

    $report_data[] = $student_info;
}

// 5. Calculate Positions for each term
$positions = [];
foreach ($term_results as $term => $results) {
    if (empty($results)) {
        $positions[$term] = null;
        continue;
    }
    usort($results, function ($a, $b) {
        return $b['total_obt'] <=> $a['total_obt'];
    });
    $positions[$term] = [
        'first' => $results[0] ?? null,
        'second' => $results[1] ?? null,
        'third' => $results[2] ?? null
    ];
}

// 6. Get Educational Year Remarks for each term
$remarks = [];
for ($term = 1; $term <= 3; $term++) {
    $rem_res = $db->getRecordSet("SELECT DISTINCT edu_year_remarks FROM result 
                                 WHERE promotionDate = :start AND dateEnd = :end 
                                   AND resultTerm = :term AND darjaSno = :darja LIMIT 1", [
        'start' => $date_start,
        'end' => $date_end,
        'term' => $term,
        'darja' => $darja_sno
    ]);
    $remarks[$term] = $rem_res[0]['edu_year_remarks'] ?? '';
}

// 7. Get Hijri Year for Header (Dates are already Hijri YYYY-MM-DD)
$hStartYear = explode('-', $date_start)[0];
$hEndYear = explode('-', $date_end)[0];

echo json_encode([
    'success' => true,
    'madrasaName' => $m_name,
    'madrasaAddress' => $m_address,
    'madrasaAddressL' => $l_address,
    'madrasaPhone' => $p_number,
    'darjaName' => $darja_name,
    'date_start' => $date_start,
    'date_end' => $date_end,
    'year_start_hijri' => $hStartYear,
    'year_end_hijri' => $hEndYear,
    'totalDarjaMarks' => $total_darja_marks,
    'subjects' => $subjects,
    'att_months' => $att_months,
    'students' => $report_data,
    'positions' => $positions,
    'remarks' => $remarks
], JSON_UNESCAPED_UNICODE);
