<?php
/**
 * This file handles the customer demo requests and email alerts.
 *
 * @package object-data-sync-for-salesforce
 */

namespace MoSfSyncSalesforce;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use MoSfSyncSalesforce\Helper\Plugin_Constants;
use MoSfSyncSalesforce\Services\DB_Utils;

/**
 * Handles the customer account and demo/support request email operations.
 */
class Customer {

	/**
	 * Contains the email of the customer.
	 *
	 * @var string
	 */
	public $email;

	/**
	 * Contains the phone number of the customer.
	 *
	 * @var string
	 */
	public $phone;

	/**
	 * Contains the default customer key of the customer.
	 *
	 * @var string
	 */
	private $default_customer_key = '16555';

	/**
	 * Contains the default API key.
	 *
	 * @var string
	 */
	private $default_api_key = 'fFd2XcvTGDemZvbw1bcUesNJWEqKbbUq';

	/**
	 * Function that processes the customer details and chooses whether to provide demo request or not. And sends the email to support mail.
	 *
	 * @param string  $email                email of the customer.
	 * @param string  $phone                phone number of the customer.
	 * @param string  $query                query type of the customer.
	 * @param boolean $call_setup           call setup.
	 * @param boolean $demo_request         indicates whether the customer has chosen demo request.
	 * @param string  $integration_selected integration selected by the customer.
	 * @param string  $integration_trial    the trials requested by the customer.
	 * @return boolean
	 */
	public function mo_sf_sync_submit_contact_us( $email, $phone, $query, $call_setup, $demo_request = false, $integration_selected = '', $integration_trial = '' ) {
		$url          = Plugin_Constants::HOSTNAME . '/moas/rest/customer/contact-us';
		$current_user = wp_get_current_user();

		$application_type = $this->mo_sf_sync_get_application_type();
		if ( $call_setup ) {
			$query = '[Call Request - Object Data Sync for Salesforce] ' . $query . '<br><br>Selected Application Type : ' . esc_html( $application_type ) . '<br><br>Site URL : ' . esc_url( home_url() );
		} else {
			if ( true === $demo_request && ( 'integration_trial_request' === $integration_trial || 'normal_trial_request' === $integration_trial ) ) {
				$query = '[Trial Request - Object Data Sync for Salesforce] ' . $query . ' <br><br>Requested Integration : ' . esc_html( $integration_selected ) . ' <br><br>Selected Application Type : ' . esc_html( $application_type ) . '<br><br>Site URL : ' . esc_url( home_url() );

			} elseif ( $demo_request ) {
				$query = '[Demo Request - Object Data Sync for Salesforce] ' . $query . ' <br><br>Requested Integration : ' . esc_html( $integration_selected ) . '  <br><br>Selected Application Type : ' . esc_html( $application_type ) . '<br><br>Site URL : ' . esc_url( home_url() );

			} else {
				$query = '[Object Data Sync for Salesforce] ' . $query . '<br><br>Selected Application Type : ' . esc_html( $application_type ) . '<br><br>Site URL : ' . esc_url( home_url() );
			}
		}

		$fields = array(
			'firstName' => $current_user->user_firstname,
			'lastName'  => $current_user->user_lastname,
			'company'   => isset( $_SERVER ['SERVER_NAME'] ) ? sanitize_text_field( wp_unslash( $_SERVER['SERVER_NAME'] ) ) : '',
			'email'     => $email,
			'ccEmail'   => 'salesforcesupport@xecurify.com',
			'phone'     => $phone,
			'query'     => $query,
		);

		$field_string = wp_json_encode( $fields );

		$headers  = array(
			'Content-Type'  => 'application/json',
			'charset'       => 'UTF-8',
			'Authorization' => 'Basic',
		);
		$args     = array(
			'method'      => 'POST',
			'body'        => $field_string,
			'timeout'     => '20',
			'redirection' => '5',
			'httpversion' => '1.0',
			'blocking'    => true,
			'headers'     => $headers,
		);
		$response = wp_remote_post( $url, $args );
		return ! is_wp_error( $response ) ? $response['body'] : implode( $response->get_error_messages() );
	}

