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

$(document).ready(function () 
{
    table = $('#datatable-fixedheader').DataTable({
        retrieve: true,
        columnDefs: [],
        "processing": true,
        "serverSide": true,
        "lengthChange": true,
        "ordering": true,
        'autoWidth': false,
        "pagingType": "full_numbers",
        "iDisplayLength": 10,
        "lengthMenu": [
            [10, 25, 50, -1],
            [10, 25, 50, "All"]
        ],
        "order": [],  
        "ajax": {
            "url": BASEURL + 'awards-list',
            "type": "POST"
        },
        
        "columnDefs": [{
            "targets": [0, 3, 4, 6, 7], 
            "orderable": false,        
        }],

        "fnInitComplete": function () 
        { 
            $(".dt-container .dt-search").append('<button type="button" id="cb-add" class="btn btn-secondary waves-effect waves-light" data-bs-toggle="modal" data-bs-target=".modal1" onclick="add_data()">+ Add New</button>');
        },
    });
});

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

$('.modal').on('shown.bs.modal', function () {
    $('[name="title"]').focus();
});

var save_method;

function add_data() 
{
    save_method = 'add';
    $('#id').val(''); 
    $('#get_old_person_img').val('');
    $('#get_old_award_img').val('');
    $("#person_img_preview").hide();
    $("#award_img_preview").hide();
    $("#preview_person_img_tag").hide();
    $("#preview_award_img_tag").hide();
    $('#person_img').val('');
    $('#award_img').val('');
    $('#form').parsley().reset();
    $('#form')[0].reset();
    $(".modal-title").html('Add Award & Achievement');
    $('#submit').attr('disabled', false);    
    $("#submit").html('Save');
}

function edit_data(id) 
{
    save_method = 'update';
    $('#form').parsley().reset();
    $('#form')[0].reset();
    $(".modal-title").html('Edit Award & Achievement');
    $("#submit").html('Update');
    $('#submit').attr('disabled', false);
    $('.modal1').modal('show');    

    $.ajax({
        url: BASEURL + 'awards/edit/' + id,
        type: "GET",
        dataType: "JSON",
        success: function (data) {
            if(data.error) {
                alert('Error! ' + data.error);
                return;
            }
            
            $('[name="id"]').val(data.id);
            $('[name="title"]').val(data.title);
            $('[name="description"]').val(data.description);
            $('[name="get_old_person_img"]').val(data.person_img);
            $('[name="get_old_award_img"]').val(data.award_img);
            
          
            if (data.person_img != "" && data.person_img != null) 
            {
                $("#person_img_preview").show();
                $('.person_img_name_get').html(data.person_img);
                $("#preview_person_img_tag").attr("src", BASEURL + '../assets/images/gallery/large/' + data.person_img).show();
            }
            else 
            {
                $("#person_img_preview").hide();
                $("#preview_person_img_tag").hide();
            }

           
            if (data.award_img != "" && data.award_img != null) 
            {
                $("#award_img_preview").show();
                $('.award_img_name_get').html(data.award_img);
                $("#preview_award_img_tag").attr("src", BASEURL + '../assets/images/gallery/large/' + data.award_img).show();
            }
            else 
            {
                $("#award_img_preview").hide();
                $("#preview_award_img_tag").hide();
            }

            $("#btnSave").html('Update');
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log('Error:', jqXHR.responseText);
            alert('Error! Get data from database. Please check console for details.');
        }
    });
} 

function deactive(id) 
{
    $.ajax({
        type: "POST",
        url: BASEURL + 'awards/deactive/' + id,
        data: {id: id},
        dataType: "json",
        success: function (data) {
            if (data == 'sucess') {
                reload_table();
            } else {
                alert('Status Update Fail');
            }
        }
    });
}

function active(id) 
{
    $.ajax({
        type: "POST",
        url: BASEURL + 'awards/active/' + id,
        data: {id: id},
        dataType: "json",
        success: function (data) {
            if (data == 'sucess') {
                reload_table();
            } else {
                alert('Status Update Fail');
            }
        }
    });
}

