<?php

if( !class_exists( 'Post_SMTP_Track' ) ):

class Post_SMTP_Track {

    /**
     * Instance of the class
     * 
     * @since 1.0.0
     * @version 1.0.0
     * @var object
     */
    private static $instance = null;
    private $email_id = '';

    /**
     * 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;

    }

    
    /**
     * PostSMTP_Track constructor.
     * 
     * @since 1.0.0
     * @version 1.0.0
     */
    public function __construct() {

        add_filter( 'wp_mail', array( $this, 'wp_mail' ), 9  );
        add_action( 'post_smtp_email_logs_table_header', array( $this, 'email_logs_table_header' ) );
        add_filter( 'post_smtp_email_logs_localize', array( $this, 'email_logs_localize' ) );
        add_filter( 'post_smtp_get_logs_query_cols', array( $this, 'query_columns' ), 10, 2 );
        add_filter( 'post_smtp_get_logs_query_after_table', array( $this, 'query_join' ), 5, 2 );
        add_filter( 'post_smtp_get_logs_args', array( $this, 'logs_args' ) );
        add_filter( 'ps_email_logs_row', array( $this, 'escape_event_type' ), 10, 1 );
        add_action( 'admin_enqueue_scripts', array( $this, 'admin_enqueue_scripts' ) );

    }

    
       /**
     * Track the email | Action Callback
     * 
     * @since 1.0.0
     * @version 1.0.0
     */
    public function wp_mail( $args ) {
       // 🔒 Bypass if we're inside batch mode
		if ( ! empty( $GLOBALS['post_smtp_suppress_logging'] ) ) {
			return $args;
		}
		
	  	$post_smtp_pro_options = get_option( 'post_smtp_pro' );
	    $bonus_extensions = isset( $post_smtp_pro_options['bonus_extensions'] ) ? $post_smtp_pro_options['bonus_extensions'] : array();
    	$enable_advance_delivery_enabled = in_array( 'email-delivery-and-logs', $bonus_extensions );
		
		if( $enable_advance_delivery_enabled ){
			$settings = get_option( PS_AEDL_Settings::OPTION );
			$enabled_advance_delivery = psaedl_extract_value_from_option( $settings, 'enable_advance_delivery' );
		}

        if( !class_exists( 'PostmanEmailLogs' ) ) {
            require_once POST_SMTP_PATH . 'Postman/PostmanEmailLogs.php';
        }
		
		$log_id = apply_filters( 'post_smtp_current_email_id', false );

        //First we need to insert the email into the log table, to get the ID  
		if ( ! $log_id ) {
            $query_log = new PostmanEmailLogs();
            $log_id    = $query_log->save( array() );
        }
		
		$this->email_id = $log_id;
        // // Expose this email id for other extensions
		add_filter( 'post_smtp_current_email_id', function() use ( $log_id ) {
			return $log_id;
		} );

        //Lets add the email ID to the filter, to update the the existing log when the email is sent
        add_filter( 'post_smtp_update_email_log_id', array( $this, 'set_email_id' ) );
		
        $mail_event = new Post_SMTP_RAT_Mail_Event( $this->email_id, $args['to'], 'open-email' );
		
        //Lets Insert Tracking Code
        if ( strpos( $args['message'], '</body>' ) !== false ) {
           $args['message'] = str_replace( '</body>', '<!-- HTML Ignored -->' . $mail_event->get_tracking_html() . '</body>', $args['message'] );
        }

		postman_add_log_meta( $this->email_id, 'track_code', $mail_event->get_tracking_html() );
        //We can not track the email, if the message does not have HTML :(
       
        return $args;

    }



    /**
     * Set Email ID | Filter Callback
     * 
     * @since 1.0.0
     * @version 1.0.0
     */
    public function set_email_id( $email_id ) {

        $email_id = $this->email_id;
        
        return $email_id;

    }


    /**
     * Add Opened Column | Action Callback
     * 
     * @since 1.0.0
     * @version 1.0.0
     */
    public function email_logs_table_header() {

        echo '<th>' . __( 'Opened', 'psrat' ) . '</th>';

    }


    /**
     * Localize the strings | Filter Callback
     * 
     * @since 1.0.0
     * @version 1.0.0
     */
    public function email_logs_localize( $localize ) {

        $localize['DTCols'][] = array(
            'data'    => 'event_type',
        );

        return $localize;

    }


    /**
     * Add Opened Column | Filter Callback
     * 
     * @param $columns String
     * @param $args Array
     * @since 1.0.0
     * @version 1.0.0
     */
    public function query_columns( $columns, $args ) {

        $columns .= ', rat.event_type';

        return $columns;

    }


    /**
     * Add Opened Column | Filter Callback
     * 
     * @param $join String
     * @param $args Array
     * @since 1.0.0
     * @version 1.0.0
     */
    public function query_join( $join, $args ) {

        $db = new Post_SMTP_RAT_DB();
        $table_name = $db->get_table_name();

        $join .= " LEFT JOIN {$table_name} AS rat ON rat.email_id = pl.id";
        
        return $join;

    }


    /**
     * Add Opened Column | Filter Callback
     * 
     * @param $args Array
     * @since 1.0.0
     * @version 1.0.0
     * 
     */
    public function logs_args( $args ) {

        if( isset( $args['order_by'] ) && $args['order_by'] == 'event_type' ) {

            $args['order_by'] = 'rat.event_type';

        }

        return $args;

    }


    /**
     * Escape event_type on output to prevent Stored XSS.
     *
     * @param object $row The email log row object.
     * @return object The row with escaped event_type.
     * @since 1.0.0
     */
    public function escape_event_type( $row ) {

        if ( isset( $row->event_type ) ) {
            $row->event_type = esc_html( $row->event_type );
        }

        return $row;

    }


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

        wp_enqueue_script( 'post-smtp-rat', plugin_dir_url( __DIR__ ) . 'assets/js/admin.js', array(), '1.0.0', true );
        wp_enqueue_style( 'post-smtp-rat', plugin_dir_url( __DIR__ ) . 'assets/css/admin.css', array(), '1.0.0' );

        wp_localize_script( 'post-smtp-rat', 'psrat', array(
            'ajax_url' => admin_url( 'admin-ajax.php' ),
            'text'     => array(
                'delivery_stability'    => __( 'Delivery Stability', 'psrat' ),
                'open_ratio'            => __( 'Open Ratio', 'psrat' )
            ),
        ) );

    }

}

Post_SMTP_Track::get_instance();

endif;