$(document).ready( function(){

    // Hide the loading GIF once the page is fully ready
    $(window).on('load', function() {
        removePageLoader();
    });


    // Get the id from the URL's query parameters
    var urlParams = new URLSearchParams(window.location.search);
    const student_id = urlParams.get('id').trim();

    getStudentDetailsById(student_id);
    $('#edu_education_info_table').DataTable({});
    $('#pe_work_info_table').DataTable({});
    loadEucationTypes();

    $(document).on('change', '#edu_type_select', function(){
        
        var education_type_id = $('#edu_type_select').val();
        loadQualifications(education_type_id);
    });

    $(document).on('click', '#btn_edu_submit', function(e){
        e.preventDefault();

        // Validate required fields
        var eduType = $('#edu_type_select').val().trim();
        var eduQual = $('#edu_qual_select').val().trim();
        var isCurrentStudy = $('#edu_cur_study_check').is(':checked') ? 1 : 0;

        if (!eduType) {
            unsuccessPopup('Please select an <strong>education type.</strong>','');
            return;
        }

        if (!eduQual) {
            unsuccessPopup('Please select a <strong>qualification.</strong>','');
            return;
        }

        // Create a new FormData object
        var educationFormData = new FormData($('#form_education_data')[0]);

        // Set the value for the current study checkbox
        educationFormData.set('edu_cur_study_check', isCurrentStudy);

        // Append an extra parameter to formData
        educationFormData.append('student_id', student_id);
        educationFormData.append('SUBMIT_EDUCATION_DATA', 1);

        // Log the form data
        // for (var pair of educationFormData.entries()) {
        //     console.log(pair[0] + ': ' + pair[1]);
        // }
        // console.log(educationFormData);

        // Perform the AJAX request
        $.ajax({
            type: 'POST',
            url: 'classes/StudentController.php',
            data: educationFormData,
            processData: false, // Prevent jQuery from automatically transforming the data into a query string
            contentType: false, // Prevent jQuery from setting the content type
            success: function (response) {
                var resp = $.parseJSON(response);

                if(resp.status == 1){

                    Swal.fire({
                        title: 'SUCCESS',
                        html: resp.message,
                        allowOutsideClick:false,
                        allowEscapeKey:false,
                        customClass: {
                            popup: 'suc-pop',
                            title: 'suc-pop-title',
                            content: 'suc-pop-content',
                            confirmButton: 'suc-pop-btn-ok'
                        }
                    }).then(okay => {
                        // saveActiveTabIndex();
                        location.reload();
                        // $('#form_education_data')[0].reset();
                        //loadEducationInfoByStudent(student_id);
                    });

                }else if(resp.status == 0){
                    unsuccessPopup(resp.message,'');

                }
                
            },
            error: function (xhr, status, error) {
                alert('Form submission failed!');
                console.error(xhr);
            }
        });
    });

    $(document).on('click', '#btn_pe_submit', function(e){
        e.preventDefault();

        // Validate required fields
        var peJobTitle = $('#pe_job_title').val().trim();
        var isCurrentWork = $('#pe_current_work_check').is(':checked') ? 1 : 0;

        if (!peJobTitle) {
            unsuccessPopup('<strong>Job Title</strong> cannot be empty!','');
            return;
        }

        // Create a new FormData object
        var workFormData = new FormData($('#form_work_data')[0]);

        // Set the value for the current study checkbox
        workFormData.set('pe_current_work_check', isCurrentWork);

        // Append an extra parameter to formData
        workFormData.append('student_id', student_id);
        workFormData.append('SUBMIT_WORK_DATA', 1);

        // Log the form data
        // for (var pair of workFormData.entries()) {
        //     console.log(pair[0] + ': ' + pair[1]);
        // }
        // console.log(workFormData);

        // Perform the AJAX request
        $.ajax({
            type: 'POST',
            url: 'classes/StudentController.php',
            data: workFormData,
            processData: false, // Prevent jQuery from automatically transforming the data into a query string
            contentType: false, // Prevent jQuery from setting the content type
            success: function (response) {

                var resp = $.parseJSON(response)

                if(resp.status == 1){

                    Swal.fire({
                        title: 'SUCCESS',
                        html: resp.message,
                        allowOutsideClick:false,
                        allowEscapeKey:false,
                        customClass: {
                            popup: 'suc-pop',
                            title: 'suc-pop-title',
                            content: 'suc-pop-content',
                            confirmButton: 'suc-pop-btn-ok'
                        }
                    }).then(okay => {
                        // saveActiveTabIndex();
                        location.reload();
                        // $('#form_education_data')[0].reset();
                        //loadEducationInfoByStudent(student_id);
                    });
                }else if(resp.status == 0){
                    unsuccessPopup(resp.message,'');

                }
                
            },
            error: function (xhr, status, error) {
                alert('Form submission failed!');
                console.error(xhr);
            }
        });
    });

    $(document).on('click', '#btn_ques_submit', function(e){
        e.preventDefault();

        var ques_title = $('#ques_title').val().trim();
        var ques_answer = $('#ques_answer').val().trim();

        if (ques_title == '' || ques_answer == '') {
            unsuccessPopup('Both the <strong>Question and the Answer</strong> are required!','');
            return;
        }

        // Create a new FormData object
        var portfolioFormData = new FormData($('#form_portfolio')[0]);

        // Append an extra parameter to formData
        portfolioFormData.append('student_id', student_id);
        portfolioFormData.append('SUBMIT_PORTFOLIO_DATA', 1);

        // Log the form data
        // for (var pair of portfolioFormData.entries()) {
        //     console.log(pair[0] + ': ' + pair[1]);
        // }
        // console.log(portfolioFormData);

        // Perform the AJAX request
        $.ajax({
            type: 'POST',
            url: 'classes/StudentController.php',
            data: portfolioFormData,
            processData: false, // Prevent jQuery from automatically transforming the data into a query string
            contentType: false, // Prevent jQuery from setting the content type
            success: function (response) {

                var resp = $.parseJSON(response)
                
                if(resp.status == 1){

                    Swal.fire({
                        title: 'SUCCESS',
                        html: resp.message,
                        allowOutsideClick:false,
                        allowEscapeKey:false,
                        customClass: {
                            popup: 'suc-pop',
                            title: 'suc-pop-title',
                            content: 'suc-pop-content',
                            confirmButton: 'suc-pop-btn-ok'
                        }
                    }).then(okay => {
                        // saveActiveTabIndex();
                        // location.reload();
                        $('#form_portfolio')[0].reset();
                        loadPortfoliosByStudent(student_id);
                    });

                }else if(resp.status == 0){
                    unsuccessPopup(resp.message,'');

                }
                
            },
            error: function (xhr, status, error) {
                alert('Form submission failed!');
                console.error(xhr);
            }
        });
    
    });

    $(document).on('click', '#btn_edu_doc_update', function() {

        var education_id = String($(this).data('edu-id')).trim();
        
        if (education_id == '' && student_id == '') {
            unsuccessPopup('<strong>Invalid Updatation,</strong> Try Again!','');
            return;
        }
        
        var formData = new FormData();
        formData.append('UPDATE_EDU_DOCUMENT', 1);
        formData.append('student_id', student_id);
        formData.append('education_id', education_id);
        
        var fileInput = $('#edu_document_update')[0];
        
        if (fileInput.files.length > 0) {
            formData.append('edu_document_update', fileInput.files[0]);
        }else{
            unsuccessPopup('<strong>No file selected.</strong> Please choose a file to upload!');
            return;
        }
        
        $.ajax({
            type: 'POST',
            url: 'classes/StudentController.php',
            data: formData,
            processData: false, // Prevent jQuery from automatically transforming the data into a query string
            contentType: false, // Prevent jQuery from setting the content type
            success: function (response) {

                var resp = $.parseJSON(response)

                if(resp.status == 1){   
                    successPopup(resp.message,'');

                }else if(resp.status == 0){
                    unsuccessPopup(resp.message,'');
                }
                
            },
            error: function (xhr, status, error) {
                console.error(xhr);
                unsuccessPopup('Invalid Request','');

            }
        });

    });

    $(document).on('click', '#btn_work_doc_update', function() {

        var work_id = String($(this).data('wrk-id')).trim();

        if (work_id == '' && student_id == '') {
            unsuccessPopup('<strong>Invalid Updatation,</strong> Try Again!','');
            return;
        }
        
        var formData = new FormData();
        formData.append('UPDATE_WORK_DOCUMENT', 1);
        formData.append('student_id', student_id);
        formData.append('work_id', work_id);
        
        var fileInput = $('#pe_document_update')[0];
        
        if (fileInput.files.length > 0) {
            formData.append('pe_document_update', fileInput.files[0]);
        }else{
            unsuccessPopup('<strong>No file selected.</strong> Please choose a file to upload!');
            return;
        }
        
        $.ajax({
            type: 'POST',
            url: 'classes/StudentController.php',
            data: formData,
            processData: false, // Prevent jQuery from automatically transforming the data into a query string
            contentType: false, // Prevent jQuery from setting the content type
            success: function (response) {

                var resp = $.parseJSON(response)

                if(resp.status == 1){   
                    successPopup(resp.message,'');

                }else if(resp.status == 0){
                    unsuccessPopup(resp.message,'');
                }
                
            },
            error: function (xhr, status, error) {
                console.error(xhr);
                unsuccessPopup('Invalid Request','');

            }
        });

    });
    
    $(document).on('click', '#btn_parent_submit', function(e){
        e.preventDefault();

        if (student_id == '') {
            unsuccessPopup('Invalid Request','');
            return;
        }

        // Create a new FormData object
        var parentsFormData = new FormData($('#form_parents')[0]);

        // Append an extra parameter to formData
        parentsFormData.append('student_id', student_id);
        parentsFormData.append('SUBMIT_PARENT_DATA', 1);

        // Perform the AJAX request
        $.ajax({
            type: 'POST',
            url: 'classes/StudentController.php',
            data: parentsFormData,
            processData: false, // Prevent jQuery from automatically transforming the data into a query string
            contentType: false, // Prevent jQuery from setting the content type
            success: function (response) {

                var resp = $.parseJSON(response)
                console.log(resp);

                if(resp.status == 1){
                    successPopup(resp.message,'');
                }else if(resp.status == 0){
                    unsuccessPopup(resp.message,'');

                }
                
            },
            error: function (xhr, status, error) {
                alert('Form submission failed!');
                console.error(xhr);
            }
        });


    });

    $(document).on('click', '#btn_back_all_students', function() {
        // Your code to redirect back
        window.location.href = 'all-students.php';
    });

});



