<?php

class HappyForms_Integrations {

	private static $instance;
	private static $hooked = false;

	private $option_name = '_happyforms_service_credentials';
	private $services = array();
	private $data = array();
	private $credentials = array();

	public $action_update = 'happyforms-service-update';
	public $nonce_update = 'happyforms_update_nonce';

	public static function instance() {
		if ( is_null( self::$instance ) ) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	public function __construct() {
		require_once( happyforms_get_integrations_folder() . '/classes/class-api-request.php' );
		require_once( happyforms_get_integrations_folder() . '/classes/class-service.php' );

		// reCaptcha
		require_once( happyforms_get_integrations_folder() . '/services/recaptcha/class-service-recaptcha.php' );
		$this->register_service( 'HappyForms_Service_Recaptcha' );

		// reCaptcha V3
		require_once( happyforms_get_integrations_folder() . '/services/recaptchav3/class-service-recaptchav3.php' );
		$this->register_service( 'HappyForms_Service_RecaptchaV3' );

		// AntiSpam
		require_once( happyforms_get_integrations_folder() . '/services/antispam/class-service-antispam.php' );
		$this->register_service( 'HappyForms_Service_AntiSpam' );

		// ActiveCampaign
		require_once( happyforms_get_integrations_folder() . '/services/active-campaign/class-service-active-campaign.php' );
		$this->register_service( 'HappyForms_Service_ActiveCampaign' );

		// AWeber
		require_once( happyforms_get_integrations_folder() . '/services/aweber/class-service-aweber.php' );
		$this->register_service( 'HappyForms_Service_AWeber' );

		// Constant Contact
		require_once( happyforms_get_integrations_folder() . '/services/constant-contact/class-service-constant-contact.php' );
		$this->register_service( 'HappyForms_Service_ConstantContact' );

		// ConvertKit
		require_once( happyforms_get_integrations_folder() . '/services/convertkit/class-service-convertkit.php' );
		$this->register_service( 'HappyForms_Service_ConvertKit' );

		// Mailchimp
		require_once( happyforms_get_integrations_folder() . '/services/mailchimp/class-service-mailchimp.php' );
		$this->register_service( 'HappyForms_Service_Mailchimp' );

		// MailerLite
		require_once( happyforms_get_integrations_folder() . '/services/mailerlite/class-service-mailerlite.php' );
		$this->register_service( 'HappyForms_Service_MailerLite' );

		// MailPoet
		require_once( happyforms_get_integrations_folder() . '/services/mailpoet/class-service-mailpoet.php' );
		$this->register_service( 'HappyForms_Service_MailPoet' );

		// SendFox
		require_once( happyforms_get_integrations_folder() . '/services/sendfox/class-service-sendfox.php' );
		$this->register_service( 'HappyForms_Service_SendFox' );

		// SendGrid
		require_once( happyforms_get_integrations_folder() . '/services/sendgrid/class-service-sendgrid.php' );
		$this->register_service( 'HappyForms_Service_SendGrid' );

		// Sendinblue
		require_once( happyforms_get_integrations_folder() . '/services/sendinblue/class-service-sendinblue.php' );
		$this->register_service( 'HappyForms_Service_Sendinblue' );

		// Email
		require_once( happyforms_get_integrations_folder() . '/services/email/class-service-email.php' );
		$this->register_service( 'HappyForms_Service_Email' );

		// Stripe
		require_once( happyforms_get_integrations_folder() . '/services/stripe/class-service-stripe.php' );
		$this->register_service( 'HappyForms_Service_Stripe' );

		// PayPal
		require_once( happyforms_get_integrations_folder() . '/services/paypal/class-service-paypal.php' );
		$this->register_service( 'HappyForms_Service_PayPal' );

		// Payments
		require_once( happyforms_get_integrations_folder() . '/services/payments/class-service-payments.php' );
		require_once( happyforms_get_integrations_folder() . '/services/payments/class-integration-payments.php' );
		$this->register_service( 'HappyForms_Service_Payments' );

		// Google Analytics
		require_once( happyforms_get_integrations_folder() . '/services/google-analytics/class-service-google-analytics.php' );
		$this->register_service( 'HappyForms_Service_Google_Analytics' );

		// Analytics
		require_once( happyforms_get_integrations_folder() . '/services/analytics/class-service-analytics.php' );
		$this->register_service( 'HappyForms_Service_Analytics' );

		// Zapier
		require_once( happyforms_get_integrations_folder() . '/services/zapier/class-service-zapier.php' );
		$this->register_service( 'HappyForms_Service_Zapier' );

		// Integromat
		require_once( happyforms_get_integrations_folder() . '/services/integromat/class-service-integromat.php' );
		$this->register_service( 'HappyForms_Service_Integromat' );

		// Automation
		require_once( happyforms_get_integrations_folder() . '/services/automation/class-service-automation.php' );
		$this->register_service( 'HappyForms_Service_Automation' );

		require_once( happyforms_get_integrations_folder() . '/classes/class-integrations-page-controller.php' );
	}

	public function hook() {
		if ( self::$hooked ) {
			return;
		}

		self::$hooked = true;

		add_action( 'admin_enqueue_scripts', array( $this, 'admin_enqueue_scripts' ) );
		add_action( 'wp_ajax_' . $this->action_update, array( $this, 'ajax_service_update' ) );
		add_action( 'happyforms_customize_enqueue_scripts', array( $this, 'customize_enqueue_scripts' ) );

		$this->read_credentials();
		$this->configure_services();
	}

	public function read_credentials() {
		$this->credentials = get_option( $this->option_name, array() );
	}

	public function get_all_credentials() {
		return $this->credentials;
	}

	public function write_credentials() {
		$this->credentials = array_map( function( $service ) {
			return $service->get_credentials();
		}, $this->services );

		update_option( $this->option_name, $this->credentials );
	}

	public function register_service( $service ) {
		$service = $service instanceof HappyForms_Service ? $service : new $service();
		$this->services[$service->id] = $service;
	}

	public function configure_services() {
		foreach( $this->services as $service ) {
			$credentials = array();

			if ( isset ( $this->credentials[$service->id] ) ) {
				$credentials = $this->credentials[$service->id];
			}

			$service->set_credentials( $credentials );
			$service->configure();
		}
	}

	public function get_services() {
		return $this->services;
	}

	public function get_service( $id ) {
		if ( isset( $this->services[$id] ) ) {
			return $this->services[$id];
		}

		return false;
	}

	public function ajax_service_update() {
		if ( ! check_ajax_referer( $this->action_update ) ) {
			wp_die();
		}

		if ( ! isset( $_REQUEST['services'] ) ) {
			wp_die();
		}

		$services = $_REQUEST['services'];
		$group = '';
		$group_service = null;

		if ( isset( $_REQUEST['group'] ) ) {
			$group = sanitize_text_field( $_REQUEST['group'] );
			$group_service = $this->services[$group];

			if ( empty( array_filter( $services ) ) ) {
				$group_service->reset_active_service();
			}
		}

		if ( empty( $services ) ) {
			wp_die();
		}

		$response        = '';
		$success_message = __( 'Changes saved.', 'happyforms' );

		ob_start();

		foreach ( $services as $service ) {
			if ( ! isset( $this->services[$service] ) ) {
				wp_send_json_success( array(
					'message' => $success_message,
				) );
			}

			$the_service = $this->services[$service];

			if ( ! isset( $_REQUEST['credentials'] ) ) {
				wp_die();
			}

			$service_credentials = $the_service->get_credentials();
			
			if ( ! isset( $_REQUEST['credentials'][$the_service->id] ) ) {
				$_REQUEST['credentials'][$the_service->id] = $service_credentials;
			}

			$credentials = wp_parse_args( $_REQUEST['credentials'][$the_service->id], $service_credentials );
			$credentials = array_intersect_key( $credentials, $service_credentials );
			$credentials = array_map( 'sanitize_text_field', $credentials );

			if ( ! empty( $group ) && ! $group_service->supports_multiple ) {
				$group_service->set_active_service( $the_service->id );
			}

			$previous_credentials = $the_service->get_credentials();
			$the_service->set_credentials( $credentials, $_REQUEST['credentials'][$the_service->id] );
			$this->write_credentials();
			$the_service->admin_widget( $previous_credentials );
		}

		$response = ob_get_clean();

		$group_label = ( ! is_null( $group_service ) ) ? $group_service->label : '';

		wp_send_json_success( array(
			'html' => $response,
			'message' => $success_message,
		) );
	}

	public function admin_enqueue_scripts() {
		if ( ! isset( $_GET['page'] ) || 'happyforms-integrations' !== $_GET['page'] ) {
			return;
		}

		wp_enqueue_style(
			'happyforms-integrations',
			happyforms_get_plugin_url() . 'integrations/assets/css/admin.css'
		);

		wp_enqueue_script(
			'happyforms-integrations',
			happyforms_get_plugin_url() . 'integrations/assets/js/dashboard.js',
			array( 'jquery' ), HAPPYFORMS_VERSION, true
		);
	}

	public function customize_enqueue_scripts() {
		$services = array();

		foreach ( $this->services as $service ) {
			switch( $service->id ) {
				case 'email':
					$services['email'] = ( ! empty( $service->active_service ) ) ? $service->active_service->id : 0;
					break;
				case 'antispam':
					$services['antispam'] = ( ! empty( $service->active_service ) ) ? $service->active_service->id : 0;
					break;
				default:
					break;
			}

			if ( empty( $service->group ) || 'email' === $service->group || 'antispam' === $service->group ) {
				continue;
			}

			$services[$service->id] = ( $service->is_connected() ) ? 1 : 0;
		}

		wp_localize_script(
			'happyforms-customize',
			'_happyFormsIntegrations',
			$services
		);
	}

}

if ( ! function_exists( 'happyforms_get_integrations' ) ):

function happyforms_get_integrations() {
	$instance = HappyForms_Integrations::instance();
	$instance->hook();

	return $instance;
}

endif;

happyforms_get_integrations();
