
//initializing the table
if ($.fn.DataTable.isDataTable('#zero_config')) {
    $('#zero_config').DataTable().destroy();
}

//load data table
let dataTable = $('#zero_config').DataTable({
    processing: true,
    ajax: {
        url: base_url + 'class/getData',
        dataSrc: 'data'
    },
    columnDefs: [
        {
            targets: [4,5,7],
            orderable: false
        }
    ]
});

//submit save form
$('#saveForm').submit(function(e){
    e.preventDefault();

    $.ajax({
        url: base_url + 'class/save',
        type: 'POST',
        data: $(this).serialize(),
        dataType: 'json',
        success: function(response){
            if(response.status == 'success'){
                $('#saveForm')[0].reset();
                $('#zero_config').DataTable().ajax.reload(null, false);
                showMessage('success', response.message);
            }
        },
        error: function(){
            showMessage('error', 'Error saving data');
        }
    });
});

//load class details to update form
$(document).on('click', '#btnUpdate', function(){
    let id = $(this).data('id');

    $.ajax({
        url: base_url + "class/get/" + id,
        type: "GET",
        dataType: "json",
        success: function(data){alert(data);
            $('#updid').val(data.id);
            $('#updname').val(data.name);
            $('#updcode').val(data.code);
            $('#upddescription').val(data.description);
            $('#updclass_day').val(data.class_day);
            $('#updstarted_date').val(data.started_date);
            $('#updstart_time').val(data.start_time);
            $('#updend_time').val(data.end_time);
            $('#updstatus').val(data.status);
            $('#updclass_type_id').val(data.class_type_id);
            $('#updpayment_type_id').val(data.payment_type_id);
            $('#updgrade_id').val(data.grade_id);

            // Students and fee
            let studentIds = [];

            $('#updstudentFeeTable').empty();

            $.each(data.students, function(index, student){
                studentIds.push(student.student_id);
                let studentName = $('#updstudent_id option[value="' + student.student_id + '"]').text();

                $('#updstudentFeeTable').append(`
                <tr id="student_row_${student.student_id}" data-student-id="${student.student_id}">
                    <td>${studentName} <input type="hidden" name="student_id[]" value="${student.student_id}"></td>
                    <td><input type="number" class="form-control" name="fee[${student.student_id}]" value="${student.fee}"></td>
                </tr>
                `);
            });

            $('#updstudent_id').val(studentIds);
            // Class Days
                let selectedDays = [];
                $('#updclassDayTable').empty();

                $.each(data.class_days, function(index, day){
                    selectedDays.push(day.day_id.toString());
                    let dayName = $('#updclass_day option[value="' + day.day_id + '"]').text();
                    $('#updclassDayTable').append(`
                    <tr id="day_row_${day.day_id}" data-day-id="${day.day_id}">
                        <td>${dayName} <input type="hidden" name="day_id[]" value="${day.day_id}"></td>
                        <td><input type="time" class="form-control" name="start_time[${day.day_id}]" value="${day.start_time}"></td>
                        <td> <input type="time" class="form-control" name="end_time[${day.day_id}]" value="${day.end_time}"></td>
                    </tr>
                    `);
                });
            $('#updclass_day').val(selectedDays);
        }
    });
});

//submit update form
$('#updateForm').submit(function(e){
    e.preventDefault();

    $.ajax({
        url: base_url + 'class/update',
        type: 'POST',
        data: $(this).serialize(),
        dataType: 'json',
        success: function(response){
            if(response.status == 'success'){
                $('#updateModal').modal('hide');
                $('#updateForm')[0].reset();
                $('#zero_config').DataTable().ajax.reload(null, false);
                showMessage('success', response.message);
            }
        }
    });
});

//student fee
$('#updstudent_id').change(function(){

    let selectedStudents = $(this).val() || [];

    // Remove unselected students
    $('#updstudentFeeTable tr').each(function(){
        let studentId = $(this).data('student-id').toString();

        if (!selectedStudents.includes(studentId)) {
            $(this).remove();
        }
    });

    // Add newly selected students
    $('#updstudent_id option:selected').each(function(){
        let studentId = $(this).val();
        let studentName = $(this).text();

        if($('#student_row_' + studentId).length == 0){
            $('#updstudentFeeTable').append(`
                <tr id="student_row_${studentId}" data-student-id="${studentId}">
                    <td>${studentName}<input type="hidden" name="student_id[]" value="${studentId}"></td>
                    <td><input type="number" class="form-control" name="fee[${studentId}]" value="0"></td>
                </tr>
            `);
        }
    });
});