function getStudentDetailsById(student_id){

    if(student_id != ''){

        $.ajax({
            type: 'GET',
            url: 'classes/StudentController.php', // Replace with the URL of your server-side script
            data: {'VIEW_STUDENT':1, 'student_id':student_id},
            dataType: 'json', // Assuming the response is in JSON format
            success: function(data) {

                var student_array = data;
                // var student_info = data.message.student_info.status
                console.log(student_array);

                if(student_array.status == 1){

                    // student basic infor - start
                    if(student_array.message.student_info.status == 1){
                    
                        var student_info = student_array.message.student_info.message[0];

                        var student_status = '';
                        if(student_info.student_status == 1){
                            student_status = '<span class="student-registered">Registered</span>';
                        }else if(student_info.student_status == 2){
                            student_status = '<span class="student-enrolled">Enrolled</span>';
                        }else if(student_info.student_status == 3){
                            student_status = '<span class="student-blocked">Blocked</span>';
                        }

                        
                        $('#student_id').html(student_info.student_id);
                        $('#student_status').html(student_status);
                        $('#first_name').html(student_info.student_first_name);
                        $('#last_name').html(student_info.student_last_name);
                        $('#student_gender').html(student_info.student_gender);
                        $('#nic_passport_id').html(student_info.student_nic_or_passport_id);
                        $('#pref_lang').html(student_info.student_pref_lang);
                        $('#campus_name').html(student_info.campus_name);
                        $('#branch_name').html(student_info.branch_name);
                        $('#phone_1').html(student_info.student_phone_1);
                        $('#phone_2').html(student_info.student_phone_2);
                        $('#email_address').html(student_info.student_email);
                        $('#textarea_address').html(student_info.student_address);
                        $('#textarea_student_note').html(student_info.student_note);
                    
                    }else{
                        unsuccessPopup('Student not available!', 'all-students.php');
                    }
                    // student basic infor - end


                    // Education qualification - start
                    var education_info = student_array.message.education_info;
                    generateEducationInfoTable(education_info);
                    // Education qualification - end

                    // professional experience - start
                    var work_info = student_array.message.work_info;
                    generateWorkInfoTable(work_info);
                    // professional experience - end

                    // parent info - start
                    console.log(student_array.message.parent_info);
                    var parent_info = student_array.message.parent_info;
                    generateParentInfo(parent_info);
                    // parent info - end

                    // portfolio - start
                    var portfolio_info = student_array.message.portfolio_info;
                    generatePortfolioAccordion(portfolio_info);
                    // portfolio - end




                    // Open the tab where click submit button
                    // openPreviousOpenTab();

                }else if(student_array.status == 0){
                    unsuccessPopup(data.message, 'all-students.php');
                }

                return false;
    
                


                if(data.status == '1'){
    
                    var resp = data.message[0];
                    var lead_notes_arr = JSON.parse(data.message[0].all_notes);
                    var note_arr_count = lead_notes_arr.length;
                    var lead_status = '';
    
                    if (resp.lead_status == 0) { // pending approval from center function
                        lead_status = '<span class="lead-pending">Pending</span>';
                    }else if(resp.lead_status == 1){ // assigned to counselor
                        lead_status = '<span class="lead-assigned">Assigned</span>';
                    }else if(resp.lead_status == 2){ // rejected by center function
                        lead_status = '<span class="lead-rejected">Rejected</span>';
                    }else if(resp.lead_status == 3){ // not prefer to join.
                        lead_status = '<span class="lead-prospective">Not Prospective</span>';
                    }else if(resp.lead_status == 4){ // convertible
                        lead_status = '<span class="lead-convertible">Convertible</span>';
                    }else if(resp.lead_status == 5){ // future intakes
                        lead_status = '<span class="lead-future-intake">Future Intake</span>';
                    }else if(resp.lead_status == 6){ // completed | pending list for register to system as a student
                        lead_status = '<span class="lead-completed">Completed</span>';
                    }else if(resp.lead_status == 7){ // registered | register with the system as a student
                        lead_status = '<span class="lead-registered">Registered</span>';
                    }
    
                    $('#lead_id').html(resp.lead_id);
                    $('#lead_status').html(lead_status);
                    $('#lead_first_name').html(resp.lead_first_name);
                    $('#lead_last_name').html(resp.lead_last_name);
                    $('#lead_pref_lang').html(resp.lead_pref_lang);
                    $('#lead_source').html(resp.lead_source);
                    $('#laad_phone_1').html(resp.lead_phone_1);
                    $('#laad_phone_2').html(resp.lead_phone_2);
                    $('#lead_email').html(resp.lead_email);
                    $('#laad_campus').html(resp.campus_name);
                    $('#laad_branch').html(resp.branch_name);
                    $('#lead_address').html(resp.lead_address);
                    $('#laad_created_date_time').html(resp.lead_created_date_time);
                    $('#laad_updated_date_time').html(resp.lead_updated_date_time);
    
                    if(note_arr_count > 0){
                        //show lead notes in table
                        lead_notes_arr.forEach((element, index) => {
                            
                            var note_row = 
                            '<tr>' +
                                '<td>' + ++index + '</td>' +
                                '<td><textarea class="lead_note_textarea" rows="3" readonly>'+ element.note_description +'</textarea></td>' +
                                '<td>'+ element.note_created_date_time +'</td>' +
                            '</tr>';
    
                            $('#lead_notes_body').append(note_row);
                        });
                        
                    }else {
                        var note_row = 
                            '<tr><td colspan="3" class="text-center">Notes not available!</td></tr>';
    
                        $('#lead_notes_body').append(note_row);
                    }
    
                }else {
                    unsuccessPopup(data.message, 'pending-registrants.php');
                }
    
            },
            error: function() {
                unsuccessPopup('Failed Request!');
            }
        });

    }else{
        unsuccessPopup('Invalid Request!', 'all-students.php');
    }

}

