<?php
/**
 * Masteriyo HubSpot addon setup.
 *
 * @package Masteriyo\Addons\HubSpotIntegration
 *
 * @since 2.14.4
 */
namespace Masteriyo\Addons\HubSpotIntegration;

use Masteriyo\Addons\HubSpotIntegration\Controllers\HubSpotIntegrationController;
use Masteriyo\Addons\HubSpotIntegration\API\API;
use Masteriyo\Constants;
use Masteriyo\Traits\Singleton;

defined( 'ABSPATH' ) || exit;

/**
 * Main Masteriyo HubSpotIntegration class.
 *
 * @class Masteriyo\Addons\HubSpotIntegration
 *
 * @since 2.14.4
 */
class HubSpotIntegrationAddon {

	use Singleton;

	/**
	 * Initialize.
	 *
	 * @since 2.14.4
	 */
	public function init() {
		$this->init_hooks();
	}

	/**
	 * Initialize hooks.
	 *
	 * @since 2.14.4
	 */
	public function init_hooks() {
		add_filter( 'masteriyo_checkout_fields', array( $this, 'add_hubspot_consent_checkbox_field_for_checkout' ) );
		add_filter( 'masteriyo_registration_form_fields', array( $this, 'add_hubspot_consent_checkbox_field' ) );
		add_action( 'masteriyo_registration_form_before_submit_button', array( $this, 'render_container_for_hubspot' ) );
		add_action( 'masteriyo_checkout_form_content', array( $this, 'render_container_for_hubspot' ), 125 );
		add_filter( 'masteriyo_get_template', array( $this, 'change_template_for_hubspot' ), 10, 5 );
		add_action( 'masteriyo_created_customer', array( $this, 'handle_customer_creation' ), 10, 3 );
		add_filter( 'masteriyo_rest_response_setting_data', array( $this, 'append_setting_in_response' ) );
		add_action( 'masteriyo_new_setting', array( $this, 'save_settings' ) );
		add_filter( 'masteriyo_rest_api_get_rest_namespaces', array( $this, 'register_rest_namespaces' ) );
	}

	/**
	 * Adds "masteriyo_hubspot_consent_checkbox" to the checkout form fields.
	 *
	 * @since 2.14.4
	 *
	 * @param array $fields The checkout form fields.
	 * @return array The updated checkout form fields.
	 */
	public function add_hubspot_consent_checkbox_field_for_checkout( $fields ) {
		$access_token = HubSpotIntegrationSettings::get_access_token();

		if ( empty( $access_token ) || ! masteriyo_string_to_bool( HubSpotIntegrationSettings::get( 'is_connected' ) ) ) {
			return $fields;
		}

		$forced_email_subscription = masteriyo_string_to_bool( HubSpotIntegrationSettings::get( 'enable_forced_email_subscription' ) );

		if ( $forced_email_subscription ) {
			return $fields;
		}

		$fields['masteriyo_hubspot_consent_checkbox'] = array(
			'label'        => __( 'HubSpot Consent Checkbox', 'learning-management-system' ),
			'enable'       => true,
			'required'     => false,
			'type'         => 'checkbox',
			'class'        => array( 'form-row-wide' ),
			'autocomplete' => 'no',
			'priority'     => 125,
		);

		return $fields;
	}

	/**
	 * Adds "masteriyo_hubspot_consent_checkbox" to the registration form fields.
	 *
	 * @since 2.14.4
	 *
	 * @param array $fields The registration form fields.
	 * @return array The updated registration form fields.
	 */
	public function add_hubspot_consent_checkbox_field( $fields ) {
		$fields[] = 'masteriyo_hubspot_consent_checkbox';

		return $fields;
	}

	/**
	 * Renders a container for HubSpot email subscription.
	 *
	 * @since 2.14.4
	 */
	public function render_container_for_hubspot() {
		$access_token = HubSpotIntegrationSettings::get_access_token();

		if ( empty( $access_token ) || ! masteriyo_string_to_bool( HubSpotIntegrationSettings::get( 'is_connected' ) ) ) {
			return;
		}

		$forced_email_subscription = masteriyo_string_to_bool( HubSpotIntegrationSettings::get( 'enable_forced_email_subscription' ) );

		if ( $forced_email_subscription ) {
			return;
		}

		$consent_message = HubSpotIntegrationSettings::get( 'subscriber_consent_message' );
		$consent_message = empty( $consent_message ) ? 'I would like to receive the newsletters.' : $consent_message;

		/* translators: %s is the consent message */
		$consent_message = sprintf( esc_html__( '%s', 'masteriyo' ), $consent_message ); // phpcs:ignore

		masteriyo_get_template( 'hubspot-integration/hubspot-integration-container.php', array( 'consent_message' => $consent_message ) );
	}

