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

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

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);

    if (!$data) {
        $response['message'] = 'غلط ڈیٹا فارمیٹ';
        echo json_encode($response);
        exit;
    }

    $darja = $data['darja'] ?? '';
    $promotionDate = $data['promotionDate'] ?? '';
    $dateEnd = $data['dateEnd'] ?? '';
    $resultTerm = $data['resultTerm'] ?? '';
    $eduYearRemarks = $data['eduYearRemarks'] ?? '';
    $results = $data['results'] ?? []; // Array of {stdSno, marks: {subjectSno: mark}}

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

    try {
        $db->beginTransactions();

        // Check if results already exist for this Darja, Term, and Year
        $sqlCheck = "SELECT sno FROM result 
                     WHERE darjasno = :darja 
                       AND promotionDate = :pDate 
                       AND dateEnd = :dEnd 
                       AND resultTerm = :term";
        $existing = $db->getRecordSet($sqlCheck, [
            'darja' => $darja,
            'pDate' => $promotionDate,
            'dEnd' => $dateEnd,
            'term' => $resultTerm
        ]);

        if (!empty($existing)) {
            $response['message'] = 'اس تعلیمی سال اور امتحان کے لیے رزلٹ پہلے سے محفوظ ہے';
            $db->rollBackTransaction();
            echo json_encode($response);
            exit;
        }

        $sqlInsert = "INSERT INTO result (darjasno, stdSno, subjectsno, obtmarks, promotionDate, dateEnd, resultTerm, edu_year_remarks) 
                      VALUES (:darja, :stdSno, :subjectSno, :obtMarks, :pDate, :dEnd, :term, :remarks)";

        foreach ($results as $stdResult) {
            $stdSno = $stdResult['stdSno'];
            foreach ($stdResult['marks'] as $subjectSno => $mark) {
                $db->dbQuery($sqlInsert, [
                    'darja' => $darja,
                    'stdSno' => $stdSno,
                    'subjectSno' => $subjectSno,
                    'obtMarks' => $mark,
                    'pDate' => $promotionDate,
                    'dEnd' => $dateEnd,
                    'term' => $resultTerm,
                    'remarks' => $eduYearRemarks
                ]);
            }
        }

        $db->commitTransaction();
        $response['success'] = true;
        $response['message'] = 'رزلٹ کامیابی کے ساتھ محفوظ ہو گیا';
    } catch (Exception $e) {
        $db->rollBackTransaction();
        $response['message'] = 'ڈیٹابیس کی خرابی: ' . $e->getMessage();
    }
}

echo json_encode($response);