function loadEucationTypes(){

    $.ajax({
        type: 'GET',
        url: 'classes/StudentController.php', // Replace with the URL of your server-side script
        data: {'LOAD_EDUCATION_TYPES':1},
        dataType: 'json', // Assuming the response is in JSON format
        success: function(response) {

            if(response.status == 1){

                response.message.forEach( function(option, i){
                    var optionEle = $('<option></option>').attr('value', option.education_type_id).text(option.education_type);
                    $('#edu_type_select').append(optionEle);
                });
            }
            
        },
        error: function() {
            unsuccessPopup('Failed Request!');
        }
    });

}

function loadQualifications(education_type_id){

    if(education_type_id != ''){

        $.ajax({
            type: 'GET',
            url: 'classes/StudentController.php', // Replace with the URL of your server-side script
            data: {'LOAD_QUALIFICATIONS':1, 'education_type_id':education_type_id},
            dataType: 'json', // Assuming the response is in JSON format
            success: function(response) {

                if(response.status == 1){
    
                    var optionEle = '<option value="" selected>Select an option</option>'; // Empty option at the top
                    response.message.forEach( function(option, i){
                        optionEle += '<option value="'+ option.education_qual_id +'">' + option.education_qual + '</option>';
                        
                    });
                        
                    $('#edu_qual_select').html(optionEle);
    
                }
                
            },
            error: function() {
                unsuccessPopup('Failed Request!');
            }
        });

    }else{
        
        var optionEle = '<option value="" selected>Select an option</option>'; // Empty option at the top
        $('#edu_qual_select').html(optionEle);

    }

}

