$(document).ready( function () {
    var currentLanguage = $('#currentLanguage').val();

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    var activeSubscriptionTableColumns = [
        (currentLanguage == 'zh_hk' ? {data: 'company_name_chinese', name: 'companies.name_chinese'} : {data: 'company_name_english', name: 'companies.name_english'}),
        {data: 'created_at', name: 'company_subscriptions.created_at'},
        {data: 'service_type', name: 'subscriptions.service_type'},
        {data: 'subscription_period', name: 'company_subscriptions.created_at'},
        (currentLanguage == 'zh_hk' ? {data: 'name_chinese', name: 'subscriptions.name_chinese'} : {data: 'name_english', name: 'subscriptions.name_english'}),
        {data: 'status', name: 'company_subscriptions.status'},
        {data: 'invoice', name: 'invoice', searchable: false, sortable: false}
    ];
    var activeSubscriptionTableUrl = $("#activeSubscriptionTable").attr('data-ajax-url');
    var activeSubscriptionTableEmptyText = $("#activeSubscriptionTable").attr('data-empty-text');
    var activeSubscriptionTable = $("#activeSubscriptionTable").DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: activeSubscriptionTableUrl,
            type: 'post',
            "data": function ( d ) {
                return $.extend( {}, d, {
                    "company_name": $('#searchFrm #search_company_name').val(),
                    "service_type": $('#searchFrm #search_service_type').val(),
                    "subscription_id": $('#searchFrm #search_subscription_id').val(),
                } );
            },
            "dataSrc": function ( json ) {
                for (var i = 0; i < json.data.length; i++) {
                    $.each( json.data[i], function( key, value ) {
                        json.data[i][key] = value ? value : '-';
                    });
                }

                return json.data;
            },
            complete: function (data) {
                if (data['responseJSON'].recordsTotal > 0) {
                    $('#totalActive').show();
                    $('#totalActive').html(data['responseJSON'].recordsTotal);
                }
                else {
                    $('#totalActive').hide();
                }
            },
        },
        columns: activeSubscriptionTableColumns,
        order: [[1, "desc"]],
        searchDelay: 500,
        "language": {
            "paginate": {
                "next": ">",         // Text for the "Next" page button
                "previous": "<"  // Text for the "Previous" page button
            },
            "emptyTable": activeSubscriptionTableEmptyText
            // Add more text customizations if needed
        }
    });

    var expiredSubscriptionTableColumns = [
        (currentLanguage == 'zh_hk' ? {data: 'company_name_chinese', name: 'companies.name_chinese'} : {data: 'company_name_english', name: 'companies.name_english'}),
        {data: 'created_at', name: 'company_subscriptions.created_at'},
        {data: 'service_type', name: 'subscriptions.service_type'},
        {data: 'subscription_period', name: 'company_subscriptions.created_at'},
        (currentLanguage == 'zh_hk' ? {data: 'name_chinese', name: 'subscriptions.name_chinese'} : {data: 'name_english', name: 'subscriptions.name_english'}),
        {data: 'status', name: 'company_subscriptions.status'},
        {data: 'invoice', name: 'invoice', searchable: false, sortable: false}
    ];
    var expiredSubscriptionTableUrl = $("#expiredSubscriptionTable").attr('data-ajax-url');
    var expiredSubscriptionTableEmptyText = $("#expiredSubscriptionTable").attr('data-empty-text');
    var expiredSubscriptionTable = $("#expiredSubscriptionTable").DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: expiredSubscriptionTableUrl,
            type: 'post',
            "data": function ( d ) {
                return $.extend( {}, d, {
                    "company_name": $('#searchFrm #search_company_name').val(),
                    "service_type": $('#searchFrm #search_service_type').val(),
                    "subscription_id": $('#searchFrm #search_subscription_id').val(),
                } );
            },
            "dataSrc": function ( json ) {
                for (var i = 0; i < json.data.length; i++) {
                    $.each( json.data[i], function( key, value ) {
                        json.data[i][key] = value ? value : '-';
                    });
                }

                return json.data;
            },
            complete: function (data) {
                if (data['responseJSON'].recordsTotal > 0) {
                    $('#totalExpired').show();
                    $('#totalExpired').html(data['responseJSON'].recordsTotal);
                }
                else {
                    $('#totalExpired').hide();
                }
            }, 
        },
        columns: expiredSubscriptionTableColumns,
        order: [[1, "desc"]],
        searchDelay: 500,
        "language": {
            "paginate": {
                "next": ">",         // Text for the "Next" page button
                "previous": "<"  // Text for the "Previous" page button
            },
            "emptyTable": expiredSubscriptionTableEmptyText
            // Add more text customizations if needed
        }
    });

    $('#searchFrm #search_service_type').change(function(e) {
        var html = '<option value="" selected>All</option>';

        if ($(this).val()) {
            $.ajax({
                url: "/cms/subscriptions/get-subscriptions/" + $(this).val(),
                type: "get",
                data: {},
                dataType: 'json',
                success:function(data) {
                    var subscriptions = data.subscriptions;
    
                    subscriptions.forEach(function(subscription) {
                        html += `
                            <option value="` + subscription.id + `">` + (currentLanguage == 'zh_hk' ? subscription.name_chinese : subscription.name_english) + `</option>
                        `;
                    });
    
                    $('#searchFrm select#search_subscription_id').html(html);
                }
            });
        }
        else {
            $('#searchFrm select#search_subscription_id').html(html);
        }
    });

    $('#searchFrm').submit(function(e) {
        e.preventDefault();
        activeSubscriptionTable.ajax.reload();
        expiredSubscriptionTable.ajax.reload();
    });
    
    $(".js-side-nav").click(function(e){
        e.preventDefault();
        var id = jQuery(this).data('id');
        jQuery(this).closest('.side-nav-tabs').next().find('.js-content-tab').hide();
        jQuery(id).show();
        jQuery(this).closest('.side-nav-tabs').find('li').removeClass('active');
        jQuery(this).parent().addClass('active');
    });

    $(".js-tab-navigate").click(function(e){
        e.preventDefault();
        var id = jQuery(this).data('id');
        jQuery(this).closest('.tabs-navigation').next().find('.tabs-content-item').hide();
        jQuery(id).show();
        jQuery(this).closest('.tabs-navigation').find('li').removeClass('active');
        jQuery(this).parent().addClass('active');
    });
} );