<?php
namespace PostSMTPSES;

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

class PostSmtpAmazonSesTransport extends \PostmanAbstractModuleTransport implements \PostmanModuleTransport {
    const SLUG = 'aws_ses_api';
    const PORT = 443;
    const HOST = 'amazonses.com';
    const PRIORITY = 8000;
    const SES_AUTH_OPTIONS = 'postman_aws_ses_auth_options';
    const SES_AUTH_SECTION = 'postman_aws_ses_auth_section';

    const OPTION_ACCESS_KEY_ID = 'ses_access_key_id';
    const OPTION_SECRET_ACCESS_KEY = 'ses_secret_access_key';
    const OPTION_REGION = 'ses_region';

    /**
     *
     * @param mixed $rootPluginFilenameAndPath
     */
    public function __construct( $rootPluginFilenameAndPath ) {
        parent::__construct( $rootPluginFilenameAndPath );

        // add a hook on the plugins_loaded event
        add_action( 'admin_init', array(
            $this,
            'on_admin_init',
        ) );

        $this->options = get_option( \PostmanOptions::POSTMAN_OPTIONS );
    }

    public function getProtocol() {
        return 'https';
    }

    // this should be standard across all transports
    public function getSlug() {
        return self::SLUG;
    }
    public function getName() {
        return __( 'AWS SES API', 'post-smtp-ses' );
    }
    /**
     * v0.2.1
     *
     * @return string
     */
    public function getHostname() {
        $options = get_option( \PostmanOptions::POSTMAN_OPTIONS );
		$host = '';

        if (  isset( $options[ self::OPTION_REGION ] ) ) {
        	$host .= $options[ self::OPTION_REGION ] . '.';
        }

        return $host . self::HOST;
    }
    /**
     * v0.2.1
     *
     * @return int
     */
    public function getPort() {
        return self::PORT;
    }
    /**
     * v1.7.0
     *
     * @return string
     */
    public function getTransportType() {
        return 'aws_ses_api';
    }

    /**
     * (non-PHPdoc)
     *
     * @see \PostmanModuleTransport::createMailEngine()
     */
    public function createMailEngine() {
        $engine = new PostSmtpAwsSesMailEngine();
        return $engine;
    }
    public function getDeliveryDetails() {
        /* translators: where (1) is the secure icon and (2) is the transport name */
        return sprintf( __( 'Post SMTP will send mail via the <b>%1$s %2$s</b>.', 'post-smtp-ses' ), '🔐', $this->getName() );
    }

	/**
	 * @param mixed $data
	 *
	 * @return mixed
	 */
    public function prepareOptionsForExport( $data ) {
        $data = parent::prepareOptionsForExport( $data );
        $options = get_option( \PostmanOptions::POSTMAN_OPTIONS );

        $data [ self::OPTION_ACCESS_KEY_ID ] = base64_decode( $options[ self::OPTION_ACCESS_KEY_ID ] );
        $data [ self::OPTION_SECRET_ACCESS_KEY ] = base64_decode( $options[ self::OPTION_SECRET_ACCESS_KEY ] );
        $data [ self::OPTION_REGION ] = $options[ self::OPTION_REGION ];

        return $data;
    }

    /**
     * Validate the settings when you save
     *
     * @return array
     */
    protected function validateTransportConfiguration() {
        $messages = parent::validateTransportConfiguration();
        $options = get_option( \PostmanOptions::POSTMAN_OPTIONS );

        $access_key = isset( $options[ self::OPTION_ACCESS_KEY_ID ] ) ? $options[ self::OPTION_ACCESS_KEY_ID ] : '';
        $secret_access_key = isset( $options[ self::OPTION_SECRET_ACCESS_KEY ] ) ? $options[ self::OPTION_SECRET_ACCESS_KEY ] : '';
        $region = isset( $options[ self::OPTION_REGION ] ) ? $options[ self::OPTION_REGION ] : '';

        if ( empty( $access_key ) ) {
            array_push( $messages, __( 'Access Key can not be empty', 'post-smtp-ses' ) . '.' );
            $this->setNotConfiguredAndReady();
        }

        if ( empty( $secret_access_key ) ) {
            array_push( $messages, __( 'Secret Access Key can not be empty', 'post-smtp-ses' ) . '.' );
            $this->setNotConfiguredAndReady();
        }

        if ( empty( $region ) ) {
            array_push( $messages, __( 'Region can not be empty', 'post-smtp-ses' ) . '.' );
            $this->setNotConfiguredAndReady();
        }
        return $messages;
    }

