<?php
require "commonincludefiles.php";
//print_r($_POST);exit;
if (isset($_SESSION["VedantnrCollegeId"]) && !empty($_SESSION["VedantnrCollegeId"])) {
    $objStudentDocumentMgmt = new StudentDocumentMgmt();

    // Decode the JSON data from the request
    $documentids = json_decode(stripslashes($_POST['documentids']));
    $noofdocument = json_decode(stripslashes($_POST['noofdocument']));
    $docrecive_date = json_decode(stripslashes($_POST['docrecive_date']));
    $student_id = $_POST['student_hidden'];
    $studentdocument_ids = json_decode(stripslashes($_POST['studentdocument_ids'])); // Handle multiple IDs

    $count = count($studentdocument_ids);

    for ($i = 0; $i < $count; $i++) {
        // Prepare data for processing
        $objStudentDocumentMgmt->semester_id = $_POST['semester_hidden'];
        $objStudentDocumentMgmt->year_id = $_POST['year_hidden'];
        $objStudentDocumentMgmt->student_id = $student_id;
        $objStudentDocumentMgmt->branch_id = $_POST['branch_hidden'];
        $objStudentDocumentMgmt->branchyear_id = $_POST['branchyear_hidden'];
        $objStudentDocumentMgmt->document_id = $documentids[$i];
        $objStudentDocumentMgmt->noofdocument = $noofdocument[$i];
        $objStudentDocumentMgmt->docrecive_date = $docrecive_date[$i];
        $objStudentDocumentMgmt->studentdocument_id  = $studentdocument_ids[$i]; // Get the studentdocument_id for each record

        // Check if the record exists
        $existingRecord = $objStudentDocumentMgmt->recordExists($student_id, $documentids[$i]);

        //Set studentdocument_id and choose the operation


        if ($existingRecord) {
            // Record exists, perform edit
            $objStudentDocumentMgmt->edit();
        } else {
            // Record does not exist, perform add
            $objStudentDocumentMgmt->add();
        }
    }
    echo json_encode(['success' => true, 'msg' => 'Data saved successfully.']);

} else {
    echo json_encode(['success' => false, 'msg' => 'Session expired.']);
}
?>