$('#updclass_day').change(function(){
    let selectedDays = $(this).val() || [];

    // Remove unselected days
    $('#updclassDayTable tr').each(function(){
        let dayId = $(this).attr('data-day-id');
        if(!selectedDays.includes(dayId)){
            $(this).remove();
        }
    });

    // Add new days
    $('#updclass_day option:selected').each(function(){
        let dayId = $(this).val();
        let dayName = $(this).text();

        if($('#day_row_' + dayId).length == 0){
            $('#updclassDayTable').append(`
                <tr id="day_row_${dayId}"  data-day-id="${dayId}">
                    <td>${dayName}
                        <input type="hidden" name="day_id[]" value="${dayId}"></td>
                    <td><input type="time" class="form-control" name="start_time[${dayId}]"></td>
                    <td><input type="time" class="form-control" name="end_time[${dayId}]"></td>
                </tr>
            `);
        }
    });
});

//class day
$('#updclass_day').change(function(){
    let selectedDays = $(this).val() || [];

    // Remove unselected days
    $('#updclassDayTable tr').each(function(){
        let dayId = $(this).attr('data-day-id');
        if (!selectedDays.includes(dayId)) {
            $(this).remove();
        }
    });

    // Add selected days
    $('#updclass_day option:selected').each(function(){
        let dayId = $(this).val();
        let dayName = $(this).text();

        if ($('#updclassDayTable').find('#day_row_' + dayId).length === 0) {
            $('#updclassDayTable').append(`
                <tr id="day_row_${dayId}" data-day-id="${dayId}">
                    <td>${dayName}
                        <input type="hidden" name="day_id[]" value="${dayId}"></td>
                    <td><input type="time" name="start_time[${dayId}]" class="form-control"></td>
                    <td><input type="time" name="end_time[${dayId}]" class="form-control"></td>
                </tr>
            `);
        }
    });
});

//set deleteid from the table
$(document).on('click', '#btnDelete', function(){
    let id = $(this).data('id');
    $('#delid').val(id);
});

//delete class
$('#deleteForm').submit(function(e){
    e.preventDefault();

    $.ajax({
        url: base_url + 'class/delete',
        type: 'POST',
        data: $(this).serialize(),
        dataType: 'json',
        success: function(response){alert("fff");
            if(response.status == 'success'){
                $('#deleteModal').modal('hide');
                $('#zero_config').DataTable().ajax.reload(null, false);
                showMessage('success', response.message);
            }
        }
    });
});


//create the name and code
let class_type = "";
let grade = "";
let student = "";

let name_class_type = "";
let name_grade = "";
let name_student = "";

$('#class_type_id').change(function () {
    let class_type_id = $('#class_type_id').val();

    $.ajax({
        url: base_url + "classtype/get/" + class_type_id,
        type: "GET",
        dataType: "json",
        success: function(data){
            class_type = data.code;
            name_class_type = data.name;
            var code = grade + " " + class_type + " " + student;
            var name = name_grade + " " + name_class_type + " " + name_student;
            $('#code').val(code);
            $('#name').val(name);
        },
        error:function(){
            alert('Unable to load data');
        }
    });
});

$('#grade_id').change(function () {
    let grade_id = $('#grade_id').val();

    $.ajax({
        url: base_url + "grade/get/" + grade_id,
        type: "GET",
        dataType: "json",
        success: function(data){
            grade = data.code;
            name_grade = data.name;
            var code = grade + " " + class_type + " " + student;
            var name = name_grade + " " + name_class_type + " " + name_student;
            $('#code').val(code);
            $('#name').val(name);
        },
        error:function(){
            alert('Unable to load data');
        }
    });
});

$('#student_id').change(function () {
    let student_id = $('#student_id').val();

    $.ajax({
        url: base_url + "student/get/" + student_id,
        type: "GET",
        dataType: "json",
        success: function(data){
            student = data.first_name + " " + data.last_name;
            name_student = data.first_name + " " + data.last_name;
            var code = grade + " " + class_type + " " + student;
            var name = name_grade + " " + name_class_type + " " + name_student;
            $('#code').val(code);
            $('#name').val(name);
        },
        error:function(){
            //alert('Unable to load data');
        }
    });
});

//create student and fee table
$('#student_ids').change(function () {
    $('#studentFeeTable').empty();
    $('#student_ids option:selected').each(function () {
        let studentId = $(this).val();
        let studentName = $(this).text();

        $('#studentFeeTable').append(`
            <tr>
                <td>${studentName} <input type="hidden" name="student_id[]" value="${studentId}"></td>
                <td><input type="number" name="fee[${studentId}]" class="form-control"></td>
            </tr>
        `);
    });
});

//create class day table
$('#class_days').change(function () {
    $('#classDayTable').empty();
    $('#class_days option:selected').each(function () {
        let dayId = $(this).val();
        let dayName = $(this).text();

        $('#classDayTable').append(`
            <tr>
                <td>${dayName}<input type="hidden" name="dayId[]"value="${dayId}"></td>
                <td><input type="time" name="startTime[${dayId}]" class="form-control"></td>
                <td><input type="time" name="endTime[${dayId}]" class="form-control"></td>
            </tr>
        `);
    });
});