	/**
	 * Function that sends the email alert to the company support mail with the message body.
	 *
	 * @param string  $email                    Email address.
	 * @param string  $phone                    Phone number.
	 * @param string  $message                  Message body to send.
	 * @param boolean $demo_request             Whether it is a Demo request.
	 * @param string  $anonymous_snapshot_json Optional raw JSON for anonymous usage (boxed in email when non-empty).
	 * @param bool    $include_configuration    Whether to append settings JSON (omit when user skipped deactivation feedback).
	 * @return boolean
	 */
	public function mo_sf_sync_send_email_alert( $email, $phone, $message, $demo_request = false, $anonymous_snapshot_json = '', $include_configuration = true ) {

		$url = Plugin_Constants::HOSTNAME . '/moas/api/notify/send';

		$customer_key = $this->default_customer_key;
		$api_key      = $this->default_api_key;

		$current_time_in_millis = self::mo_sf_sync_get_timestamp();
		$current_time_in_millis = number_format( $current_time_in_millis, 0, '', '' );
		$string_to_hash         = $customer_key . $current_time_in_millis . $api_key;
		$hash_value             = hash( 'sha512', $string_to_hash );
		$from_email             = 'no-reply@xecurify.com';
		$subject                = 'Feedback: Object Data Sync for Salesforce';
		if ( $demo_request ) {
			$subject = 'DEMO REQUEST: Object Data Sync for Salesforce';
		}
		$site_url = site_url();

		$mo_sf_sync_current_user = wp_get_current_user();
		$application_type        = $this->mo_sf_sync_get_application_type();

		$mo_sf_sync_email_json_box_style = 'margin:8px 0;padding:10px 12px;border:1px solid #c3c4c7;border-radius:4px;background:#f4f5f6;font-family:Consolas,Monaco,monospace;font-size:12px;line-height:1.4;word-break:break-word;';

		$config_box = '';
		if ( $include_configuration ) {
			$configuration_json = $this->mo_sf_sync_get_configuration_json();
			$config_box         = '<div style="' . esc_attr( $mo_sf_sync_email_json_box_style ) . '">' . esc_html( $configuration_json ) . '</div>';
		}

		$snapshot_section = '';
		if ( is_string( $anonymous_snapshot_json ) && '' !== $anonymous_snapshot_json ) {
			$snapshot_box     = '<div style="' . esc_attr( $mo_sf_sync_email_json_box_style ) . '">' . esc_html( $anonymous_snapshot_json ) . '</div>';
			$snapshot_section = '<br>' . esc_html__( 'Anonymous usage snapshot:', 'object-data-sync-for-salesforce' ) . ' ' . $snapshot_box;
		}

		$query = '[Object Data Sync for Salesforce: ]: ' . nl2br( esc_html( $message ) ) . $snapshot_section . '<br>Selected Application Type : ' . esc_html( $application_type );
		if ( $include_configuration ) {
			$query .= '<br><br>Configurations: ' . $config_box;
		}

		if ( isset( $_SERVER['SERVER_NAME'] ) ) {
			$company_url = esc_url( sanitize_text_field( wp_unslash( $_SERVER['SERVER_NAME'] ) ) );
			$content     = '<div >Hello, <br><br>First Name :' . esc_html( $mo_sf_sync_current_user->user_firstname ) . '<br><br>Last  Name :' . esc_html( $mo_sf_sync_current_user->user_lastname ) . '   <br><br>Company :<a href="' . $company_url . '" target="_blank" >' . $company_url . '</a><br><br>Phone Number :' . esc_html( $phone ) . '<br><br>Email :<a href="mailto:' . esc_attr( $email ) . '" target="_blank">' . esc_html( $email ) . '</a><br><br>Query :' . $query . '</div>';
		}

		$fields       = array(
			'customerKey' => $customer_key,
			'sendEmail'   => true,
			'email'       => array(
				'customerKey' => $customer_key,
				'fromEmail'   => $from_email,
				'fromName'    => 'Xecurify',
				'toEmail'     => 'info@xecurify.com',
				'toName'      => 'salesforcesupport@xecurify.com',
				'bccEmail'    => 'salesforcesupport@xecurify.com',
				'subject'     => $subject,
				'content'     => $content,
			),
		);
		$field_string = wp_json_encode( $fields );

		$headers  = array(
			'Content-Type'  => 'application/json',
			'Customer-Key'  => $customer_key,
			'Timestamp'     => $current_time_in_millis,
			'Authorization' => $hash_value,
		);
		$args     = array(
			'method'      => 'POST',
			'body'        => $field_string,
			'timeout'     => '20',
			'redirection' => '5',
			'httpversion' => '1.0',
			'blocking'    => true,
			'headers'     => $headers,
		);
		$response = wp_remote_post( $url, $args );
		return ! is_wp_error( $response ) ? json_decode( $response['body'], true ) : implode( $response->get_error_messages() );
	}

	/**
	 * Function that returns the time stamp.
	 *
	 * @return boolean
	 */
	public function mo_sf_sync_get_timestamp() {
		$url      = Plugin_Constants::HOSTNAME . '/moas/rest/mobile/get-timestamp';
		$response = wp_remote_post( $url, array() );
		return ! is_wp_error( $response ) ? json_decode( $response['body'], true ) : implode( $response->get_error_messages() );
	}

