<script>
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': '{{ csrf_token() }}'
    }
});
$(function() {
    //Initialize Select2 Elements
    $('.select2').select2();
    //Initialize Select2 Elements
    $('.select2bs4').select2({
        theme: 'bootstrap4'
    });
});

// for empployee data table
$(function() {
    $('#EmployeeList').DataTable({
        "paging": true,
        "lengthChange": true,
        "searching": true,
        "ordering": true,
        "info": true,
        "autoWidth": false,
        "responsive": true,
        "pageLength": 100
        // "buttons": ["copy", "csv", "excel", "pdf", "print", "colvis"]
        // "buttons": ["csv", "excel", "pdf"]
    })
    // .buttons().container().appendTo('#EmployeeList_wrapper .col-md-6:eq(0)');
});


// for empployee data table
$(function() {
    $('#claimListing').DataTable({
        "paging": true,
        "lengthChange": true,
        "searching": true,
        "ordering": true,
        "info": true,
        "autoWidth": false,
        "responsive": true,
        "pageLength": 100,
        // "buttons": ["copy", "csv", "excel", "pdf", "print", "colvis"]
       // "buttons": ["csv", "excel", "pdf"]
    });
   //  .buttons().container().appendTo('#EmployeeList_wrapper .col-md-6:eq(0)');
});


$('.print_btn').click(function() {
    window.print();
});

// deactivate Employee
$('.deactivate-employee').click(function(event) {
    event.preventDefault();
    let btn = $(this);
    let tr = $(this).parent().parent();
    let url = $(this).attr('data-id');
    if (confirm('Do you want to delete this employee.') == 1) {
        $.ajax({
            url: url,
            type: "get",
            dataType: "Json",
            success: function(data) {
                if (data.status == 'success') {
                    tr.addClass('bg-danger');
                    // tr.fadeOut(1000, function() {
                    //     // tr.remove();
                    // });
                    btn.remove();
                } else {
                    alert('Somthing wents wrong. Failed to delete employee');
                }
            }
        });
    }
});
// reset user password 
$('.reset-user-password').click(function(event) {
    event.preventDefault();
    let id = $(this).attr('data-id');
    let url = "{{ route('reset.user.password') }}";
    if (confirm('Do you want to Reset Password of this employee.') == 1) {
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            }
        });
        $.ajax({
            url: url,
            type: "post",
            dataType: "Json",
            data: {
                id: id
            },
            success: function(data) {
                if (data.status == 'success') {
                    alert(data.message);
                }
                if (data.status = 'fail') {
                    alert(data.message);
                }
            }
        });
    }
});

// code to update user profile image
$('#update_profile_image_form').ready(function() {
    // click on update profile
    $('#update_profile_image_btn').click(function(event) {
        event.preventDefault();
        let url = "{{ route('update.profile.image') }}";
        let err = $('.profile_err');
        err.text('');
        let files = $('#profileImage')[0].files;
        let fd = new FormData();
        // Append data
        if (files.length > 0) {
            fd.append('file', files[0]);
        }
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            }
        });
        $.ajax({
            url: url,
            type: "post",
            dataType: "json",
            data: fd,
            cache: false,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.status == 'success') {
                    err.text(response.message);
                    setTimeout(function() {
                        $('#modal-default').modal('hide');
                        location.reload();

                    }, 1000);
                }
                if (response.status = 'fail') {
                    err.text(response.message);
                }
            }
        });
    });
});

// get Scheme
$('#emp_department').change(function() {
    getSchemes();
});
$('#emp_department').ready(function() {
    // setTimeout(() => {
    // if($('#emp_department').find('option:selected').val() != '') {
    getSchemes();
    // console.log('sa',$('#emp_department').find('option:selected').val())
    // }
    // }, 1000);
});

