<?php
/**
 * User Handler
 *
 * @category   WordPress_Plugin
 * @package    Standard
 * @subpackage Handlers\Rest_API
 * @author     miniOrange <info@miniorange.com>
 * @license    MIT/Expat
 * @link       https://plugins.miniorange.com/woocommerce-api-product-sync-with-woocommerce-rest-apis
 */

namespace MOWCPS\Standard\Handlers\Rest_API;

use Error;
use WP_Error;
use MOWCPS\Common\Utils\Utils;
use MOWCPS\Common\Constants\Constants;
use MOWCPS\Common\Utils\Model_Utils;
use MOWCPS\Common\Handlers\Rest_API\User_Handler as Common_User_Handler;
use MOWCPS\Standard\Handlers\Feedback\Feedback_Handler;

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

/**
 * Class User_Handler.
 *
 * Handles user REST API operations for standard plan
 * Extends common handler to inherit login and contact_us functionality
 */
class User_Handler extends Common_User_Handler {

	/**
	 * Register user
	 *
	 * @param string $email Email.
	 * @param string $password Password.
	 * @param string $confirm_password Confirm password.
	 * @param string $phone    Phone number.
	 * @return array|WP_Error
	 */
	public function register_user( $email, $password, $confirm_password, $phone ) {
		$customer_response = $this->check_customer( $email );

		if ( is_wp_error( $customer_response ) ) {
			return $customer_response;
		}

		$customer_response = json_decode( $customer_response['body'], true );

		if ( 'CUSTOMER_NOT_FOUND' === $customer_response['status'] ) {
			if ( false !== strpos( $customer_response['message'], 'The customer is not valid' ) ) {
				return new WP_Error( 'customer_not_valid', 'Please use a valid email address.', array( 'status' => Constants::HTTP_BAD_REQUEST ) );
			}
			return $this->create_customer( $email, $password, $phone );
		} elseif ( strcasecmp( $customer_response['status'], 'SUCCESS' ) === 0 ) {
			return new WP_Error( 'customer_exists', 'Customer already exists.', array( 'status' => Constants::HTTP_BAD_REQUEST ) );
		} elseif ( is_null( $customer_response ) ) {
			return new WP_Error( 'customer_not_found', 'Failed to create customer. Try again.', array( 'status' => Constants::HTTP_BAD_REQUEST ) );
		} else {
			return new WP_Error( 'customer_not_found', $customer_response['message'], array( 'status' => Constants::HTTP_BAD_REQUEST ) );
		}
	}

	/**
	 * Check customer
	 *
	 * @param string $email Email.
	 * @return array|WP_Error
	 */
	public function check_customer( $email ) {
		$request_parameters = Utils::generate_request_parameters();

		$api_request = array(
			'endpoint' => Constants::MOWCPS_HOST_NAME . '/moas/rest/customer/check-if-exists',
			'method'   => Constants::HTTP_REQUEST_METHOD_POST,
			'headers'  => $request_parameters['headers'],
			'body'     => wp_json_encode(
				array(
					'email' => $email,
				)
			),
		);

		return $this->api_service::make_api_call( $api_request['endpoint'], $api_request );
	}

	/**
	 * Create customer
	 *
	 * @param string $email Email.
	 * @param string $password Password.
	 * @param string $phone    Phone number.
	 * @return array|WP_Error
	 */
	public function create_customer( $email, $password, $phone ) {
		$request_parameters = Utils::generate_request_parameters();

		$api_request = array(
			'endpoint' => Constants::MOWCPS_HOST_NAME . '/moas/rest/customer/add',
			'method'   => Constants::HTTP_REQUEST_METHOD_POST,
			'headers'  => $request_parameters['headers'],
			'body'     => array(
				'companyName'    => '',
				'areaOfInterest' => 'Product Sync for WooCommerce',
				'firstname'      => '',
				'lastname'       => '',
				'email'          => $email,
				'phone'          => $phone,
				'password'       => $password,
			),
		);

		return $this->api_service::make_api_call( $api_request['endpoint'], $api_request );
	}

	/**
	 * Submit feedback
	 *
	 * @param array $form_data Form data array.
	 * @return array|WP_Error
	 */
	public function submit_feedback( $form_data ) {
		$reason          = $form_data['reason'] ?? '';
		$request_contact = $form_data['request_contact'] ?? false;
		$user_config     = $form_data['user_config'] ?? array();
		$user_email      = ! empty( $form_data['user_email'] ) ? $form_data['user_email'] : get_bloginfo( 'admin_email' );

		$server_config = Feedback_Handler::collect_detailed_user_config();

		$plugin_version = Utils::get_version_number();
		// Prepare email subject.
		if ( 'contact_query' === $reason ) {
			$email_subject = '[Products Sync for WooCommerce : ' . $plugin_version . '] Contact Query';
		} elseif ( 'expert_contact' === $reason ) {
			$email_subject = '[Products Sync for WooCommerce : ' . $plugin_version . '] Contact Expert';
		} else {
			$email_subject = '[Products Sync for WooCommerce : ' . $plugin_version . '] ' . ucfirst( str_replace( array( '[', ']' ), '', $reason ) );
		}

		$detailed_query = Feedback_Handler::prepare_query( $form_data, array_merge( $user_config, $server_config ) );

		// Use inherited contact_us method directly.
		$result = $this->contact_us( $user_email, '', $detailed_query, '', $email_subject );

		// Deactivate plugin if feedback is submitted successfully.
		if ( ! is_wp_error( $result ) && 'contact_query' !== $reason && ( 0 !== stripos( $reason, 'expert_contact' ) && 0 !== stripos( $reason, 'Contact Expert' ) ) ) {
			deactivate_plugins( 'products-sync-for-woocommerce/products-sync-for-woocommerce.php' );
		}
		return $detailed_query;
	}

	/**
	 * Delete user details
	 *
	 * @return void
	 */
	public static function delete_user_details() {
		Model_Utils::delete_option( 'mowcps_user_display_details' );
		Model_Utils::delete_option( 'mowcps_user_details' );
	}
}
