<?php

require_once 'vendor/autoload.php';
use  PostSMTPSES\PostSmtpAmazonSesTransport ;

if( !defined( 'PSASES_ASSETS' ) ):
    define( 'PSASES_ASSETS', plugin_dir_url( __FILE__ ) . 'assets/' );
endif;

if( !class_exists( 'Post_Smtp_Amazon_Ses' ) ):
class Post_Smtp_Amazon_Ses
{
    const  FILE = __FILE__ ;
    public function __construct()
    {
        $this->validate();
    }
    
    /**
     * Retrieves custom plugin data (Name, Version, and Description) from a plugin file header.
     *
     * This function reads the specified plugin file and extracts key data like the plugin name,
     * version, and description by parsing the file's comment headers.
     *
     * @param string $plugin_file The full path to the plugin file.
     * @return array|false An associative array containing 'Name', 'Version', and 'Description' if the file exists,
     *                     or false if the file does not exist.
     *
     * @since 1.2.3
     * @version 1.1
     */
    public function get_post_smtp_data( $plugin_file ) {
        $plugin_data = array(
            'Name'        => '',
            'Version'     => '',
            'Description' => '',
        );
        
        if ( ! file_exists( $plugin_file ) ) {
            return $plugin_data = array(
            'Name'        => '',
            'Version'     => '',
            'Description' => '',
        );;
        }

        $plugin_contents = file_get_contents( $plugin_file );

        if ( preg_match( '/^.*Plugin Name:\s*(.+)$/mi', $plugin_contents, $matches ) ) {
            $plugin_data['Name'] = trim( $matches[1] );
        }

        if ( preg_match( '/^.*Version:\s*(.+)$/mi', $plugin_contents, $matches ) ) {
            $plugin_data['Version'] = trim( $matches[1] );
        }

        if ( preg_match( '/^.*Description:\s*(.+)$/mi', $plugin_contents, $matches ) ) {
            $plugin_data['Description'] = trim( $matches[1] );
        }

        return $plugin_data;
    }