// load Schemes
function getSchemes() {
    
    //get scheme id for update
    var selectedText = "";   
    @if(!empty($claim_data->scheme_id)) 
    selectedText = "{{$claim_data->scheme_id}}";
    @endif
  
    let department_master_id = $('#emp_department').find('option:selected').val();
    let url = "{{ route('load.schemes') }}" + "?department_master_id=" + department_master_id;
    if (department_master_id != '') {
        $.ajax({
            url: url,
            type: "get",
            dataType: "json",
            success: function(response) {
                console.log(response);
                if (response.status == 'success') {
                    let select = $('#scheme');
                    select.html('');
                    select.append(`<option value="">Select Scheme</option>`);
                    $.each(response.result, function(i, item) {
                        let option =
                            `<option value="${response.result[i].scheme_master_id}" ${(response.result[i].scheme_master_id == selectedText) ? 'selected' : ''}>${response.result[i].scheme_name}</option>`;
                        select.append(option);
                    });
                    $('.scheme_error').text('');
                    // getPostingPlaces();
                    //autoload division after scheme selected for update
                    @if(!empty($claim_data->scheme_id)) 
                    getDivison();
                    @endif
                }
                if (response.status == 'fail') {
                    $('.scheme_error').text('Undefind or Mismatch Department.');
                }

            }
        });
    } else {
        $('.scheme_error').text('Department not selected. Please select depart to load Scheme')
    }
}


// get divisions
$('#scheme').change(function() {
    getDivison();
});
$('#scheme').ready(function() {
    // setTimeout(() => {
    getDivison();
    // }, 1000);
});

// load divions in claim form
function getDivison() {

    //get division id for update
    var selectedText = "";   
    @if(!empty($claim_data->division_id)) 
    selectedText = "{{$claim_data->division_id}}";
    @endif

    let scheme_master_id = $('#scheme').find('option:selected').val();
    let division_url = "{{ route('load.divions') }}" + "?scheme_master_id=" + scheme_master_id;
    if (scheme_master_id != '') {
        $.ajax({
            url: division_url,
            type: "get",
            dataType: "json",
            success: function(response) {
                if (response.status == 'success') {
                    let select = $('#emp_division');
                    select.html('');
                    select.append(`<option value="">Select Division</option>`);
                    $.each(response.result, function(i, item) {
                        let option =
                            `<option value="${response.result[i].division_master_id}" ${(response.result[i].division_master_id == selectedText) ? 'selected' : ''}>${response.result[i].division_name}</option>`;
                        select.append(option);
                    });
                    $('.emp_division_error').text('');

                   //autoload posting places after division selected for update
                    @if(!empty($claim_data->division_id)) 
                    getPostingPlaces();
                    @endif
                }
                if (response.status == 'fail') {
                    $('.emp_division_error').text('Undefind or Mismatch Scheme.');
                }
            }
        });
    } else {
        $('.emp_division_error').text('Scheme not selected. Please select Scheme to load divison')
    }
}

//get posting places
$('#emp_division').change(function() {
    getPostingPlaces();
});
$('#emp_division').ready(function() {
    // setTimeout(() => {
    getPostingPlaces();
    // }, 1000);
});
// load posting places in claim form
function getPostingPlaces() {

    //get posting place id for update
    var selectedText = "";   
    @if(!empty($claim_data->posting_place_id)) 
    selectedText = "{{$claim_data->posting_place_id}}";
    @endif

    let division_id = $('#emp_division').find('option:selected').val();
    let url = "{{ route('load.posting.places') }}" + "?division_id=" + division_id;
    if (division_id != '') {
        $.ajax({
            url: url,
            type: "get",
            dataType: "json",
            success: function(response) {
                if (response.status == 'success') {
                    let select = $('#emp_posting_place');
                    select.html('');
                    select.append(`<option value="">Select Posting Place</option>`);
                    $.each(response.result, function(i, item) {
                        let option =
                            `<option value="${response.result[i].id}"  ${(response.result[i].id == selectedText) ? 'selected' : ''}>${response.result[i].posting_place_name}</option>`;
                        select.append(option);
                    });
                    $('.emp_posting_place_error').text('');


                }
                if (response.status == 'fail') {
                    $('.emp_posting_place_error').text('Undefind or Mismatch Department.');
                }
            }
        });
    } else {
        $('.emp_posting_place_error').text('Division not selected. Please select division to load posting place')
    }
}

// check aadhar length
$('#aadhar_number').on('focusout keyup', function() {
    let aadhar = $(this).val();
    if (aadhar.length == 12) {
        $('.aadhar_error').text('');
    } else {
        $('.aadhar_error').text('Please Enter Valid 12 digits Aadhar Number');
    }
});


