$(document).ready(function () {

    // Detect pagination click
    $('#pagination').on('click', 'a', function (e) {
        e.preventDefault();

        if ($(this).attr('href').trim() === '#') {
            return;
        }

        const pageno = $(this).attr('data-ci-pagination-page');
        loadPagination(pageno, $('.search-block').serialize());
    });

    // Prevent submit form by press the enter button
    $(window).keydown(function (event) {
        if (event.keyCode == 13) {
            loadPagination(0);
            event.preventDefault();
            return false;
        }
    });

    // Load Page
    loadPagination(0);

    function loadPagination(pagno, filters = null) {

        $.ajax({
            url: '/credit_cards/loadRecord',
            type: 'get',
            dataType: 'json',
            async: false,
            data: {
                'rowno': pagno,
                'filters': filters
            },
            success: function (response) {
                $('#pagination').html(response.pagination);
                createTable(response.result);
            },
            complete: function () { }
        });
    }

    function createTable(result) {

        $('#credit-card-list tbody').empty();

        result.forEach(function (value, index) {
            
            let benefits = '';
            let benefit_list = '';

            value.benefits.forEach(function(value, index, array) {
                benefits += value.benefit;
                benefit_list += JSON.stringify(value);
                if (index !== array.length - 1) {
                    benefits += '<br>';
                    benefit_list += '<br>';
                }
            })

            let tr =
                `<tr class="card-${value.credit_card_id}">
                    <td>${index + 1}</td>
                    <td class="bank-name">${value.bank_name}</td>
                    <td class="card-name">${value.card_name}</td>
                    <td class="input-group-btn">
                        <button type="button" class="btn btn-info btn-sm btn-update">Update</button>
                        <button type="button" class="btn btn-secondary btn-sm btn-cancel hidden">Cancel</button>
                        <button type="button" class="btn btn-danger btn-sm btn-delete">Delete</button>
                        <button type="button" class="btn btn-primary btn-sm btn-show-benefits">Show Benefits</button>
                    </td>
                    <td hidden>${value.credit_card_id}</td>
                    <td hidden>
                        ${benefits}
                    </td>
                    <td hidden>${value.bank_id}</td>
                    <td hidden class="benefit-list">${benefit_list}</td>
                </tr>`;

            $('#credit-card-list tbody').append(tr);
        })
    }

    // Add benefit
    $('#btn-add-benefit').on('click', function () {
        const val = $('#benefit').val().trim();

        if (val !== '') {
            $('#benefit-list ul').append(
                `<li class="list-group-item list-group-item-success col-lg-12">
                    <div class="col-lg-11" style="word-wrap: break-word;">${val}</div>
                    <button type="button" class="close btn-delete-benefit col-lg-1" data-dismiss="alert" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </li>`
            );
            $('#benefit').val('');
        }
    })

    // Detect on click the update button
    $(document).on('click', '.btn-update', function (e) {
        const $row = $(this).closest("tr"); // Finds the closest row <tr> 
        const $tds = $row.find("td"); // Finds all children <td> elements

        removeHiddenField();

        $('.btn-cancel').addClass('hidden');
        $('.btn-update').removeClass('hidden');
        $('#btn-add').addClass('hidden');
        $('#btn-update').removeClass('hidden');

        $(this).siblings('.btn-cancel').removeClass('hidden');
        $(this).addClass('hidden');

        $('[name="bank_name"]').val($tds[1].innerText);
        $('[name="bank_name"]').prop('disabled', true);
        $('[name="card_name"]').val($tds[2].innerText);
        $('[name="credit_card_id"]').val($tds[4].innerText);

        $('#benefit-list ul').empty();
        $('input[name="expired_date[]"]').remove();
        $tds[7].innerHTML.split('<br>').forEach(function(val) {
            if (val.trim() !== '') {
                val = JSON.parse(val);

                $('#benefit-list ul').append(
                    `<li class="list-group-item list-group-item-success col-lg-12">
                        <div class="col-lg-11" style="word-wrap: break-word;">${val.benefit}</div>
                        <button type="button" class="close btn-delete-benefit col-lg-1" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">×</span>
                        </button>
                    </li>`
                );

                // add expired date array
                $('<input>').attr({
                    type: 'hidden',
                    name: 'expired_date[]',
                    value: val.expired_date
                }).appendTo('#credit-card-form');
            }
        })

        $('<input>').attr({
            type: 'hidden',
            name: 'old_bank_name',
            value: $tds[1].innerText
        }).appendTo('#credit-card-form')

        $('<input>').attr({
            type: 'hidden',
            name: 'old_card_name',
            value: $tds[2].innerText
        }).appendTo('#credit-card-form')

        $('#credit-card-form').attr('action', origin + "/credit_cards/update/");
    });

    // Detect on click the cancel button
    $(document).on('click', '.btn-cancel', function (e) {
        $(this).siblings('.btn-update').removeClass('hidden');
        $(this).addClass('hidden');
        $('#btn-add').removeClass('hidden');
        $('#btn-update').addClass('hidden');

        $('#bank-name').val('');
        $('#bank-name').prop('disabled', false);
        $('#card-type').val('');
        $('#credit-card-id').val('');
        $('#benefit-list ul').empty();
        removeHiddenField();

        $('#credit-card-form').attr('action', origin + "/credit_cards/create");
    });

    // Detect on click the delete button
    $(document).on('click', '.btn-delete', function (e) {

        if (!confirm('Are you sure want to delete?')) {
            return;
        }

        const $row = $(this).closest("tr"); // Finds the closest row <tr> 
        const $tds = $row.find("td"); // Finds all children <td> elements

        $('[name="credit_card_id"]').val($tds[4].innerText);
        $('<input>').attr({
            type: 'hidden',
            name: 'bank_id',
            value: $tds[6].innerText
        }).appendTo('#credit-card-form');
        $('#credit-card-form')
            .attr('action', origin + "/credit_cards/destroy/")
            .submit();
    });

    // Detect on click the add button on form
    $('#btn-add').click(function (e) {
        e.preventDefault();
        var form = $('#credit-card-form');
        $('input[name="benefits[]"]').remove();
        $('.list-group li').each((idx, val) => {
            $('<input>').attr({
                type: 'hidden',
                name: 'benefits[]',
                value: val.children[0].innerText
            }).appendTo(form);
        });
        var disabled = form.find(':input:disabled').removeAttr('disabled');
        var data = form.serialize();
        disabled.attr('disabled','disabled');
        $.ajax({
            url: '/credit_cards/create',
            type: 'POST',
            data: data,
        })
        .done(function( res ) {
            if ( res.type && res.type == 'errors' ) {
                alert( 'Create Credit Card Benefits Failed\n' + $("<div/>").html(res.message).text() );
                return;
            }
            // update item
            var page = $('#pagination');
            var page = page.length > 0 ? page.find('ul>li.active a').text() : 0;
            loadPagination(page, $('.search-block').serialize());
            var target = $(document).find('tr.card-'+res.credit_card_id);
            target.find('.btn-update').trigger('click');
            
            alert( 'Create Credit Card Benefits Successful' );       
        })
        .fail(function( jqXHR, textStatus, errorThrown ) {
            console.log( errorThrown );
        })
        .always(function() {
            lockUpdate = false;
        });
    });

    // Detect on click the update button on form
    $('#btn-update').click(function () {
        var form = $('#credit-card-form');
        $('input[name="benefits[]"]').remove();
        $('.list-group li').each((idx, val) => {
            $('<input>').attr({
                type: 'hidden',
                name: 'benefits[]',
                value: val.children[0].innerText
            }).appendTo(form);
        });
        var disabled = form.find(':input:disabled').removeAttr('disabled');
        var data = form.serialize();
        disabled.attr('disabled','disabled');

        $.ajax({
            url: '/credit_cards/update',
            type: 'POST',
            data: data,
        })
        .done(function( res ) {
            if ( res.type && res.type == 'errors' ) {
                alert( 'Update Credit Card Benefits Failed\n' + $("<div/>").html(res.message).text() );
                return;
            }
            // update item
            var page = $('#pagination');
            var page = page.length > 0 ? page.find('ul>li.active a').text() : 0;
            loadPagination(page, $('.search-block').serialize());
            var target = $(document).find('tr.card-'+res.credit_card_id);
            target.find('.btn-update').trigger('click');

            alert( 'Update Credit Card Benefits Successful' );       
        })
        .fail(function( jqXHR, textStatus, errorThrown ) {
            console.log( errorThrown );
        })
        .always(function() {
            lockUpdate = false;
        });
    });

    // remove benefit from list
    $(document).on('click', '.btn-delete-benefit', function (e) {
        $(this).closest("li").remove();
    });

    // button search for filter
    $('.btn-search').on('click', function() {
        loadPagination(0, $('.search-block').serialize());
    })

    // show benefit list modal
    $(document).on('click', '.btn-show-benefits', function() {
        const $row = $(this).closest("tr"); // Finds the closest row <tr> 
        const $tds = $row.find("td"); // Finds all children <td> elements

        $('#message-benefits').html('');
        $("#benefit-list-modal").modal();

        let benefit_list = $('#benefit-list-modal #benefit-list tbody');
        benefit_list.empty();

        $('#cell-actived').removeAttr('id');
        $tds[7].setAttribute('id', 'cell-actived');
        $tds[7].innerHTML.split('<br>').forEach(function (value, index) {

            if (value.trim() !== '') {

                value = JSON.parse(value);
                let tr =
                    `<tr>
                        <td style="display: none">
                            <input class="form-control" name="benefit_id_modal[]" value="${value.id}" />
                        </td>
                        <td>
                            <input class="form-control" name="benefit_modal[]" value="${value.benefit}" />
                        </td>
                        <td>
                            <input class="form-control expired_date" name="expired_date_modal[]" value="${value.expired_date}" />
                        </td>
                    </tr>`;
    
                benefit_list.append(tr);
            }
        })
    })

    $(document).on('click', '#btn-save', function() {
        if ($('#benefit-list-modal #benefit-list tbody').children().length > 0) {
            const benefit_id = $('input[name="benefit_id_modal[]"]').map(function(){ 
                return this.value; 
            }).get();

            const benefit = $('input[name="benefit_modal[]"]').map(function(){ 
                return this.value; 
            }).get();

            const expired_date = $('input[name="expired_date_modal[]"]').map(function(){ 
                return this.value; 
            }).get();

            let new_val = '';
            benefit_id.forEach((value, index, array) => {
                new_val += JSON.stringify({
                    'id': value,
                    'benefit': benefit[index],
                    'expired_date': expired_date[index]
                })
                if (index !== array.length - 1) {
                    new_val += '<br>';
                }
            })

            $.ajax({
                url: '/credit_card_benefits/update',
                type: 'post',
                dataType: 'json',
                data: {
                    benefit_id,
                    benefit,
                    expired_date
                },
                success: function (response) {
                    if (response.code === '200') {
                        $('#cell-actived').html(new_val);
                        $('.btn-cancel').click();
                    }
                    $('#message-benefits').html(response.message);
                },
            });
        } 
    })

    $('body').on("focus", '.expired_date', function() {
        window.addDatePicker(this);
    })

    function removeHiddenField() {
        $('[name="old_bank_name"]').remove();
        $('[name="old_card_name"]').remove();
        $('[name="expired_date[]"]').remove();
    }
});