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

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

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

    $.ajax({
        url: base_url + 'classdiary/save',
        type: 'POST',
        data: $(this).serialize(),
        dataType: 'json',
        success: function(response){
            if(response.status == 'success'){
                $('#saveForm')[0].reset();
                $('#student_table_body').empty();
                var today = new Date().toISOString().split('T')[0];
                $('#date').val(today);
                $('#zero_config').DataTable().ajax.reload(null, false);
                showMessage('success', response.message);
            }
        },
        error: function(){
            showMessage('error', 'Error saving data');
        }
    });
});

//get lessons according to class
$('#class_id').on('change', function() {
    var classId = $(this).val();

    //get lessons by class id
    $.ajax({
        url: base_url + "classdiary/getLessonsByClassId/" + classId,
        type: 'GET',
        dataType: 'json',
        success: function(response) {
            console.log(response);
            $('#lesson_id').html(
                '<option value="">Select Lesson</option>'
            );

            $.each(response, function(index, lesson) {

                $('#lesson_id').append(
                    '<option value="' + lesson.id + '">' + lesson.code + ' - ' + lesson.name + '</option>'
                );

            });
        },
        error: function(xhr, status, error) {
            console.log(error);
        }
    });

    //get class day and times
    $.ajax({
        url: base_url + "classdiary/getClassDayByClassId/" + classId,
        type: 'GET',
        dataType: 'json',
        success: function(response) {//alert(response.start_time);
            //alert(response.selected_day_id);
            $('#class_day').val(response.selected_day_id);
            $('#started_time').val(response.start_time.substring(0, 5));
            $('#ended_time').val(response.end_time.substring(0, 5));

            setTimeout(function () {
                calculateDuration();
            }, 100);
        },
        error: function(xhr, status, error) {
            console.log(error);
        }
    });

    //get students by class
    $.ajax({
        url: base_url + "classdiary/getStudentsByClassId/" + classId,
        type: 'GET',
        dataType: 'json',
        success: function(data) {

            $('#student_table_body').html('');

            $.each(data, function(index, data) {

                $('#student_table_body').append(
                    '<tr><td>' + data.first_name + " " + data.last_name + '<input type="hidden"\n' +
                    '                                   name="student_id[]"\n' +
                    '                                   value="' + data.id + '"></td>' +
                    '<td>' + '<div class="" data-bs-toggle="buttons" role="group">\n' +
                    '                                            <label class="btn btn-outline btn-info">\n' +
                    '                                                <div class="custom-control custom-radio">\n' +
                    '                                                    <input type="radio" id="attendance1' + data.id + '" name="attendance[' + data.id + ']" value="1"\n' +
                    '                                                        class="custom-control-input" checked>\n' +
                    '                                                    <label class="custom-control-label" for="attendance1' + data.id + '"> <i\n' +
                    '                                                            class="ti-check text-active" aria-hidden="true"></i>\n' +
                    '                                                        Present</label>\n' +
                    '                                                </div>\n' +
                    '                                            </label>\n' +
                    '                                            <label class="btn btn-outline btn-danger">\n' +
                    '                                                <div class="custom-control custom-radio">\n' +
                    '                                                    <input type="radio" id="attendance2' + data.id + '" name="attendance[' + data.id + ']" value="0"\n' +
                    '                                                        class="custom-control-input">\n' +
                    '                                                    <label class="custom-control-label" for="attendance2' + data.id + '"> <i\n' +
                    '                                                            class="ti-check text-active" aria-hidden="true"></i>\n' +
                    '                                                        Absent</label>\n' +
                    '                                                </div>\n' +
                    '                                            </label>\n' +
                    '                                        </div>' + '</td>' +
                    '<td><input type="number" class="form-control" placeholder="" id="duration[' + data.id + ']" name="duration[' + data.id + ']" required>' +
                    '<td><input type="text" class="form-control" placeholder="" id="student_comment[' + data.id + ']" name="student_comment[' + data.id + ']">'
                );
            });
        },
        error: function(xhr, status, error) {
            console.log(error);
        }
    });
});

//set today date to date
$(document).ready(function () {
    var today = new Date().toISOString().split('T')[0];
    $('#date').val(today);
});


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

    $.ajax({
        url: base_url + "classdiary/get/" + id,
        type: "GET",
        dataType: "json",
        success: function(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);
            $('#updfee').val(data.fee);
            $('#updstatus').val(data.status);
            $('#updclass_type_id').val(data.class_type_id);
            $('#updpayment_type_id').val(data.payment_type_id);
            //$('#updstudent_id').val(data.student_id);
            $('#updgrade_id').val(data.grade_id);
        },
        error:function(){
            alert('Unable to load data');
        }
    });

    //fill student list
    $.ajax({
        url: base_url + "class/getStudents/" + id,
        type: "GET",
        dataType: "json",
        success: function(data){
            $('#updstudent_id').val(data.student_ids).trigger('change');

        },
        error:function(){
            alert('Unable to load data');
        }
    });
});

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

    $.ajax({
        url: base_url + 'classdiary/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);
            }
        }
    });
});

//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 + 'classdiary/delete',
        type: 'POST',
        data: $(this).serialize(),
        dataType: 'json',
        success: function(response){
            if(response.status == 'success'){
                $('#deleteModal').modal('hide');
                $('#zero_config').DataTable().ajax.reload(null, false);
                showMessage('success', response.message);
            }
        }
    });
});



function calculateDuration() {

    var startTime = $('#started_time').val();
    var endTime = $('#ended_time').val();

    if (!startTime || !endTime) {
        return;
    }

    var start = new Date('2000-01-01T' + startTime);
    var end = new Date('2000-01-01T' + endTime);

    var duration = Math.round((end - start) / 60000); // minutes

    if (duration < 0) {
        duration = 0;
    }

    // Process each attendance group only once
    var processed = [];

    $('input[name^="attendance["]').each(function () {

        var studentId = $(this).attr('name').match(/\[(\d+)\]/)[1];

        if (processed.includes(studentId)) {
            return;
        }

        processed.push(studentId);

        var attendance = $('input[name="attendance[' + studentId + ']"]:checked').val();

        if (attendance == '1') {
            $('input[name="duration[' + studentId + ']"]').val(duration);
        } else {
            $('input[name="duration[' + studentId + ']"]').val(0);
        }
    });
}

// User manually changes times
$(document).on('change input', '#started_time, #ended_time', function () {
    calculateDuration();
});

// User changes attendance
$(document).on('change', 'input[name^="attendance["]', function () {
    calculateDuration();
});
