<?php

if( !class_exists( 'Post_SMTP_RAT_EMail_Reporting' ) ):

class Post_SMTP_RAT_EMail_Reporting {

    const SECTION = 'ps_rat_section';
    const OPTION = 'ps_rat_option';

    private static $instance = null;

    /**
     * Get the instance of the class
     * 
     * @since 1.0.0
     * @version 1.0.0
     */
    public static function get_instance() {

        if( null == self::$instance ) {

            self::$instance = new self;

        }

        return self::$instance;

    }

    /**
     * Instance of the class
     * 
     * @since 1.0.0
     * @version 1.0.0
     */
    public function __construct() {
        
        add_action( 'wp_ajax_ps-get-open-ratio', array( $this, 'get_open_ratio' ) );
        add_action( 'admin_menu', array( $this, 'add_sub_menu' ), 21 );
        add_action( 'wp_ajax_ps-get-report', array( $this, 'get_report' ) );
        add_action( 'postman_delete_logs_successfully', array( $this, 'delete_logs' ) );

        if( isset( $_GET['page'] ) && $_GET['page'] == 'post-smtp-email-reporting' ) {

            add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );

        }

    }


    /**
     * Get Open Ratio | Ajax Callback
     * 
     * @since 1.0.0
     * @version 1.0.0
     */
    public function get_open_ratio() {

        if( wp_verify_nonce( $_POST['security'], 'security' ) ) {

            $email_id = sanitize_text_field( $_POST['email_id'] );
            
            $db = new POST_SMTP_RAT_DB;
            $total_sent_count = $db->get_total_sent_emails_count( $email_id );
            $total_opened_count = $db->get_total_open_count_by_id( $email_id );
            $original_to = ( $total_opened_count && isset( $total_opened_count->original_to ) ) ? $total_opened_count->original_to : 0;
            $opened_count = ( $total_opened_count && isset( $total_opened_count->opened_count ) ) ? $total_opened_count->opened_count : 0;
            $opened_ratio = ( $total_sent_count && $opened_count ) ? ( $opened_count / $total_sent_count ) * 100 : 0;

            $data = array(
                'total_sent_count'      =>  $total_sent_count,
                'original_to'           =>  $original_to,
                'opened_count'          =>  $opened_count,
                'opened_ratio'          =>  number_format( (float)$opened_ratio, 2, '.', '' )
            );

            wp_send_json_success( 
                $data, 
                200 
            );

        }

    }


    /**
     * Add Sub Menu | Action Callback
     * 
     * @since 1.0.0
     * @version 1.0.0
     */
    public function add_sub_menu() {

        add_submenu_page(
            PostmanViewController::POSTMAN_MENU_SLUG,
            __( 'Reports', 'post-smtp' ),
            __( 'Reports', 'post-smtp' ),
            Postman::MANAGE_POSTMAN_CAPABILITY_NAME,
            'post-smtp-email-reporting',
            array( $this, 'email_reporting' )
        );

    }


    /**
     * Email Reporting
     * 
     * @since 1.0.0
     * @version 1.0.0
     */
    public function email_reporting() {
     
        $url = admin_url( 'admin.php?page=post-smtp-email-reporting&action=ps-get-report' );
        $from_last_seven_days = strtotime( date( 'Y-m-d', strtotime( '-7 days' ) ) );
        $from_last_fourteen_days = strtotime( date( 'Y-m-d', strtotime( '-14 days' ) ) );
        $from_last_thirty_days = strtotime( date( 'Y-m-d', strtotime( '-30 days' ) ) );
        $to = strtotime( date( 'Y-m-d', strtotime( '-1 days' ) + 60 * 60 * 24 ) );
        $redirected_from = isset( $_GET['from'] ) ? date( 'Y-m-d', sanitize_text_field( $_GET['from'] ) ) : '';
        $redirected_to = isset( $_GET['to'] ) ? date( 'Y-m-d', sanitize_text_field( $_GET['to'] ) ) : '';

        ?>
        <div class="wrap">
            <h1>Reports</h1>
            <div class="ps-email-reporting-header">
                <input type="hidden" class="ps-emai-reporting-security" value="<?php echo wp_create_nonce( 'ps-emai-reporting-security' ) ?>">
                <a href="<?php echo esc_url( $url ) ?>" data-from="<?php echo esc_attr( $from_last_seven_days ) ?>" data-to="<?php echo esc_attr( $to ) ?>" class="button button-primary ps-email-log-export-btn ps-email-reporting-filter"><?php _e( 'Last 7 Days', 'psrat' ); ?></a>
                <a href="<?php echo esc_url( $url ); ?>" data-from="<?php echo esc_attr( $from_last_fourteen_days  ) ?>" data-to="<?php echo esc_attr( $to ) ?>" class="button button-primary ps-email-log-export-btn ps-email-reporting-filter"><?php _e( 'Last 14 Days', 'psrat' ); ?></a>
                <a href="<?php echo esc_url( $url ); ?>" data-from="<?php echo esc_attr( $from_last_thirty_days ) ?>" data-to="<?php echo esc_attr( $to ) ?>" class="button button-primary ps-email-log-export-btn ps-email-reporting-filter"><?php _e( 'Last 30 Days', 'psrat' ); ?></a>
                <div class="ps-email-log-date-filter">
                    <label><?php _e( 'From', 'psrat' ); ?> <input type="date" value='<?php echo esc_attr( $redirected_from ) ?>' class="ps-email-reporting-from" /></label>
                    <label><?php _e( 'To', 'psrat' ); ?> <input type="date" value='<?php echo esc_attr( $redirected_to ) ?>' class="ps-email-reporting-to" /></label>
                </div>
                <a href="<?php echo esc_url( $url ); ?>" class="button button-primary ps-email-log-export-btn ps-email-reporting-filter rat-filter-btn"><?php _e( 'Filter', 'psrat' ); ?></a>
            </div>
            <div id="ps-email-reporting-stability-graph"></div>
            <div id="ps-email-reporting-opened-ratio"></div>
            <table width="100%" id="ps-email-reporting-logs">
                <thead>
                    <tr>
                        <th><?php _e( 'Subject', 'psrat' ); ?></th>
                        <th><?php _e( 'Total', 'psrat' ); ?></th>
                        <th><?php _e( 'Sent', 'psrat' ); ?></th>
                        <th><?php _e( 'Failed', 'psrat' ); ?></th>
                        <th><?php _e( 'Open Count', 'psrat' ); ?></th>
                    </tr>
                </thead>
                <tfoot>
                    <tr>
                        <th><?php _e( 'Subject', 'psrat' ); ?></th>
                        <th><?php _e( 'Total', 'psrat' ); ?></th>
                        <th><?php _e( 'Sent', 'psrat' ); ?></th>
                        <th><?php _e( 'Failed', 'psrat' ); ?></th>
                        <th><?php _e( 'Open Count', 'psrat' ); ?></th>
                    </tr>
                </tfoot>
            </table>
        </div>
        <?php

    }


    /**
     * Enqueue Scripts | Action Callback
     * 
     * @since 1.0.0
     * @version 1.0.0
     */
    public function enqueue_scripts() {

		$pluginData = apply_filters( 'postman_get_plugin_metadata', null );

        wp_enqueue_script( 'postman-datatable', POST_SMTP_URL . '/assets/js/dataTable.min.js', array(), $pluginData['version'] );
		wp_enqueue_style( 'postman-datatable', POST_SMTP_URL . '/assets/css/dataTable.min.css', array(), $pluginData['version'] );
        
        wp_enqueue_script( 'post-smtp-email-reporting-plotly', 'https://cdnjs.cloudflare.com/ajax/libs/plotly.js/2.20.0/plotly.min.js', array(), '1.0.0' );
        wp_enqueue_script( 'post-smtp-email-reporting', plugin_dir_url( __DIR__ ) . 'assets/js/graph.js', array( 'jquery', 'post-smtp-email-reporting-plotly' ), '1.0.0', true );
        wp_enqueue_style( PostmanViewController::POSTMAN_STYLE );

    }


    /**
     * Get Report | AJAX Callback
     * 
     * @since 1.0.0
     * @version 1.0.0
     */
    public function get_report() {

        if( 
            isset( $_GET['action'] )
            && 
            $_GET['action'] == 'ps-get-report' 
            && 
            wp_verify_nonce( $_GET['security'], 'ps-emai-reporting-security' ) 
        ) {

            $to = isset( $_GET['to'] ) ? sanitize_text_field( $_GET['to'] ) : '';
            $from = isset( $_GET['from'] ) ? sanitize_text_field( $_GET['from'] ) : '';

            $to = ( isset( $_GET['from'] ) && ( !isset( $_GET['to'] ) || empty( $_GET['to']  ) ) ) ? time() : $to;

            $data = new Post_SMTP_RAT_DB();
            $report['data']['logs'] = $data->get_reporting_logs( $from, $to );
            $report['data']['graph'] = $data->get_reporting_graph_data( $from, $to );
            
            if( $report['data']['graph'] ) {
                
                $report['data']['graph'] = array(
                    'date'          =>  array_column( $report['data']['graph'], 'date' ),
                    'total'         =>  array_column( $report['data']['graph'], 'total' ),
                    'sent'          =>  array_column( $report['data']['graph'], 'sent' ),
                    'failed'        =>  array_column( $report['data']['graph'], 'failed' ),
                    'opened'        =>  array_column( $report['data']['graph'], 'opened' ) 
                );
                
            }

            $report = json_encode( $report );
            
            echo $report;
            die;
            
        }

    }


    /**
     * Delete Logs | Action Callback
     * 
     * @since 1.0.0
     * @version 1.0.0
     */
    public function delete_logs( $ids ) {
    
        $db = new Post_SMTP_RAT_DB();
        
        return $db->delete_logs( $ids );

    }

}

Post_SMTP_RAT_EMail_Reporting::get_instance();

endif;