function generateEducationInfoTable(education_info){

    var table_arr = education_info.message;

    // Check if DataTable is already initialized and destroy it if necessary
    // if ($.fn.DataTable.isDataTable('#edu_education_info_table')) {
    //     $('#edu_education_info_table').DataTable().clear().destroy();
    // }

    $('#edu_education_info_table').DataTable().destroy();

    var table_education = $('#edu_education_info_table').DataTable({
        data: table_arr,
        columns: [
            { 'data':'id'}, // 0
            { 'data':'education_type'}, // 1
            { 'data':'education_qual'}, // 2
            { 'data':'education_start_date'}, // 3
            { 'data':'education_end_date'}, // 4
            { 'data':'education_current_study'}, // 5
            { 'data':'education_doc_status'}, // 6
            { 'data':'actions'} // 7
        ],
        columnDefs: [
            {
                targets: 0, // Index of the first column (ID)
                visible: true, // Hide the column from the user
                orderable: true, // Disable sorting for this column
                searchable: false, // Disable searching for this column
                className: 'text-center',
                render: function (data, type, row, meta) {
                    // Auto-incremented ID starts from 1
                    return meta.row + 1;
                }
            },
            {
                targets: 3, // Index of the 'start_date' and 'end_date' column
                className: 'text-center',
            },
            {
                targets: 4, // Index of the 'end_date' column
                className: 'text-center'
            },
            {
                targets: 5, // education_current_study
                className: 'text-center',
                render: function(data, type, row, meta) {

                    var current_study = '';
                    if(row.education_current_study == 1){
                        current_study = '<i data-feather="check" class="me-2 edu_check_mark_table"></i>';
                    }else{
                        current_study = '-';
                    }

                    return current_study;
                }
            },
            {
                targets: 6, // education_doc_status
                className: 'text-center',
                render: function(data, type, row, meta) {

                    var doc_verify = '';
                    if(row.education_doc_status == 0){ // document not uploaded
                        doc_verify = '<span class="doc_na">N/A</span>';
                    }else if(row.education_doc_status == 1){ //pending verified
                        doc_verify = '<span class="doc_pending">Pending</span>';
                    }else if(row.education_doc_status == 2){ // verified
                        doc_verify = '<span class="doc_verified">Verified</span>';
                    }else if(row.education_doc_status == 3){ // rejected
                        doc_verify = '<span class="doc_rejected">Rejected</span>';
                    }
                    
                    return doc_verify;
                }
            },
            {
                targets: -1, // Index of the last column
                orderable: false, // Make the column not sortable
                searchable: false, // Make the column not searchable
                className: 'text-center',
                render: function(data, type, row, meta) {

                    // Create buttons for view, edit
                    var btn_view = '<button class="btn edu_table_btn_view" data-education-id="' + row.education_id + '">VIEW</button>';

                    return btn_view;
                }
            }
        ],
        drawCallback: function(settings) {
            feather.replace(); // Replace all data-feather attributes with SVGs
        }
    });

    // Handle the click event for the VIEW button
    $('#edu_education_info_table tbody').on('click', '.edu_table_btn_view', function () {
        var tr = $(this).closest('tr');
        var row = table_education.row(tr);

        if (row.child.isShown()) {
            // This row is already open - close it
            row.child.hide();
            tr.removeClass('shown');
        } else {
            // Open this row
            row.child(format(row.data())).show();
            tr.addClass('shown');
        }
    });

    // Format function for row details
    function format(d) {

        var document_path = '';
        
        if(d.education_doc_status == 0){ // document not uploaded
            document_path = '<input type="file" class="form-control edu_document_update" id="edu_document_update" name="edu_document_update" accept=".pdf">' + 
            '<div class="col-md-12 edu_btn_submit_group">' +
                '<button class="btn btn-primary mt-md-0 mt-2" id="btn_edu_doc_update" data-edu-id="' +  d.education_id + '"> Update &nbsp;<i class="fa fa-save"></i></button>' +
            '</div>';
        }else if(d.education_doc_status == 1){ // document verification is pending
            document_path = '<span class="doc_pending">Pending</span>';
        }else if(d.education_doc_status == 2){ // document verified
            document_path = '<a href="..'+ d.education_doc_path +'" target="_blank"><i class="fa fa-file edu_doc_icon"></i></a>';
        }else if(d.education_doc_status == 3){ // document rejected
            document_path = '<span class="doc_rejected">Rejected</span>';
        }

        // Create the child row content with additional data
        return '<div class="row form_cstm_row">' +
               '<div class="col-md-4 form_cstm_col cstm_mq">' +
                   '<strong><label>Institute</label></strong>' +
                   '<textarea class="form-control edu_institute_table" id="edu_institute_table" placeholder="" readonly>' + d.education_institute + '</textarea>' +
               '</div>' +
               '<div class="col-md-4 form_cstm_col cstm_mq">' +
                   '<strong><label>Additional Info</label></strong>' +
                   '<textarea class="form-control edu_additional_info_table" id="edu_additional_info_table" placeholder="" readonly>' + d.education_additional_info + '</textarea>' +
               '</div>' +
               '<div class="col-md-4 form_cstm_col">' +
                   '<strong><label>Document (.pdf)</label></strong>' +
                   '<p>'+ document_path +'</p>' +
               '</div>' +
           '</div>';
    }

}