	/**
	 * Function that returns the selected application type.
	 *
	 * @return string
	 */
	public function mo_sf_sync_get_application_type() {
		$config_object   = get_option( Plugin_Constants::CONFIG_OBJECT );
		$resp_object     = get_option( Plugin_Constants::SF_RESPONSE_OBJECT );
		$connection_type = get_option( Plugin_Constants::CONNECTION_TYPE );
		if ( empty( $resp_object ) && empty( $config_object ) ) {
			$application_type = 'None';
		} elseif ( 'automatic' === $connection_type ) {
			$application_type = 'Pre-connected (Automatic)';
		} else {
			$application_type = 'Manual (Custom)';
		}
		return $application_type;
	}

	/**
	 * Function that retrieves and formats configuration objects as JSON (OAuth client id/secret and tokens omitted).
	 *
	 * @return string
	 */
	public function mo_sf_sync_get_configuration_json() {
		$config_object = get_option( Plugin_Constants::CONFIG_OBJECT );
		$resp_object   = get_option( Plugin_Constants::SF_RESPONSE_OBJECT );

		$config_object = is_array( $config_object ) ? $config_object : array();
		$resp_object   = is_array( $resp_object ) ? $resp_object : array();

		$connection_status = 'not_configured';
		if ( ! empty( $config_object ) && ! empty( $resp_object ) ) {
			$connection_status = 'success';
		}

		$mapping_status = 'not_configured';
		$mapping_data   = null;

		$db_utils     = DB_Utils::instance();
		$mapping_data = $db_utils->mo_sf_sync_get_all_mapping_data();
		if ( ! empty( $mapping_data ) && is_array( $mapping_data ) && isset( $mapping_data['id'] ) ) {
			$mapping_status = 'configured';
		}

		$provision_setting = get_option( Plugin_Constants::PROVISION_OBJECT );

		$mapping_data_nested = 'not_configured';
		if ( ! empty( $mapping_data ) && is_array( $mapping_data ) ) {
			$mapping_data_nested = $mapping_data;
		}

		$mapping_details = array(
			'status'       => $mapping_status,
			'mapping_data' => $mapping_data_nested,
		);

		$connection_settings = array();
		if ( ! empty( $config_object ) ) {
			foreach ( array( 'client_id', 'client_secret' ) as $field ) {
				unset( $config_object[ $field ] );
			}
			$connection_settings = array_merge( $connection_settings, $config_object );
		}

		if ( ! empty( $resp_object ) ) {
			foreach ( array( 'access_token', 'refresh_token' ) as $field ) {
				unset( $resp_object[ $field ] );
			}
			$connection_settings = array_merge( $connection_settings, $resp_object );
		}

		$config_data = array(
			'connection_status'   => $connection_status,
			'mapping_details'     => $mapping_details,
			'provision_setting'   => $provision_setting ? $provision_setting : 'not_configured',
			'connection_settings' => $connection_settings,
		);

		$json_string = wp_json_encode( $config_data );

		return $json_string ? $json_string : '{}';
	}

	/**
	 * Function that performs a check if the customer is logged in or not.
	 *
	 * @param boolean $html_element html element.
	 * @return boolean
	 */
	public static function mo_sf_sync_is_customer_logged_in( $html_element = false ) {
		$email        = get_option( 'mo_sf_sync_admin_email' );
		$customer_key = get_option( 'mo_sf_sync_admin_customer_key' );
		if ( ! $email || ! $customer_key || ! is_numeric( trim( $customer_key ) ) ) {
			return $html_element ? 'disabled' : 0;
		}
		return $html_element ? '' : 1;
	}

	/**
	 * Function that checks for a pattern in the given password.
	 *
	 * @param string $password The password upon which the regex pattern match is checked .
	 * @return int|boolean
	 */
	public static function mo_sf_sync_check_password_pattern( $password ) {
		$pattern = '/^[(\w)*(\!\@\#\$\%\^\&\*\.\-\_)*]+$/';
		return ! preg_match( $pattern, $password );
	}

	/**
	 * Function that deletes the options for removing the customer account as a process of deactivation.
	 *
	 * @return void
	 */
	public static function mo_sf_sync_deactivate() {
		delete_option( 'mo_sf_sync_admin_password' );
		delete_option( 'mo_sf_sync_admin_customer_key' );
		delete_option( 'mo_sf_sync_admin_api_key' );
		delete_option( 'mo_sf_sync_customer_token' );
		delete_option( 'vl_check_t' );
		delete_option( 'vl_check_s' );
	}
}
