jQuery( document ).ready( function( $ ) {

    var security = jQuery( '.ps-emai-reporting-security' ).val();
    var from = jQuery( '.ps-email-reporting-from' ).val();
	var to = jQuery( '.ps-email-reporting-to' ).val();

    from = from != '' ? Date.parse( from ) / 1000 : '';
    to = to != '' ? Date.parse( to ) / 1000 : '';

    jQuery( document ).on( 'change', '.ps-email-reporting-from, .ps-email-reporting-to', function(){

        from = jQuery( '.ps-email-reporting-from' ).val();
		to = jQuery( '.ps-email-reporting-to' ).val();

        from = Date.parse( from ) / 1000;
        to = Date.parse( to ) / 1000;
        
        jQuery( '.rat-filter-btn' ).attr( 'data-from', from );
        jQuery( '.rat-filter-btn' ).attr( 'data-to', to );

    } );

    //DataTable
    var EmailReportingDT = jQuery( '#ps-email-reporting-logs' ).DataTable( {

        searching: false,
        processing: true,
        //serverSide: true,
        paging: false,
        ajax: {
			url: `${ajaxurl}?action=ps-get-report&security=${security}&from=${from}&to=${to}`,
            dataSrc: 'data.logs'
        },
        columns: [
            { data: 'subject' },
            { data: 'total' },
            { data: 'sent' },
            { data: 'failed' },
            { data: 'opened', 
                render: function( data, type, row, meta ) {
                    
                    return `
                    ${data} (${row.opened_ratio})
                    `
                    
                }
            },
        ],
        "initComplete": function( settings, json ) {
        
            //Lets render graph
            var graphData = json.data.graph;
            RATDeliveryGraph( graphData.date, graphData.total, graphData.sent, graphData.failed );
            RATOpenGraph( graphData.date, graphData.sent, graphData.opened );

        },

    } );

    var EmailReportingDT = jQuery( '#ps-email-reporting-logs' ).DataTable();

    jQuery( document ).on( 'click', '.ps-email-reporting-filter', function( e ) {

        e.preventDefault();

        var security = jQuery( '.ps-emai-reporting-security' ).val(); 
        var url = jQuery( this ).attr( 'href' );
        var to =  jQuery( this ).attr( 'data-to' );;
        var from = jQuery( this ).attr( 'data-from' );
        var action = RATGetParameterByName( 'action', url );
        to = ( to == undefined || isNaN( to ) ) ? '' : to;
        from = ( from == undefined || isNaN( from ) ) ? '' : from;

        if( from == '' ) {

            alert( 'Please select from date' );
            return;

        }

        jQuery.ajax( {

            url: ajaxurl,
            type: 'GET',
            data: {
                action: action,
                security: security,
                to: to,
                from: from
            },
            success: function( response ) {

                var graphData = JSON.parse( response );
                var graphData = graphData.data.graph;

                RATDeliveryGraph( graphData.date, graphData.total, graphData.sent, graphData.failed );
                RATOpenGraph( graphData.date, graphData.sent, graphData.opened );
                
                EmailReportingDT.ajax.url( `${ajaxurl}?action=ps-get-report&security=${security}&from=${from}&to=${to}` ).load();

            }

        } );

    } );

} );

function RATGetParameterByName( name, url ) {

    if ( !url ) url = window.location.href;
    name = name.replace( /[\[\]]/g, "\\$&" );
    var regex = new RegExp( "[?&]" + name + "(=([^&#]*)|&|#|$)" ),
    results = regex.exec( url );
    if ( !results ) return null;
    if ( !results[2] ) return '';
    return decodeURIComponent( results[2].replace( /\+/g, " " ) );

}

function RATDeliveryGraph( date, total, sent, failed ) {

    var total = {
        x: date,
        y: total,
        type: 'scatter',
        name: 'Total'
    };

    var sent = {
        x: date,
        y: sent,
        type: 'scatter',
        name: 'Sent',
        marker: {
            color: 'rgb(92, 184, 92)'
        },
    };

    var failed = {
        x: date,
        y: failed,
        type: 'scatter',
        name: 'Failed',
        marker: {
            color: 'rgb(220, 53, 69)'
          },
    };

    var layout = {
        title: psrat.text.delivery_stability
    };

    var data = [total, sent, failed];

    Plotly.newPlot( 'ps-email-reporting-stability-graph', data, layout );

}

function RATOpenGraph( date, sent, opened ) {

    var sent = {
        x: date,
        y: sent,
        type: 'scatter',
        name: 'Sent',
        marker: {
            color: 'rgb(92, 184, 92)'
        },
    };

    var opened = {
        x: date,
        y: opened,
        type: 'scatter',
        name: 'Opened'
    };

    var layout = {
        title: psrat.text.open_ratio
    };

    var data = [sent, opened];
    
    Plotly.newPlot( 'ps-email-reporting-opened-ratio', data, layout );

}