function saveActiveTabIndex() {
    var activeTab = $('#top-tab .nav-link.active');
    var activeTabIndex = activeTab.parent().index();
    localStorage.setItem('activeTabIndex', activeTabIndex);
}

function generateWorkInfoTable(work_info){

        var table_arr = work_info.message;
    
        // Check if DataTable is already initialized and destroy it if necessary
        // if ($.fn.DataTable.isDataTable('#edu_education_info_table')) {
        //     $('#edu_education_info_table').DataTable().clear().destroy();
        // }
    
        $('#pe_work_info_table').DataTable().destroy();
    
        var table_work = $('#pe_work_info_table').DataTable({
            data: table_arr,
            columns: [
                { 'data':'id'}, // 0
                { 'data':'work_job_title'}, // 1
                { 'data':'work_organization'}, // 2
                { 'data':'work_start_date'}, // 3
                { 'data':'work_end_date'}, // 4
                { 'data':'work_current_work'}, // 5
                { 'data':'work_doc_status'}, // 6
                { 'data':'actions'} // 7
            ],
            columnDefs: [
                {
                    targets: 0, // Index of the first column (ID)
                    visible: true, // Hide the column from the user
                    orderable: true, // Disable sorting for this column
                    searchable: false, // Disable searching for this column
                    className: 'text-center',
                    render: function (data, type, row, meta) {
                        // Auto-incremented ID starts from 1
                        return meta.row + 1;
                    }
                },
                {
                    targets: 3, // Index of the 'work_start_date'
                    className: 'text-center',
                },
                {
                    targets: 4, // Index of the 'work_end_date' column
                    className: 'text-center'
                },
                {
                    targets: 5, // work_current_work
                    className: 'text-center',
                    render: function(data, type, row, meta) {
    
                        var current_work = '';
                        if(row.work_current_work == 1){
                            current_work = '<i data-feather="check" class="me-2 edu_check_mark_table"></i>';
                        }else{
                            current_work = '-';
                        }
    
                        return current_work;
                    }
                },
                {
                    targets: 6, // work_doc_status
                    className: 'text-center',
                    render: function(data, type, row, meta) {
    
                        var doc_status = '';
                        if(row.work_doc_status == 0){ // document not uploaded
                            doc_verify = '<span class="doc_na">N/A</span>';
                        }else if(row.work_doc_status == 1){ //pending verified
                            doc_verify = '<span class="doc_available">Available</span>';
                        }
                        
                        return doc_verify;
                    }
                },
                {
                    targets: -1, // Index of the last column
                    orderable: false, // Make the column not sortable
                    searchable: false, // Make the column not searchable
                    className: 'text-center',
                    render: function(data, type, row, meta) {
    
                        // Create buttons for view, edit
                        var btn_view = '<button class="btn work_table_btn_view" data-work-id="' + row.work_id + '">VIEW</button>';
    
                        return btn_view;
                    }
                }
            ],
            drawCallback: function(settings) {
                feather.replace(); // Replace all data-feather attributes with SVGs
            }
        });
    
        // Handle the click event for the VIEW button
        $('#pe_work_info_table tbody').on('click', '.work_table_btn_view', function () {

            var tr = $(this).closest('tr');
            var row = table_work.row(tr);
    
            if (row.child.isShown()) {
                // This row is already open - close it
                row.child.hide();
                tr.removeClass('shown');
            } else {
                // Open this row
                row.child(format(row.data())).show();
                tr.addClass('shown');
            }
        });
    
        // Format function for row details
        function format(d) {

            var document_path = '';
            if(d.work_doc_status == 0){ // DOC Not available (not uploaded)
                document_path = '<input type="file" class="form-control pe_document_update" id="pe_document_update" accept=".pdf" name="pe_document_update">' +
            '<div class="col-md-12 pe_btn_submit_group">' +
                '<button class="btn btn-primary mt-md-0 mt-2" id="btn_work_doc_update" data-wrk-id="' +  d.work_id + '"> Update &nbsp;<i class="fa fa-save"></i></button>' +
            '</div>';
            }else if(d.work_doc_status == 1){ // Document available (uploaded)
                document_path = '<a href="..'+ d.work_doc_path +'" target="_blank"><i class="fa fa-file edu_doc_icon"></i></a>';
            }
    
            // Create the child row content with additional data
            return '<div class="row form_cstm_row">' +
            '<div class="col-md-8 form_cstm_col cstm_mq">' +
                '<strong><label>Additional Info</label></strong>' +
                '<textarea class="form-control pe_additional_info_table" id="pe_additional_info_table" placeholder="" readonly>' + d.work_additional_info + '</textarea>' +
            '</div>' +
            
            '<div class="col-md-4 form_cstm_col">' +
                '<strong><label>Document (.pdf)</label></strong>' +
                '<p>' +  document_path + '</p>' +
            '</div>' +
            '</div>';
        }
    
}

