<?php
header('Content-Type: application/json');
require_once('../libs/classes/DbPathsArray.php');
require_once('../libs/classes/App_DB.php');

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

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

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $darja = $_GET['darja'] ?? '';
    $attendanceDate = $_GET['attendanceDate'] ?? '';

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

    try {
        // Query to fetch attendance records with student names
        $sql = "SELECT att.sno as attSno, att.stdStatus, att.attendanceDate, att.regSno,
                       rg.stdName, rg.fatherName, r.registrationNo
                FROM attendence att
                INNER JOIN registrationinfo rg ON att.regSno = rg.sno
                INNER JOIN regnumbers r ON rg.sno = r.regSno
                WHERE att.darjaSno = :darja 
                  AND att.attendanceDate = :aDate
                ORDER BY rg.stdName ASC";

        $records = $db->getRecordSet($sql, [
            'darja' => $darja,
            'aDate' => $attendanceDate
        ]);

        if (!empty($records)) {
            $response['success'] = true;
            $response['records'] = $records;
        } else {
            $response['message'] = 'اس تاریخ کی کوئی حاضری نہیں ملی';
        }
    } catch (Exception $e) {
        $response['message'] = 'ڈیٹابیس کی خرابی: ' . $e->getMessage();
    }
}

echo json_encode($response);