$(document).on("click", ".delete_btn", function (event) {
    var id = $(this).attr('data-id');  
    
    Swal.fire({
        title: "Are you sure?",
        text: "You won't be able to revert this!",
        icon: "warning",
        showCancelButton: true,
        confirmButtonColor: "#34c38f",
        cancelButtonColor: "#f03b3b",
        confirmButtonText: "Yes, delete it!",
        cancelButtonText: "No, cancel!"
    }).then(function (result) {
        if (result.value) {
            $.ajax({
                type: 'POST',
                url: BASEURL + 'awards/delete/' + id,
                data: {id: id},
                dataType: 'json',
                beforeSend: function () {
                    $('.dataTables_processing').css('visibility', 'visible');
                },
                success: function (returnData) {
                    if (returnData.status == 'ok') {
                        Swal.fire({
                            title: "Deleted!",
                            text: "Award & Achievement has been deleted.",
                            icon: "success"
                        });
                        reload_table();
                    } else if (returnData.status == 'not') {
                        Swal.fire({
                            title: "Cancelled",
                            text: "Award & Achievement can't delete, Because they are used in " + returnData.tbc_name + ".",
                            icon: "error"
                        });
                    }
                },
                complete: function () {
                    $('.dataTables_processing').css('visibility', 'hidden');
                },
                error: function() {
                    Swal.fire({
                        title: "Error!",
                        text: "Something went wrong!",
                        icon: "error"
                    });
                }
            });
        }
    });
}); 

$('#form').submit(function (e) {
    e.preventDefault();
    
    if ($('#form').parsley().isValid()) 
    { 
        $('#submit').attr('disabled', true);
        $("#submit").html('<i class="mdi mdi-loading mdi-spin"></i> Processing...');
        
        var formData = new FormData(this);
        
       
        console.log('Form Data:');
        for (var pair of formData.entries()) {
            console.log(pair[0] + ': ' + pair[1]);
        }
        
        $.ajax({
            url: BASEURL + 'awards/submit',
            type: "POST",
            data: formData,
            processData: false,
            contentType: false,
            cache: false,
            dataType: "JSON",
            success: function (result) 
            {
                console.log('Response:', result);
                
                if (result.status == 'ok') 
                {
                    $('.modal1').modal('hide');
                    reload_table(); 
                    
                    $('#id').val(''); 
                    $('#get_old_person_img').val('');
                    $('#get_old_award_img').val('');
                    $('#form').parsley().reset();
                    $('#form')[0].reset();
                    $('#submit').html('Save');
                    $('#submit').attr('disabled', false);
                    
                    $(".alert-danger").hide();
                    $(".alert-success").show();
                    $(".alert-success-msg").html(result.message);                        
                    setTimeout(function () {
                        $(".alert-success").fadeOut(500);
                    }, 5000);
                } 
                else 
                {
                    $('.modal1').modal('hide');
                    
                    $('#submit').html('Save');
                    $('#submit').attr('disabled', false);
                    
                    $(".alert-success").hide();
                    $(".alert-danger").show();
                    $(".alert-danger-msg").html(result.message);
                    setTimeout(function () {
                        $(".alert-danger").fadeOut(500);
                    }, 5000);
                }
            },
            error: function(xhr, status, error) {
                console.log('AJAX Error:', xhr.responseText);
                
                $('#submit').html('Save');
                $('#submit').attr('disabled', false);
                
                $('.modal1').modal('hide');
                
                var errorMsg = 'Error: ' + error;
                if(xhr.responseText) {
                    try {
                        var errorData = JSON.parse(xhr.responseText);
                        errorMsg = errorData.message || errorMsg;
                    } catch(e) {
                        errorMsg = xhr.responseText.substring(0, 200);
                    }
                }
                
                $(".alert-success").hide();
                $(".alert-danger").show();
                $(".alert-danger-msg").html(errorMsg);
                setTimeout(function () {
                    $(".alert-danger").fadeOut(500);
                }, 5000);
            }
        });
    }
    
    return false;
});
 
$('#person_img').on('change', function() {
    if (this.files && this.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) {
            $('#preview_person_img_tag').attr('src', e.target.result).show();
            $('.person_img_name_get').html($('#person_img')[0].files[0].name);
            $('#person_img_preview').show();
        };
        reader.readAsDataURL(this.files[0]);
    }
});
 
$('#award_img').on('change', function() {
    if (this.files && this.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) {
            $('#preview_award_img_tag').attr('src', e.target.result).show();
            $('.award_img_name_get').html($('#award_img')[0].files[0].name);
            $('#award_img_preview').show();
        };
        reader.readAsDataURL(this.files[0]);
    }
});