function generateParentInfo(parent_info){

    if(Array.isArray(parent_info.message) && parent_info.message.length > 0 ){

        var parentData = parent_info.message[0];
        
        $('#parent_f_name').val(parentData.father_name);
        $('#parent_f_occupation').val(parentData.father_occupation);
        $('#parent_f_organization').val(parentData.father_organization);
        $('#parent_f_phone_1').val(parentData.father_phone_1);
        $('#parent_f_phone_2').val(parentData.father_phone_2);
        $('#parent_m_name').val(parentData.mother_name);
        $('#parent_m_occupation').val(parentData.mother_occupation);
        $('#parent_m_organization').val(parentData.mother_organization);
        $('#parent_m_phone_1').val(parentData.mother_phone_1);
        $('#parent_m_phone_2').val(parentData.mother_phone_2);
    }

}

function generatePortfolioAccordion(portfolio_info){

    var portfolio_items = '';

    if(portfolio_info.message.length > 0 ){
        
        portfolio_info.message.forEach((element, index) => {

            portfolio_items += 
            '<div class="accordion-item ques_item" id="portfolio_item_'+ element.portfolio_id +'">' +
                '<h2 class="accordion-header" id="flush-headingOne">' +
                '<button class="accordion-button collapsed ques_btn" type="button" data-bs-toggle="collapse" data-bs-target="#porfolio_target_'+ index +'" aria-expanded="false" aria-controls="flush-collapseOne">' + element.portfolio_question + '</button>' +
                '</h2>' +
                '<div id="porfolio_target_'+ index +'" class="accordion-collapse collapse" aria-labelledby="flush-headingOne" data-bs-parent="#portfolio_list">' +
                    '<div class="accordion-body">' + element.portfolio_answer + '</div>' +
                '</div>' +
            '</div>';
        });

        $('#portfolio_list').html(portfolio_items);

    }else{
        portfolio_items = '<p class="no_portfolio">No portfolio available!</p>'
        $('#portfolio_list').html(portfolio_items);
    }

}