    /**
     * Validate this Plugin Dependencies
     *
     * @since 1.0.1
     * @version 1.0
     */
    public function validate()
    {
        $phpversion = phpversion();
        if ( !function_exists( 'is_plugin_active' ) ) {
            include_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        if ( !is_plugin_active( 'post-smtp/postman-smtp.php' ) ) {
            add_action( 'admin_notices', array( $this, 'main_notice' ) );
        } elseif ( is_plugin_active( 'post-smtp/postman-smtp.php' ) ) {
       
            $plugin_data = $this->get_post_smtp_data( WP_PLUGIN_DIR . '/post-smtp/postman-smtp.php' );
            if ( version_compare( $plugin_data['Version'], '2.1', '<' ) ) {
                add_action( 'admin_notices', array( $this, 'version_notice' ) );
            } elseif ( version_compare( $phpversion, '7.0', '<' ) ) {
                add_action( 'admin_notices', array( $this, 'php_version_notice' ) );
            } else {
                $this->init();
            }
        
        }
    
    }
    
    /**
     * Throws notice of Post SMTP Missing
     *
     * @since 1.0.1
     * @version 1.0
     */
    public function main_notice()
    {
        ?>
        <div class="notice notice-error is-dismissible">
            <p>In order to use Amazon SES Extenstion, make sure Installed and Active <a href='https://wordpress.org/plugins/post-smtp/' target="_blank">Post SMTP</a></p>
        </div>
        <?php 
    }
    
    /**
     * Version Compatiblity issue
     *
     * @since 1.0.1
     * @version 1.0
     */
    public function version_notice()
    {
        ?>
        <div class="notice notice-error is-dismissible">
            <p>In order to use Amazon SES Extenstion, Update <a href='https://wordpress.org/plugins/post-smtp/' target="_blank">Post SMTP</a> to latest Version.</p>
        </div>
        <?php 
    }
    
    /**
     * PHP Version Compatiblity Notice
     *
     * @since 1.0.1
     * @version 1.0
     */
    public function php_version_notice()
    {
        $phpversion = phpversion();
        ?>
        <div class="notice notice-error is-dismissible">
            <p>Amazon SES for Post SMTP requires PHP 7.1 or greater version, you currently have <?php 
             echo  esc_html( $phpversion ) ;
        ?></p>
        </div>
        <?php 
    }
    
    /**
     * Finally Initialize Plugin :)
     * 
     * @since 1.0
     * @version 1.0
     */
    private function init()
    {
        $this->hooks();
    }
    
    /**
     * Hooks and Filters
     *
     * @since 1.0
     * @version 1.0
     */
    private function hooks()
    {
        add_action( 'postsmtp_register_transport', array( $this, 'register_transport' ) );
        add_filter( 'plugin_action_links_' . plugin_basename( self::FILE ), array( $this, 'add_plugin_row_links' ) );
        add_filter(
            'post_smtp_sanitize',
            [ $this, 'sanitize_options' ],
            10,
            3
        );
        add_action( 'post_smtp_settings_sections', [ $this, 'add_custom_section' ] );
        //Control Test email args
        add_filter( 'postman_test_email_args', array( $this, 'postman_test_email_args' ) );
    }
    
    /**
     * Notifies admin to meet requirements
     *
     * @since 1.0
     * @version 1.0
     */
    public function admin_notices()
    {
        ?>
        <div class="notice notice-error is-dismissible">
             <p>
            <?php 
        echo  'In order to use Post SMTP Extension Amazon SES, make sure <a href=\'https://wordpress.org/plugins/post-smtp/\' target=\'_blank\'>Post SMTP</a> is install and active.' ;
        ?>
            </p>
        </div>
        <?php 
    }
    
    /**
     * Registers Transport
     *
     * @since 1.0
     * @version 1.0
     */
    function register_transport( $postman_transport_registry )
    {
        $postman_transport_registry->registerTransport( new PostSmtpAmazonSesTransport( Postman::$rootPlugin ) );
    }
    
    /**
     * FOR TEST MAIL ONLY | Making Email compatible to Amazon SES
     *
     * @since 1.0
     * @version 1.0
     */
    public function postman_test_email_args( $args )
    {
        $args['header'] = explode( PostmanMessage::EOL, $args['header'] );
        unset( $args['header'][1] );
        $args['header'] = implode( PostmanMessage::EOL, $args['header'] );
        return $args;
    }
    
    public function add_plugin_row_links( $links )
    {
        // only administrators should be able to trigger this
        
        if ( PostmanUtils::isAdmin() ) {
            $mylinks = array( sprintf( '<a href="%s" target="_blank" class="postman_settings">%s</a>', 'https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&business=yehuda@myinbox.in&item_name=Donation+for+PostSMTP', __( 'Donate', 'post-smtp' ) ), sprintf( '<a href="%s" class="postman_settings">%s</a>', PostmanUtils::getSettingsPageUrl(), __( 'Settings', 'post-smtp' ) ), sprintf( '<a href="%s" class="postman_settings">%s</a>', 'https://postmansmtp.com', __( 'Visit us', 'post-smtp' ) ) );
            return array_merge( $mylinks, $links );
        }
    
    }
    
    /**
     * @param $new_input
     * @param $input
     * @param PostmanInputSanitizer $sanitize
     * @return mixed
     */
    public function sanitize_options( $new_input, $input, $sanitize )
    {
        $options = get_option( PostmanOptions::POSTMAN_OPTIONS );
        $sanitize->sanitizePassword(
            'AWS SES Access Key',
            PostSmtpAmazonSesTransport::OPTION_ACCESS_KEY_ID,
            $input,
            $new_input,
            base64_decode( $options[PostSmtpAmazonSesTransport::OPTION_ACCESS_KEY_ID] )
        );
        $sanitize->sanitizePassword(
            'AWS SES Secret Access',
            PostSmtpAmazonSesTransport::OPTION_SECRET_ACCESS_KEY,
            $input,
            $new_input,
            base64_decode( $options[PostSmtpAmazonSesTransport::OPTION_SECRET_ACCESS_KEY] )
        );
        $sanitize->sanitizeString(
            'AWS SES Region',
            PostSmtpAmazonSesTransport::OPTION_REGION,
            $input,
            $new_input
        );
        return $new_input;
    }
    
    public function add_custom_section()
    {
        print '<div id="ses_settings" class="authentication_setting non-basic non-oauth2">';
        do_settings_sections( PostSmtpAmazonSesTransport::SES_AUTH_OPTIONS );
        print '</div>';
    }

    public function psp_load_amazon_ses_mail(){
        if ( ! class_exists( 'PostmanMailEngine' ) ) {
            $post_smtp = WP_PLUGIN_DIR . '/post-smtp/Postman/Postman-Mail/PostmanMailEngine.php';
            if ( file_exists( $post_smtp ) ) {
                require_once $post_smtp;
            } 
        }
        require_once 'src/PostSmtpAmazonSesTransport.php';
        require_once 'src/PostSmtpAwsSesMailEngine.php';
    }

}

new Post_Smtp_Amazon_Ses();
endif;

if ( !class_exists( 'PostmanAbstractModuleTransport' ) ) {
    add_action('post_smtp_init',  array( new Post_Smtp_Amazon_Ses() , 'psp_load_amazon_ses_mail' ) );
} else {
    $instance = new Post_Smtp_Amazon_Ses();
    $instance->psp_load_amazon_ses_mail();
}