// Claim Type
$('#claim_type').change(function() {
    claimType();
});
$('#claim_type').ready(function() {
    claimType();
});

// show hide inputs according to the claim type
function claimType() {
    let claim_type = $('#claim_type').find('option:selected').val();
    let for_death = $('.for_death');
    let for_accident = $('.for_accident');
    let for_both = $('.for_both');
    let hide_for_accident = $('.hide_for_accident');
    let hide_for_death = $('.hide_for_death');

    if (claim_type == '') {
        for_death.hide();
        hide_for_accident.hide();
        for_both.hide();
        hide_for_death.hide();
    }
    if (claim_type == 1) {
        for_death.show();
        for_both.show();
        hide_for_death.hide();
    }
    if (claim_type == 2) {
        for_death.show();
        for_both.show();
        hide_for_accident.hide();
        hide_for_death.show();
    }
}

// Hide Show Claim For Box
$('#claim_for').change(function() {
    claimFor();
    changeIntimationLabel();
});
$('#claim_for').ready(function() {
    claimFor();
    changeIntimationLabel();
});

// hide/show claim form fields
function claimFor() {
    let claim_for = $('#claim_for').find('option:selected').val();
    let claim_by_epf = $('.claim_by_epf');
    let claim_by_esi = $('.claim_by_esi');
    let claim_by_wc = $('.claim_by_wc');
    let claim_by_gpa = $('.claim_by_gpa');

    if (claim_for == '') {
        claim_by_epf.hide();
        claim_by_esi.hide();
        claim_by_wc.hide();
        claim_by_gpa.hide();
    }
    if (claim_for == 'EPF') {
        claim_by_epf.show();
        claim_by_esi.hide();
        claim_by_wc.hide();
        claim_by_gpa.hide();
    }
    if (claim_for == 'ESI') {
        claim_by_epf.hide();
        claim_by_esi.show();
        claim_by_wc.hide();
        claim_by_gpa.hide();
    }
    if (claim_for == 'WC') {
        claim_by_epf.hide();
        claim_by_esi.hide();
        claim_by_wc.show();
        claim_by_gpa.hide();
    }
    if (claim_for == 'GPA') {
        claim_by_epf.hide();
        claim_by_esi.hide();
        claim_by_wc.hide();
        claim_by_gpa.show();
    }
}

// Change Intimation date info label
function changeIntimationLabel() 
{
    let claim_for = $('#claim_for').find('option:selected').val();
    
    // define label
    let label_for_wc_gpa = "(Intimation to Insurance Company)";
    let label_for_epf = "(Intimation to EPF Department)";
    let label_for_esi = "(Intimation to ESI Department)";
    // get intimation tag
    let intimation_info_tag = $(".intimation_date_info_label");
    intimation_info_tag.text('');
    if(claim_for == "") {
        intimation_info_tag.text('');
    } 
    if(claim_for == 'EPF') {
        intimation_info_tag.text(label_for_epf);
    }
    if(claim_for == 'ESI') {
        intimation_info_tag.text(label_for_esi);
    }
    if(claim_for == 'WC') {
        intimation_info_tag.text(label_for_wc_gpa);
    }
    if(claim_for == 'GPA') {
        intimation_info_tag.text(label_for_wc_gpa);
    }
}


// Auto load claim form details
$('#emp_id').focusout(function() {
    getEmployeeDetails();
});


function getEmployeeDetails() {
    let emp_id = $('#emp_id').val();

    if (emp_id != '') {
        let url = "{{ route('get.emp.details') }}" + "?emp_id=" + emp_id;
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            }
        });
        $.ajax({
            url: url,
            type: 'GET',
            dataType: "json",
            success: function(data) {
                if (data.status == 'success') {
                    $('.emp_id_error').text('');
                    fillForm(data);
                }
                if (data.status == 'fail') {
                    $('.emp_id_error').text('Undefind or Mismatch EMP ID.');
                }
            }
        });
    } else {
        $('.emp_id_error').text('Enter Employee ID');
    }
}