    /**
     * (non-PHPdoc)
     *
     * @see \PostmanModuleTransport::getConfigurationBid()
     */
    public function getConfigurationBid( \PostmanWizardSocket $hostData, $userAuthOverride, $originalSmtpServer ) {
        $recommendation = array();
        $recommendation ['priority'] = 0;
        $recommendation ['transport'] = self::SLUG;
        $recommendation ['hostname'] = null; // scribe looks this
        $recommendation ['label'] = $this->getName();
        if ( $hostData->hostname == $this->getHostname() && $hostData->port == self::PORT ) {
            $recommendation ['priority'] = self::PRIORITY;
            /* translators: where variables are (1) transport name (2) host and (3) port */
            $recommendation ['message'] = sprintf( __( ('Postman recommends the %1$s to host %2$s on port %3$d.') ), $this->getName(), $this->getHostname(), self::PORT );
        }
        return $recommendation;
    }

    /**
     *
     * @param mixed $hostname
     * @param mixed $response
     */
    public function populateConfiguration( $hostname ) {
        $response = parent::populateConfiguration( $hostname );
        return $response;
    }

    /**
     * Print The option to select when you choose the transport in the wizard
     *
     * @param \PostmanWizardSocket $socket
     * @param $winningRecommendation
     * @param $userSocketOverride
     * @param $userAuthOverride
     * @return array
     */
    public function createOverrideMenu( \PostmanWizardSocket $socket, $winningRecommendation, $userSocketOverride, $userAuthOverride ) {
        $overrideItem = parent::createOverrideMenu( $socket, $winningRecommendation, $userSocketOverride, $userAuthOverride );
        // push the authentication options into the $overrideItem structure
        $overrideItem ['auth_items'] = array(
            array(
                'selected' => true,
                'name' => __( 'AWS SES Credentials', 'post-smtp-ses' ),
                'value' => 'api_key',
            ),
        );
        return $overrideItem;
    }

    /**
     * On admin init - create settings and run scripts
     */
    public function on_admin_init() {
        // only administrators should be able to trigger this
        if ( \PostmanUtils::isAdmin() ) {
            $this->addSettings();
            $this->registerStylesAndScripts();
        }
    }

    /**
     * Create the settings for the plugin
     */
    public function addSettings() {
        // the Auth section
        add_settings_section( self::SES_AUTH_SECTION, __( 'Authentication', 'post-smtp-ses' ), array(
            $this,
            'printAuthSectionInfo',
        ), self::SES_AUTH_OPTIONS );

        add_settings_field( self::OPTION_ACCESS_KEY_ID, __( 'Access Key Id', 'post-smtp-ses' ), array(
            $this,
            'api_key_callback',
        ), self::SES_AUTH_OPTIONS, self::SES_AUTH_SECTION );

        add_settings_field( self::OPTION_SECRET_ACCESS_KEY, __( 'Secret Access Key', 'post-smtp-ses' ), array(
            $this,
            'secret_key_callback',
        ), self::SES_AUTH_OPTIONS, self::SES_AUTH_SECTION );

        add_settings_field( self::OPTION_REGION, __( 'SES Region', 'post-smtp-ses' ), array(
            $this,
            'region_callback',
        ), self::SES_AUTH_OPTIONS, self::SES_AUTH_SECTION );
    }

    public function printAuthSectionInfo() {
        /* Translators: Where (1) is the service URL and (2) is the service name and (3) is a api key URL */
        printf( '<p id="wizard_ses_auth_help">%s</p>', sprintf( __( 'Create an account at <a href="%1$s" target="_blank">%2$s</a> and enter the account id and secret below.', 'post-smtp-ses' ), 'https://aws.amazon.com/ses/', 'https://aws.amazon.com/ses/' ) );
    }


