$(".alert-dismissible").fadeOut(0);
var table;

$(document).ready(function () {
    table = $('#datatable-fixedheader').DataTable({
        processing: true,
        serverSide: true,
        ordering: true,
        autoWidth: false,
        pageLength: 10,
        order: [],
        ajax: {
            url: BASEURL + 'book_a_health_checkup/ajax_list',
            type: 'POST'
        },
        columnDefs: [
            { targets: [0,4,5,6,7,8], orderable: false }
        ]
    });
});

function reload_table(){
    table.ajax.reload(null, false);
}

function reject_btn(id){
    $('[name="checkup_id"]').val(id);
    $('#remarks').val('');
    $('#modal2').modal('show');
}

function confirm_checkup(id){
    if(confirm('Confirm this health checkup booking?')){
        $.post(
            BASEURL + 'book_a_health_checkup/confirm_checkup/' + id,
            function(){
                reload_table();
            }
        );
    }
}
function view_checkup(id){
  $.get(BASEURL+'book_a_health_checkup/view/'+id,function(res){

    $('#v_patient_name').text(res.patient_name);
    $('#v_patient_mobile').text(res.patient_mobile);
    $('#v_patient_email').text(res.patient_email);
    $('#v_package').text(res.package_name);
    $('#v_date').text(res.appontment_date);
    $('#v_time').text(res.appontment_time);
    $('#v_description').text(res.decription ?? '-');

    let cls='status-pending', txt='Pending';
    if(res.status==1){cls='status-confirm';txt='Confirmed'}
    if(res.status==2){cls='status-reject';txt='Rejected'}

    $('#v_status')
      .removeClass()
      .addClass('status-badge '+cls)
      .text(txt);

    $('#viewCheckupModal').modal('show');
  },'json');
}


function reject_checkup(){
    if($('#remarks').val() === ''){ 
        $('#err_editor').html('Required'); 
        return; 
    }

    $.ajax({
        url: BASEURL + 'book_a_health_checkup/reject_checkup',
        type: 'POST',
        data: $('#reject_checkup_form').serialize(),
        dataType: 'json',
        success: function(){ 
            $('#modal2').modal('hide'); 
            reload_table(); 
        }
    });
}

$(document).on('click', '.delete_btn', function(){
    var id = $(this).data('id');
    if(confirm('Delete this record?')){
        $.ajax({
            url: BASEURL + 'book_a_health_checkup/ajax_delete/' + id,
            type: 'POST',
            dataType: 'json',
            success: function(response){
                if(response.status === 'ok'){
                    reload_table();
                }
            }
        });
    }
});