function fillForm(data) {
    $("#emp_department option[value='']").attr('selected', true);
    // $("#scheme option[value='']").attr('selected', true);
    // $("#emp_division option[value='']").attr('selected', true);
    // $("#emp_posting_place option[value='']").attr('selected', true);
    if (data.result == null) {
        $('#emp_name').val('');
        $('#emp_mobile').val('');
        $("#emp_department option[value='']").attr('selected', true);
    } else {
        $('#emp_name').val(data.result.emp_name);
        $('#emp_mobile').val(data.result.emp_mobile);
        $('#emp_department option[value=' + data.result.department + ']').attr('selected', true);
        getSchemes();
    }
}

// report summary
let date_column = $('.date-column');
let month_column = $('.month-column');
let category_column = $('.category-column');
date_column.hide();
month_column.hide();
category_column.hide();
$('#report_type').change(function() {
    reportFilterColumn();
});
$('#report_type').ready(function() {
    reportFilterColumn();
});

function reportFilterColumn() {
    let type = $('#report_type').val();

    if (type == '') {
        date_column.hide();
        month_column.hide();
        category_column.hide();
    }
    if (type == 1) {
        // All Report
        date_column.hide();
        month_column.hide();
        category_column.hide();

    }
    if (type == 2) {
        // Date Wise Report
        date_column.show();
        month_column.hide();
        category_column.hide();
    }
    if (type == 3) {
        // Month Wise Report
        date_column.hide();
        month_column.show();
        category_column.hide();
    }
    if (type == 4) {
        // Pending Report
        date_column.hide();
        month_column.hide();
        category_column.show();
    }
    if (type == 5) {
        // Processing Wise Report
        date_column.hide();
        month_column.hide();
        category_column.show();
    }
    if (type == 6) {
        // Close Report/Done Report
        date_column.hide();
        month_column.hide();
        category_column.show();
    }
}



$(document).ready(function() {
        // Counter to keep track of added plaintiff fields
        let plaintiffCount = 0;

        // Function to add a new plaintiff field
        function addPlaintiffField() {
            plaintiffCount++;
            const newPlaintiffField = `
            <div class="form-group" id="plaintiffField${plaintiffCount}">
                <div class="input-group">
                    <input type="text" name="additional_plaintiff[${plaintiffCount}]" class="form-control" placeholder="Additional Plaintiff">
                    <div class="input-group-append">
                        <button class="btn btn-danger removePlaintiff" type="button">-</button>
                    </div>
                </div>
            </div>
        `;
            $("#additionalPlaintiffs").append(newPlaintiffField);
        }

        // Event handler for the plus button
        $("#addPlaintiff").click(function() {
            addPlaintiffField();
        });

        // Event handler for removing a plaintiff field
        $("#additionalPlaintiffs").on("click", ".removePlaintiff", function() {
            $(this).closest(".form-group").remove();
        });
    });


    $(document).ready(function() {
        // Counter to keep track of added plaintiff fields
        let defendantCount = 0;

        // Function to add a new plaintiff field
        function adddefendantField() {
            defendantCount++;
            const newdefendantField = `
                <div class="form-group" id="defendantField${defendantCount}">
                <div class="input-group">
                <input type="text" name="additional_defendant[${defendantCount}]" class="form-control" placeholder="Additional defendant">
                    <div class="input-group-append">
                        <button class="btn btn-danger removedefendant" type="button">-</button>
                    </div>
                    </div>
                    </div>
            `;
            $("#additionaldefendant").append(newdefendantField);
        }

        // Event handler for the plus button
        $("#adddefendant").click(function() {
            adddefendantField();
        });
        $("#additionaldefendant").on("click", ".removedefendant", function() {
            $(this).closest(".form-group").remove();
        });
    });

    $(document).ready(function() {
        $("#district").change(function() {
            var selectedDistrict = $(this).val();
            if (selectedDistrict === "other") {
                $("#otherDistrictField").show();
            } else {
                $("#otherDistrictField").hide();
            }
        });
    });

    $(document).ready(function() {
        $('#example1').DataTable({
            dom: 'Bfrtip',
            buttons: [
                'csv', 'excel', 'print'
            ],
            pageLength: 20, // Set the default number of rows per page to 20
        });
    });



</script>