    public function api_key_callback() {
    	$access_key_id = isset( $this->options[ self::OPTION_ACCESS_KEY_ID ] ) ? $this->options[ self::OPTION_ACCESS_KEY_ID ] : '';
        printf( '<input type="password" autocomplete="off" id="' . self::OPTION_ACCESS_KEY_ID . '" name="postman_options[' . self::OPTION_ACCESS_KEY_ID . ']" value="%s" size="60" class="required" placeholder="%s"/>', null !== $access_key_id ? esc_attr( \PostmanUtils::obfuscatePassword( base64_decode( $access_key_id ) ) ) : '', __( 'Required', 'post-smtp-ses' ) );
        print '<input type="button" id="toggle' . self::OPTION_ACCESS_KEY_ID . '" value="Show Password" class="button button-secondary" style="visibility:hidden" />';
    }

    function secret_key_callback() {
	    $access_key_secret = isset( $this->options[ self::OPTION_SECRET_ACCESS_KEY ] ) ? $this->options[ self::OPTION_SECRET_ACCESS_KEY ] : '';
        printf( '<input type="password" autocomplete="off" id="' . self::OPTION_SECRET_ACCESS_KEY . '" name="postman_options[' . self::OPTION_SECRET_ACCESS_KEY . ']" value="%s" size="60" class="required" placeholder="%s"/>', null !== $access_key_secret ? esc_attr( \PostmanUtils::obfuscatePassword( base64_decode( $access_key_secret )  ) ) : '', __( 'Required', 'post-smtp-ses' ) );
        print '<input type="button" id="toggle' . self::OPTION_SECRET_ACCESS_KEY . '" value="Show Password" class="button button-secondary" style="visibility:hidden" />';
    }

    function region_callback() {
        $region = isset( $this->options[ self::OPTION_REGION ] ) ? esc_attr( $this->options[ self::OPTION_REGION ] ) : '';
        printf( '<input type="text" id="' . self::OPTION_REGION . '" name="postman_options[' . self::OPTION_REGION . ']" value="%s" />', $region );
    }

    /**
     */
    public function registerStylesAndScripts() {
        // register the stylesheet and javascript external resources
        $pluginData = apply_filters( 'postman_get_plugin_metadata', null );
        $slug = self::SLUG;
        wp_register_script( "post_smtp_{$slug}", plugins_url( 'assets/postman_aws_ses.js', \Post_Smtp_Amazon_Ses::FILE ), array(
            \PostmanViewController::JQUERY_SCRIPT,
            'jquery_validation',
            \PostmanViewController::POSTMAN_SCRIPT
        ), $pluginData ['version'], true );
    }

    /**
     */
    public function enqueueScript() {
        $slug = self::SLUG;
        wp_enqueue_script( "post_smtp_{$slug}" );
    }

    /**
     * Print Wizard Settings
     */
    public function printWizardAuthenticationStep() {
        print '<section class="wizard_ses">';
        $this->printAuthSectionInfo();
        printf( '<label for="' . self::OPTION_ACCESS_KEY_ID . '">%s</label>', __( 'Access Key Id', 'post-smtp-ses' ) );
        print $this->api_key_callback();
        printf( '<label for="' . self::OPTION_SECRET_ACCESS_KEY . '">%s</label>', __( 'Secret Access Key', 'post-smtp-ses' ) );
        print $this->secret_key_callback();
        printf( '<label for="' . self::OPTION_REGION . '">%s</label>', __( 'Region Host', 'post-smtp-ses' ) );
        print $this->region_callback();
        print $this->documentation();
        print '</section>';
    }

    /**
     * Gets Logo URL
     * 
     * @since 1.0
     * @version 1.0
     */
    public function getLogoURL() {
        return PSASES_ASSETS . 'images/logo.png';
    }

    /**
     * Show Video and documentation to user on wizard
     * 
     * @since 1.0.1
     * @version 1.0
     */
    public function documentation() {

        $content = '
        <div class="ps-amazonses-documentation" style="margin-top: 20px;">
            <div>
            <iframe width="300" height="200" src="https://www.youtube.com/embed/F2AFui3UcC4" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
            </div>
            <div>
                <a href="https://postmansmtp.com/documentation/#setup-the-amazon-ses-mailer-in-post-smtp" target="_blank">Stuck in Setup?</a>
            </div>
        </div>
        ';

        return $content; 

    }
}
