<?php
header('Content-Type: application/json');
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);
$hijri = new Hijri_GregorianConvert();

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? 'fetch';

    if ($action === 'update_attendance') {
        $stdSno = $_POST['stdSno'] ?? '';
        $date = $_POST['date'] ?? '';
        $status = $_POST['status'] ?? '';

        if (empty($stdSno) || empty($date) || empty($status)) {
            echo json_encode(['success' => false, 'message' => 'Invalid data']);
            exit;
        }

        try {
            $darja = $_POST['darja'] ?? '';
            // Check if record exists
            $exists = $db->getValue("SELECT sno FROM attendence WHERE regSno = :sno AND attendanceDate = :date", [
                ':sno' => $stdSno,
                ':date' => $date
            ]);

            if ($exists) {
                $sql = "UPDATE attendence SET stdStatus = :status WHERE sno = :sno";
                $db->dbQuery($sql, [':status' => $status, ':sno' => $exists]);
            } else {
                if (empty($darja)) {
                    throw new Exception("Darja info missing for new record.");
                }
                $sql = "INSERT INTO attendence (regSno, attendanceDate, stdStatus, darjaSno) VALUES (:sno, :date, :status, :darja)";
                $db->dbQuery($sql, [':sno' => $stdSno, ':date' => $date, ':status' => $status, ':darja' => $darja]);
            }
            echo json_encode(['success' => true]);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        exit;
    }

    $darja = $_POST['darja'] ?? '';
    $date1 = $_POST['date1'] ?? '';
    $date2 = $_POST['date2'] ?? '';

    if (empty($darja) || empty($date1) || empty($date2)) {
        $response['message'] = 'تمام مطلوبہ معلومات مہیا کریں';
        echo json_encode($response);
        exit;
    }

    try {
        $darjaName = $db->getValue("SELECT darja from darjaat WHERE derjaCode = :darja", [':darja' => $darja]);

        // Hijri Month Names Map
        $hijriMonths = [
            1 => 'محرم الحرام',
            2 => 'صفر المظفر',
            3 => 'ربیع الاول',
            4 => 'ربیع الثانی',
            5 => 'جمادی الاولیٰ',
            6 => 'جمادی الثانیہ',
            7 => 'رجب المرجب',
            8 => 'شبان المعظم',
            9 => 'رمضان المبارک',
            10 => 'شوال المکرم',
            11 => 'ذوالقعدہ',
            12 => 'ذوالحجہ'
        ];

        // Generate list of dates in range
        $period = new DatePeriod(
            new DateTime($date1),
            new DateInterval('P1D'),
            (new DateTime($date2))->modify('+1 day')
        );
        $datesList = [];
        $datesMeta = [];

        foreach ($period as $dt) {
            $gDate = $dt->format('Y-m-d');
            $datesList[] = $gDate;

            // Inline Gregorian→Hijri conversion (no external class dependency)
            $gy = (int) $dt->format('Y');
            $gm = (int) $dt->format('n');
            $gd = (int) $dt->format('j');

            // Step 1: Gregorian date → Julian Day Number
            $jGm = $gm;
            $jGy = $gy;
            if ($jGm <= 2) {
                $jGy--;
                $jGm += 12;
            }
            $A = (int) ($jGy / 100);
            $B = 2 - $A + (int) ($A / 4);
            $jdn = (int) (365.25 * ($jGy + 4716)) + (int) (30.6001 * ($jGm + 1)) + $gd + $B - 1524;

            // Step 2: Julian Day → Hijri (tabular Islamic calendar)
            $l = $jdn - 1948440 + 10632;
            $n = (int) (($l - 1) / 10631);
            $l = $l - 10631 * $n + 354;
            $j = (int) ((10985 - $l) / 5316) * (int) ((50 * $l) / 17719)
                + (int) ($l / 5670) * (int) ((43 * $l) / 15238);
            $l = $l - (int) ((30 - $j) / 15) * (int) ((17719 * $j) / 50)
                - (int) ($j / 16) * (int) ((15238 * $j) / 43) + 29;
            $hMonth = (int) ((24 * $l) / 709);
            $hDay = (int) ($l - (int) ((709 * $hMonth) / 24));
            $hYear = 30 * $n + $j - 30;


            $datesMeta[] = [
                'greg' => $gDate,
                'hDay' => $hDay,
                'hMonth' => $hMonth,
                'hMonthName' => $hijriMonths[$hMonth] ?? '',
                'hYear' => $hYear
            ];
        }

        $response['meta'] = [
            'darjaName' => $darjaName,
            'dateStart' => date('d-m-Y', strtotime($date1)),
            'dateEnd' => date('d-m-Y', strtotime($date2)),
            'dates' => $datesMeta
        ];

        $dateFirst = date('Y-m-d', strtotime($date1));
        $dateSecond = date('Y-m-d', strtotime($date2));

        $sqlGetData = "SELECT r.sno, r.stdName, r.fatherName, r.isActive, reg.registrationNo 
                       FROM registrationinfo r
                       INNER JOIN stddarjaat std ON std.stdSno = r.sno
                       LEFT JOIN regnumbers reg ON r.sno = reg.regSno
                       WHERE std.darja = :darja 
                       AND std.isCurrent = 1 
                       ORDER BY r.stdName ASC";

        $students = $db->getRecordSetFilled($sqlGetData, [':darja' => $darja]);

        if (!empty($students)) {
            foreach ($students as &$student) {
                // Initialize counters
                $counters = ['hazir' => 0, 'ghairHazir' => 0, 'bemar' => 0, 'rokhsat' => 0, 'totalWorkingDays' => 0];

                // Fetch ALL attendance records for this student in range
                $sqlAttendance = "SELECT stdStatus, attendanceDate 
                                 FROM attendence 
                                 WHERE regSno = :sno 
                                 AND attendanceDate BETWEEN :date1 AND :date2";

                $attendanceRows = $db->getRecordSetFilled($sqlAttendance, [
                    ':sno' => $student['sno'],
                    ':date1' => $dateFirst,
                    ':date2' => $dateSecond
                ]);

                // Map results by date for easy lookup
                $attendanceMap = [];
                foreach ($attendanceRows as $row) {
                    $attendanceMap[$row['attendanceDate']] = $row['stdStatus'];
                }

                // Process daily status
                $dailyData = [];
                foreach ($datesList as $d) {
                    $status = $attendanceMap[$d] ?? 'ح'; // Default to present as requested
                    $dailyData[$d] = $status;

                    switch ($status) {
                        case 'ح':
                            $counters['hazir']++;
                            break;
                        case 'غ':
                            $counters['ghairHazir']++;
                            break;
                        case 'ب':
                            $counters['bemar']++;
                            break;
                        case 'ر':
                            $counters['rokhsat']++;
                            break;
                    }
                }

                $counters['totalWorkingDays'] = count($datesList);
                $student['percentage'] = $counters['totalWorkingDays'] > 0
                    ? round(($counters['hazir'] / $counters['totalWorkingDays']) * 100, 1)
                    : 0;

                $student['attendanceGrid'] = $dailyData;
                $student['counters'] = $counters;
                $student['mezaan'] = ($counters['ghairHazir'] == 0 && $counters['bemar'] == 0 && $counters['rokhsat'] == 0 && $counters['hazir'] > 0) ? 'صاحب الترتیب' : '';
            }

            $response['success'] = true;
            $response['data'] = $students;
        } else {
            $response['message'] = 'کوئی ریکارڈ نہیں ملا';
        }
    } catch (Exception $e) {
        $response['message'] = 'Database Error: ' . $e->getMessage();
    }
}

echo json_encode($response);
