<?php

if( !class_exists( 'PS_AEDL_Truncate_Log' ) ):

class PS_AEDL_Truncate_Log {

    static $instance = null;
    private $delete_logs_days = 0;
    private $auto_retry = false;
    private $times_to_retry = 0;

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

    }

    /**
     * constructor of the class
     * 
     * @since 1.0.0
     * @version 1.0.0
     */
    public function __construct() {

        $settings = get_option( PS_AEDL_Settings::OPTION );
        $this->delete_logs_days = psaedl_extract_value_from_option( $settings, 'delete_logs_days' );
        $this->auto_retry = psaedl_extract_value_from_option( $settings, 'enable_auto_retry' );
        $this->times_to_retry = psaedl_extract_value_from_option( $settings, 'times_to_retry' );

        if( !empty( $this->delete_logs_days ) && $this->delete_logs_days != 0 ) {

            add_filter( 'post_smtp_truncate_the_log', array( $this, 'truncate_log' ) );

        }

    }


    /**
     * Truncate the log | Filter Callback
     * 
     * @since 1.0.0
     * @version 1.0.0
     */
    public function truncate_log() {

        if( !class_exists( 'PostmanEmailLogs' ) ) {

            require_once POST_SMTP_PATH . '/Postman/PostmanEmailLogs.php';

        }

        global $wpdb;
        $emails_logs = new PostmanEmailLogs();

        if( $this->auto_retry ) {

            $wpdb->query(
                $wpdb->prepare(
                    "DELETE pl, lm
                    FROM {$wpdb->prefix}{$emails_logs->db_name} AS pl
                    LEFT JOIN
                    {$wpdb->prefix}{$emails_logs->meta_table} AS lm
                    ON pl.id = lm.log_id AND lm.meta_key = 'retried'
                    WHERE FROM_UNIXTIME( pl.`time` ) < NOW() - INTERVAL %d DAY AND pl.success != 'In Queue' AND ( lm.meta_value >= %d OR lm.meta_key IS NULL );",
                    $this->delete_logs_days,
                    $this->times_to_retry
                )
            );

        }
        else {

            $wpdb->query(
                $wpdb->prepare(
                    "DELETE pl, lm
                    FROM {$wpdb->prefix}{$emails_logs->db_name} AS pl
                    LEFT JOIN
                    {$wpdb->prefix}{$emails_logs->meta_table} AS lm
                    ON pl.id = lm.log_id
                    WHERE FROM_UNIXTIME( pl.`time` ) < NOW() - INTERVAL %d DAY && pl.success != 'In Queue';",
                    $this->delete_logs_days
                )
            );

        }

        return false;

    }

}

PS_AEDL_Truncate_Log::get_instance();

endif;