<?php
session_start();
require_once('../libs/classes/DbPathsArray.php');
require_once('../libs/classes/App_DB.php');
require_once('../classes/Hijri_GregorianConvert.php');

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

if (!isset($_SESSION['userid'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}
$hijriConv = new Hijri_GregorianConvert();
$data = json_decode(file_get_contents('php://input'), true);

$darja_sno = $data['darja_sno'] ?? '';
$date_start = $data['date_start'] ?? '';
$date_end = $data['date_end'] ?? '';
$std_id = $data['reg_sno'] ?? '';

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

// 1. Get Student Info
$std_info_sql = "SELECT r.stdName, r.fatherName, r.stdPhoto, reg.registrationNo 
                 FROM registrationinfo r 
                 LEFT JOIN regnumbers reg ON reg.regSno = r.sno
                 WHERE r.sno = :std_id";
$std_info = $db->getRecordSet($std_info_sql, ['std_id' => $std_id]);

if (empty($std_info)) {
    echo json_encode(['success' => false, 'message' => 'Student not found']);
    exit();
}

$student = $std_info[0];

// 2. Get Subjects for Darja
$subjects_sql = "SELECT sno, subjectName as name, totalMarks FROM subjects WHERE darjaSno = :darja";
$subjects = $db->getRecordSet($subjects_sql, ['darja' => $darja_sno]);
$total_darja_marks = array_sum(array_column($subjects, 'totalMarks'));

// 3. Get Marks for each term (1, 2, 3)
$term_results = [];
for ($term = 1; $term <= 3; $term++) {
    $marks_sql = "SELECT subjectSno, obtmarks FROM result 
                   WHERE stdSno = :std_id AND darjaSno = :darja 
                     AND promotionDate = :start AND dateEnd = :end 
                     AND resultTerm = :term";
    $marks_res = $db->getRecordSet($marks_sql, [
        'std_id' => $std_id,
        'darja' => $darja_sno,
        'start' => $date_start,
        'end' => $date_end,
        'term' => $term
    ]);

    if (!empty($marks_res)) {
        $marks_map = [];
        $total_obtained = 0;
        foreach ($marks_res as $m) {
            $marks_map[$m['subjectSno']] = $m['obtmarks'];
            $total_obtained += $m['obtmarks'];
        }

        $avg = ($total_darja_marks > 0) ? round(($total_obtained * 100) / $total_darja_marks, 2) : 0;

        // Grading Logic based on legacy code
        $grade = 'راسب';
        if ($avg > 75)
            $grade = 'ممتاز';
        else if ($avg > 65)
            $grade = 'جید جداً';
        else if ($avg > 56)
            $grade = 'جید';
        else if ($avg >= 40)
            $grade = 'مقبول';

        $term_results[$term] = [
            'marks' => $marks_map,
            'total_obt' => $total_obtained,
            'avg' => $avg,
            'grade' => $grade
        ];
    } else {
        $term_results[$term] = null;
    }
}

// 4. Monthly Attendance (Hijri Mapped)
$att_months = ['10', '11', '12', '01', '02', '03', '04', '05', '06', '07'];
$attendance_records = $db->getRecordSet("SELECT attendanceDate, stdStatus 
                                        FROM attendence 
                                        WHERE darjaSno = :darja 
                                          AND regSno = :regSno 
                                          AND attendanceDate BETWEEN :start AND :end", [
    'darja' => $darja_sno,
    'regSno' => $std_id,
    'start' => $date_start,
    'end' => $date_end
]);

$monthly_attendance = [];
$total_g = 0; // Absent
$total_r = 0; // Leave
$total_b = 0; // Sick

foreach ($attendance_records as $row) {
    $gDate = $row['attendanceDate'];
    $status = $row['stdStatus'];

    $parts = explode('-', $gDate);
    $formattedGDate = $parts[2] . $parts[1] . $parts[0]; // DDMMYYYY

    $hDateStr = $hijriConv->GregorianToHijri($formattedGDate, 'DDMMYYYY');
    if ($hDateStr) {
        $hParts = explode('-', $hDateStr);
        $hMonth = $hParts[1];

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

        if ($status == 'غ')
            $total_g++;
        if ($status == 'ر')
            $total_r++;
        if ($status == 'ب')
            $total_b++;
    }
}

// Sahib-e-Tarteeb logic: if all non-present statuses are 0
$is_sahib_tarteeb = ($total_g == 0 && $total_r == 0 && $total_b == 0);

// 5. Get Exam Remarks/Dates
$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'] ?? '';
}

// 6. Get Class Name
$darja_res = $db->getRecordSet("SELECT darja FROM darjaat WHERE derjaCode = :darja", ['darja' => $darja_sno]);
$darja_name = $darja_res[0]['darja'] ?? '';

// 7. Get Hijri Year for Header
$hStartStr = $hijriConv->GregorianToHijri(date('dmY', strtotime($date_start)), 'DDMMYYYY');
$hEndStr = $hijriConv->GregorianToHijri(date('dmY', strtotime($date_end)), 'DDMMYYYY');
$hStartYear = $hStartStr ? explode('-', $hStartStr)[2] : '';
$hEndYear = $hEndStr ? explode('-', $hEndStr)[2] : '';

echo json_encode([
    'success' => true,
    'madrasaName' => M_Name,
    'madrasaAddressL' => L_Address,
    'darjaName' => $darja_name,
    'year_start_hijri' => $hStartYear,
    'year_end_hijri' => $hEndYear,
    'student' => $student,
    'subjects' => $subjects,
    'totalDarjaMarks' => $total_darja_marks,
    'term_results' => $term_results,
    'monthly_attendance' => $monthly_attendance,
    'att_months' => $att_months,
    'total_stats' => [
        'غ' => $total_g,
        'ر' => $total_r,
        'ب' => $total_b
    ],
    'is_sahib_tarteeb' => $is_sahib_tarteeb,
    'remarks' => $remarks
]);
