<?php
/**
 * EverestForms MailerLite Admin Settings
 *
 * @package EverestForms\Pro\Addons\Mailerlite\Settings.
 * @version 1.0.0
 * @since   1.7.7
 */

namespace EverestForms\Pro\Addons\Mailerlite\Settings;

defined( 'ABSPATH' ) || exit;


/**
 * Class Settings.
 */
class Settings {

	/**
	 * Account ID for current account.
	 *
	 * @var string
	 */
	public $account = false;

	/**
	 * Initialize.
	 *
	 * @since 1.1.0
	 */
	public function __construct() {
		$this->id                 = 'mailerlite';
		$this->icon               = plugins_url( 'src/Addons/Mailerlite/assets/img/mailerlite.png', EFP_PLUGIN_FILE );
		$this->method_title       = esc_html__( 'MailerLite', 'everest-forms-pro' );
		$this->method_description = esc_html__( 'MailerLite Integration with Everest Forms', 'everest-forms-pro' );
		$connected_lists          = get_option( 'everest_forms_integrations', array() );
		if ( ! empty( $connected_lists[ $this->id ] ) ) {
			$this->account_status = 'connected';
		} else {
			$this->account_status = '';
		}
		add_action( 'everest_forms_integration_account_connect_mailerlite', array( $this, 'api_connect' ) );
	}

	/**
	 * API Connect Mailerlite function.
	 *
	 * @param array $posted_data Has information on api connection & integration.
	 */
	public function api_connect( $posted_data ) {
		if ( ! class_exists( '\MailerLiteApi\MailerLite' ) ) {
			require_once dirname( EFP_PLUGIN_FILE ) . '/vendor/autoload.php';
		}

		try {
			$auth = new \MailerLiteApi\MailerLite( trim( $posted_data['apikey'] ) );
		} catch ( Exception $e ) {
			wp_send_json_error(
				array(
					'error'     => esc_html__( 'Could not connect to the provider.', 'everest-forms-pro' ),
					'error_msg' => $e->getMessage(),
				)
			);
		}
		if ( is_wp_error( $auth ) ) {
			$details = true === $auth ? $auth : __( 'Could not verify API URL', 'everest-forms-pro' );
			// * translators: %s: Error thrown by API authentication issues. */
			EverestForms_MailerLite::log( sprintf( __( 'MailerLite API error: %s', 'everest-forms-pro' ), $details ), 'error' );
			// * translators: %s: Error thrown by API authentication issues. */
			$error_msg = sprintf( __( 'API auth error: %s', 'everest-forms-pro' ), $details );
			wp_send_json_error(
				array(
					'error'     => esc_html__( 'Could not connect to the provider.', 'everest-forms-pro' ),
					'error_msg' => $error_msg,
				)
			);
		}

		$to_be_stored_id    = uniqid();
		$connected_accounts = get_option( 'everest_forms_integrations', array() );

		$connected_accounts['mailerlite'][ $to_be_stored_id ] = array(
			'api'   => trim( $posted_data['apikey'] ),
			'label' => sanitize_text_field( $posted_data['label'] ),
			'date'  => time(),
		);
		update_option( 'everest_forms_integrations', $connected_accounts );

		$output      = '<tr>';
			$output .= '<td><strong>' . sanitize_text_field( $_POST['label'] ) . '</strong></td>'; // @codingStandardsIgnoreLine
			/* translators: %s: Date of connection. */
		$output     .= '<td>' . sprintf( esc_html__( 'Connected on: %s', 'everest-forms-pro' ), date_i18n( get_option( 'date_format', time() ) ) ) . '</td>';
			$output .= '<td><a href="#" class="disconnect everest-forms-integration-disconnect-account" data-source="' . esc_attr( $_POST['source'] ) . '" data-key="' . esc_attr( $to_be_stored_id ) . '">' . esc_html__( 'Disconnect', 'everest-forms-pro' ) . '</a></td>'; // @codingStandardsIgnoreLine
			$output .= '</tr>';

		wp_send_json_success(
			array(
				'html' => $output,
			)
		);
	}

		/**
		 * Facilitates mailerlite integration. Evoked from extensibility.
		 */
	public function output_integration() {
		$connected_lists = get_option( 'everest_forms_integrations', array() );
		if ( ! empty( $connected_lists['mailerlite'] ) ) {
			$status_class = 'Connected';
		} else {
			$status_class = '';
		}
		?>
		<a href="<?php echo esc_url( admin_url( 'admin.php?page=evf-settings&tab=integration' ) ); ?>" class="everest-forms-integration-back-button">
			<span><?php echo esc_html__( 'Back', 'everest-forms-pro' ); ?></span>
		</a>
		<div class="everest-forms-integration-content">
			<div class="integration-addon-detail">
				<div class="evf-integration-info-header">
					<figure class="evf-integration-logo">
						<img src="<?php echo esc_attr( $this->icon ); ?>" alt="<?php echo esc_attr( 'test' ); ?>">
					</figure>
					<div class="integration-info">
						<h3><?php echo $this->method_title; /* phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped */ ?></h3>
						<div class="integration-status <?php echo $status_class; /* phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped */ ?>">
							<span class="toggle-switch connected"><?php echo $status_class; /* phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped */ ?></span>
						</div>
					</div>
				</div>
				<p><?php echo $this->method_description; /* phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped */ ?></p>
			</div>
			<div class="integration-connection-detail">
				<div class="evf-account-connect">
					<h3>Add New Connection</h3>
					<p>Fill out the fields to connect your MailerLite account</p>
					<form>
						<div class="evf-connection-form">
							<input type="text" placeholder="MailerLite API Key" class="evf-apikey">
							<input type="text" placeholder="MailerLite Nick Name" class="evf-nickname">
						</div>
						<a href="#" class="everest-forms-btn everest-forms-btn-primary everest-forms-integration-connect-account" data-source="<?php echo esc_attr( $this->id ); ?>">Connect to MailerLite</a>
					</form>
				</div>
				<div class="evf-connection-list">
					<table class="evf-connection-list-table">
						<tbody>
							<?php
							if ( ! empty( $connected_lists ) && isset( $connected_lists['mailerlite'] ) ) {
								foreach ( $connected_lists['mailerlite'] as $key => $list ) {
									?>
									<tr>
										<td><strong><?php echo sanitize_text_field( $list['label'] ); /* phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped */ ?></strong></td>
										<td>Connected on <?php echo date_i18n( get_option( 'date_format' ), $list['date'] ); /* phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped */ ?></td>
										<td>
											<a href='#' class='disconnect everest-forms-integration-disconnect-account' data-source='mailerlite' data-key='<?php echo esc_attr( $key ); ?>'><?php echo esc_html__( 'Disconnect', 'everest-forms-pro' ); ?></a>
										</td>
									</tr>
									<?php
								}
							}
							?>
						</tbody>
					</table>
				</div>
			</div>
		</div>
		<?php
	}
}