function successPopup(msg, customURL){
    Swal.fire({
        title: 'SUCCESS',
        text: msg,
        allowOutsideClick:false,
        allowEscapeKey:false,
        customClass: {
            popup: 'suc-pop',
            title: 'suc-pop-title',
            content: 'suc-pop-content',
            confirmButton: 'suc-pop-btn-ok'
        }
    }).then(okay => {
        if (okay) {
            if(customURL){
                window.location.href = customURL;
            }else{
                location.reload();
            }
        }
    });
}

function unsuccessPopup(msg, customURL){
    Swal.fire({
        title: 'UNSUCCESS',
        html: msg,
        allowOutsideClick:false,
        allowEscapeKey:false,
        customClass: {
            popup: 'unsuc-pop',
            title: 'unsuc-pop-title',
            confirmButton: 'unsuc-pop-btn-ok'
        }
    }).then(okay => {
        if (okay) {
            if(customURL){
                window.location.href = customURL;
            }
        }
    });
}

function infoHTMLPopup(msg, customURL){
    Swal.fire({
        title: 'INFORMATION',
        html: msg,
        allowOutsideClick:false,
        allowEscapeKey:false,
        customClass: {
            popup: 'info-pop',
            title: 'info-pop-title',
            confirmButton: 'info-pop-btn-ok'
        }
    }).then(okay => {
        if (okay) {
            if(customURL){
                window.location.href = customURL;
            }
        }
    });
}

