<?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' => '',
    'data' => []
];

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

    if ($action === 'search') {
        $stdName = $_POST['stdName'] ?? '';
        $stdRegNo = $_POST['stdRegNo'] ?? '';

        if (empty($stdName) && empty($stdRegNo)) {
            $response['message'] = 'طالب العلم کا نام یا رجسٹریشن نمبر میں سے کم از کم ایک مہیا کریں';
            echo json_encode($response);
            exit;
        }

        try {
            $sql = "SELECT r.sno, r.stdName, r.fatherName, r.dob, r.permanentAddress, r.presentAddress, r.cellNo, r.stdPhoto,
                    reg.registrationNo, st.darja, st.promotionDate, st.isCurrent 
                    FROM registrationinfo r
                    INNER JOIN stddarjaat st ON r.sno = st.stdSno
                    INNER JOIN regnumbers reg ON r.sno = reg.regSno
                    WHERE st.isCurrent = 1 AND r.isActive = 1";
            
            $bindVars = [];

            if (!empty($stdName) && !empty($stdRegNo)) {
                $sql .= " AND r.stdName = :stdName AND reg.registrationNo = :stdRegNo";
                $bindVars[':stdName'] = $stdName;
                $bindVars[':stdRegNo'] = $stdRegNo;
            } else if (!empty($stdName)) {
                $sql .= " AND r.stdName = :stdName";
                $bindVars[':stdName'] = $stdName;
            } else if (!empty($stdRegNo)) {
                $sql .= " AND reg.registrationNo = :stdRegNo";
                $bindVars[':stdRegNo'] = $stdRegNo;
            }

            $students = $db->getRecordSetFilled($sql, $bindVars);

            if (!empty($students)) {
                // Fetching darja history for each student
                foreach ($students as &$student) {
                    $darjaCode = $student['darja'];
                    $student['darjaName'] = $db->getValue("SELECT darja FROM darjaat WHERE derjaCode = :darja", [':darja' => $darjaCode]);
                    
                    $historySql = "SELECT s.sno, s.promotionDate, s.isCurrent, d.darja as darjaName
                                   FROM stddarjaat s
                                   LEFT JOIN darjaat d ON s.darja = d.derjaCode
                                   WHERE s.stdSno = :stdSno ORDER BY s.promotionDate ASC";
                    $student['history'] = $db->getRecordSetFilled($historySql, [':stdSno' => $student['sno']]);
                }
                $response['success'] = true;
                $response['data'] = $students;
            } else {
                $response['message'] = 'کوئی ریکارڈ نہیں ملا';
            }
        } catch (Exception $e) {
            $response['message'] = 'Database Error: ' . $e->getMessage();
        }
    } else if ($action === 'delete_history') {
        $sno = $_POST['sno'] ?? '';
        
        if (empty($sno)) {
            $response['message'] = 'ریکارڈ کی شناخت فراہم نہیں کی گئی';
            echo json_encode($response);
            exit;
        }

        try {
            $sqlDel = "DELETE FROM stddarjaat WHERE sno = :sno AND isCurrent = 0";
            if ($db->dbQuery($sqlDel, [':sno' => $sno])) {
                $response['success'] = true;
                $response['message'] = 'ریکارڈ کامیابی کے ساتھ مٹا دیا گیا ہے';
            } else {
                $response['message'] = 'ریکارڈ منسوخ نہیں ہو سکا';
            }
        } catch (Exception $e) {
            $response['message'] = 'Database Error: ' . $e->getMessage();
        }
    } else {
        $response['message'] = 'Invalid action request.';
    }
}

echo json_encode($response);