	/**
	 * Changes the template for HubSpot integration specific templates.
	 *
	 * This function changes the template for HubSpot integration specific templates.
	 * It changes the template only if it matches the template name in the template map.
	 *
	 * @since 2.14.4
	 *
	 * @param string $template The template path.
	 * @param string $template_name The template name.
	 *
	 * @return string The updated template path or the original template path.
	 */
	public function change_template_for_hubspot( $template, $template_name ) {

		$template_map = array(
			'hubspot-integration/hubspot-integration-container.php' => 'hubspot-integration-container.php',
		);

		if ( isset( $template_map[ $template_name ] ) ) {
			$new_template = trailingslashit( Constants::get( 'MASTERIYO_HUBSPOT_INTEGRATION_TEMPLATES' ) ) . $template_map[ $template_name ];

			return file_exists( $new_template ) ? $new_template : $template;
		}

		return $template;
	}

	/**
	 * Handles customer creation in HubSpot integration.
	 *
	 * @since 2.14.4
	 *
	 * @param \Masteriyo\Models\User    $user The user object.
	 * @param string                    $password_generated The generated password.
	 *
	 * @param array                     $args The form arguments.
	 */
	public function handle_customer_creation( $user, $password_generated, $args ) {
		if ( ! $user instanceof \Masteriyo\Models\User ) {
			return;
		}

		$forced_email_subscription = masteriyo_string_to_bool( HubSpotIntegrationSettings::get( 'enable_forced_email_subscription' ) );
		$user_consent              = sanitize_text_field( masteriyo_array_get( $args, 'masteriyo_hubspot_consent_checkbox' ) );
		$user_consent              = 'on' === $user_consent || '1' === $user_consent ? true : false;

		if ( ! $user_consent && ! $forced_email_subscription ) {
			return;
		}

		$email = $user->get_email();

		$api = new API( HubSpotIntegrationSettings::get_access_token() );

		$data = array(
			'properties' => array(
				'email'     => $email,
				'firstname' => $user->get_first_name(),
				'lastname'  => $user->get_last_name(),
			),
		);

		$response = $api->create_contact( $data );

		if ( is_wp_error( $response ) ) {
			masteriyo_get_logger()->error( $response->get_error_message() . " For email: {$email}", array( 'source' => 'hubspot-integration' ) );
		}

		masteriyo_get_logger()->info( "HubSpot contact created for email: {$email}", array( 'source' => 'hubspot-integration' ) );

		$record_id = isset( $response['id'] ) ? $response['id'] : '';

		if ( empty( $record_id ) ) {
			return;
		}

		$list = HubSpotIntegrationSettings::get( 'list' );

		if ( empty( $list ) ) {
			return;
		}

		$response = $api->add_to_list( $record_id, $list );

		if ( is_wp_error( $response ) ) {
			masteriyo_get_logger()->error( $response->get_error_message() . " For email: {$email}", array( 'source' => 'hubspot-integration' ) );
		}

		masteriyo_get_logger()->info( "HubSpot contact added to list: {$list} for email: {$email}", array( 'source' => 'hubspot-integration' ) );
	}

	/**
	 * Appends HubSpot Integration settings to the response data.
	 *
	 * @since 2.14.4
	 *
	 * @param array $data Response data.
	 * @return array Modified response data.
	 */
	public function append_setting_in_response( $data ) {
		$data['integrations']['hubspot_integration'] = HubSpotIntegrationSettings::all( array( 'api_key' ) );

		return $data;
	}

	/**
	 * Saves HubSpot Integration settings.
	 *
	 * @since 2.14.4
	 *
	 * @return void
	 */
	public function save_settings() {
		if ( ! masteriyo_is_rest_api_request() ) {
			return;
		}

		$request = masteriyo_current_http_request();

		if ( ! isset( $request['integrations']['hubspot_integration'] ) ) {
			return;
		}

		$settings = masteriyo_array_only( $request['integrations']['hubspot_integration'], array_keys( HubSpotIntegrationSettings::all() ) );
		$settings = masteriyo_parse_args( $settings, HubSpotIntegrationSettings::all() );

		$settings['enable_forced_email_subscription'] = sanitize_text_field( $settings['enable_forced_email_subscription'] ?? false );
		$settings['list']                             = sanitize_text_field( $settings['list'] ?? '' );
		$settings['subscriber_consent_message']       = sanitize_text_field( $settings['subscriber_consent_message'] ?? '' );

		unset( $settings['access_token'] );

		HubSpotIntegrationSettings::set_props( $settings );
		HubSpotIntegrationSettings::save();
	}


	/**
	 * Registers the HubSpot Integration namespace to the REST API.
	 *
	 * @since 2.14.4
	 *
	 * @param array $namespaces List of namespaces and their controllers.
	 *
	 * @return array Modified list of namespaces and their controllers.
	 */
	public function register_rest_namespaces( $namespaces ) {
		$namespaces['masteriyo/v1']['hubspot-integration'] = HubSpotIntegrationController::class;

		return $namespaces;
	}
}