function openPreviousOpenTab(){

    var activeTabIndex = localStorage.getItem('activeTabIndex');

    // If an active tab index is found, activate the corresponding tab and then remove the index from localStorage
    if (activeTabIndex !== null) {
        $('#top-tab .nav-item').eq(activeTabIndex).find('.nav-link').tab('show');
        // localStorage.removeItem('activeTabIndex');
    }

}

function loadPortfoliosByStudent(student_id){

    if(student_id != ''){

        $.ajax({
            type: 'GET',
            url: 'classes/StudentController.php', // Replace with the URL of your server-side script
            data: {'LOAD_PORTFOLIOS_BY_STU_ID':1, 'student_id':student_id},
            dataType: 'json', // Assuming the response is in JSON format
            success: function(data) {

                if(data){
                    generatePortfolioAccordion(data);
                }
    
            },
            error: function() {
                unsuccessPopup('Failed Request!');
            }
        });

    }else{
        unsuccessPopup('Invalid Request!', 'all-students.php');
    }
    
}

function showPageLoader(){
    var loadingDiv = $('<div id="loading" style="display: none;"><img src="../assets/loading2.gif" alt="Loading..."></div>');
    $('body').append(loadingDiv);

    // Show the loading animation
    $('#loading').show();
}

function removePageLoader(){
    $('#loading').fadeOut('slow', function() {
        $(this).remove(); // Optionally remove the loading element from the DOM
   });
}

// function loadEducationInfoByStudent(student_id){
//     console.log(student_id);

//     if(student_id != ''){

//         $.ajax({
//             type: 'GET',
//             url: 'classes/StudentController.php', // Replace with the URL of your server-side script
//             data: {'LOAD_EDUCATION_INFO_BY_STU_ID':1, 'student_id':student_id},
//             dataType: 'json', // Assuming the response is in JSON format
//             success: function(data) {

//                 console.log(data);
//                 if(data.status == 1){
//                     generateEducationInfoTable(data);

//                 }
    
//             },
//             error: function() {
//                 unsuccessPopup('Failed Request!');
//             }
//         });

//     }else{
//         unsuccessPopup('Invalid Request!', 'all-students.php');
//     }

    
// }