<?php
/**
 * REST API for Cart Tracking.
 *
 * @package automation-web-platform
 */

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

/**
 * Class WAWP_Rest_Cart_API.
 */
class WAWP_Rest_Cart_API {
	use WAWP_Abandoned_Cart_Helper_Trait;
	use WAWP_Security_Trait;
	use WAWP_Phone_Helper_Trait;
	use WAWP_Settings_Handler;

	/**
	 * Namespace.
	 *
	 * @var string
	 */
	private $namespace = 'wawp/v1';

	/**
	 * Base route.
	 *
	 * @var string
	 */
	private $base = 'cart';

	/**
	 * Constructor.
	 */
	public function __construct() {
		if ( did_action( 'rest_api_init' ) ) {
			$this->register_routes();
		} else {
			add_action( 'rest_api_init', array( $this, 'register_routes' ) );
		}
	}

	/**
	 * Register routes.
	 */
	public function register_routes() {
		register_rest_route(
			$this->namespace,
			'/' . $this->base . '/track-page',
			array(
				'methods'             => WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'track_page' ),
				'permission_callback' => '__return_true',
			)
		);

		register_rest_route(
			$this->namespace,
			'/' . $this->base . '/update-status',
			array(
				'methods'             => WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'update_status' ),
				'permission_callback' => '__return_true',
			)
		);

		register_rest_route(
			$this->namespace,
			'/' . $this->base . '/capture-fields',
			array(
				'methods'             => WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'capture_fields' ),
				'permission_callback' => '__return_true',
			)
		);

		register_rest_route(
			$this->namespace,
			'/' . $this->base . '/send-otp',
			array(
				'methods'             => WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'send_otp' ),
				'permission_callback' => '__return_true',
			)
		);

		register_rest_route(
			$this->namespace,
			'/' . $this->base . '/verify-otp',
			array(
				'methods'             => WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'verify_otp' ),
				'permission_callback' => '__return_true',
			)
		);
	}



	/**
	 * Track page.
	 *
	 * @param WP_REST_Request $request Request.
	 * @return WP_REST_Response|WP_Error
	 */
	public function track_page( $request ) {
		$session_id = $this->get_cart_session_id();
		if ( ! $session_id ) {
			return new WP_Error( 'no_session', 'No active session', array( 'status' => 400 ) );
		}

		if ( WAWP()->abandoned_carts ) {
			$page_url    = $request->get_param( 'page_url' );
			$page_title  = $request->get_param( 'page_title' );
			$screen_size = $request->get_param( 'screen_size' );

			// Extracting history event logic.
			WAWP()->abandoned_carts->insert_or_update(
				$session_id,
				get_current_user_id(),
				'',
				'',
				'',
				0.0,
				'',
				'',
				'',
				'',
				'',
				null,
				$screen_size
			);
			WAWP()->abandoned_carts->add_history_event(
				'page',
				array(
					'url'   => $page_url,
					'title' => $page_title,
				)
			);
		}

		return rest_ensure_response( array( 'success' => true ) );
	}

	/**
	 * Update status.
	 *
	 * @param WP_REST_Request $request Request.
	 * @return WP_REST_Response|WP_Error
	 */
	public function update_status( $request ) {
		$status     = $request->get_param( 'status' );
		$session_id = $this->get_cart_session_id();
		if ( ! $session_id ) {
			return new WP_Error( 'no_session', 'No active session', array( 'status' => 400 ) );
		}

		if ( WAWP()->abandoned_carts ) {
			WAWP()->abandoned_carts->update_cart_status_logic( $session_id, $status );
		}

		return rest_ensure_response( array( 'success' => true ) );
	}

	/**
	 * Capture fields.
	 *
	 * @param WP_REST_Request $request Request.
	 * @return WP_REST_Response|WP_Error
	 */
	public function capture_fields( $request ) {
		$params     = $request->get_params();
		$session_id = $this->get_cart_session_id();
		if ( ! $session_id ) {
			return new WP_Error( 'no_session', 'No active session', array( 'status' => 400 ) );
		}

		$res = array();
		if ( WAWP()->abandoned_carts ) {
			$res = WAWP()->abandoned_carts->capture_billing_logic( $session_id, $params );
		}

		return rest_ensure_response(
			array(
				'success' => true,
				'data'    => array(
					'status'  => 'captured',
					'billing' => $res,
				),
			)
		);
	}

	/**
	 * Send OTP challenge.
	 *
	 * @param WP_REST_Request $request Request.
	 * @return WP_REST_Response|WP_Error
	 */
	public function send_otp( $request ) {
		$phone = sanitize_text_field( $request->get_param( 'phone' ) );
		if ( empty( $phone ) ) {
			return new WP_Error( 'invalid_phone', esc_html__( 'Phone number is required.', 'automation-web-platform' ), array( 'status' => 400 ) );
		}

		$session_id = $this->get_cart_session_id();
		if ( ! $session_id ) {
			return new WP_Error( 'no_session', esc_html__( 'No active session', 'automation-web-platform' ), array( 'status' => 400 ) );
		}

		$method = $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_VERIFICATION_METHOD, 'none' );
		if ( 'none' === $method ) {
			return rest_ensure_response(
				array(
					'success' => true,
					'message' => esc_html__( 'No verification required.', 'automation-web-platform' ),
				)
			);
		}

		$settings = array(
			'whatsapp_auth_type'          => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_WA_AUTH_TYPE, 'otp' ),
			'whatsapp_otp_lang_type'      => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_WA_OTP_LANG_TYPE, 'site' ),
			'whatsapp_otp_custom_lang'    => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_WA_OTP_CUSTOM_LANG, '' ),
			'whatsapp_otp_footer_enabled' => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_WA_OTP_FOOT_EN, 0 ),
			'whatsapp_otp_footer'         => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_WA_OTP_FOOT, '' ),
			'whatsapp_list_title'         => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_WA_LIST_TITLE, 'Secure Authentication' ),
			'whatsapp_list_desc'          => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_WA_LIST_DESC, 'Verify your identity to continue' ),
			'whatsapp_list_footer'        => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_WA_LIST_FOOTER, 'Authorized by Wawp Engine' ),
			'whatsapp_list_button'        => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_WA_LIST_BUTTON, 'Choose Action' ),
			'whatsapp_list_item1'         => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_WA_LIST_ITEM1, 'Approve Request' ),
			'whatsapp_list_item1_desc'    => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_WA_LIST_ITEM1_DESC, 'This is my login attempt' ),
			'whatsapp_list_item2'         => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_WA_LIST_ITEM2, 'Reject & Report' ),
			'whatsapp_list_item2_desc'    => $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_WA_LIST_ITEM2_DESC, 'I don\'t recognize this' ),
		);

		$challenge = WAWP_OTP_Service::get_instance()->send_challenge(
			$phone,
			array(
				'method'   => $method,
				'context'  => 'Cart Recovery',
				'settings' => $settings,
			)
		);

		if ( ! empty( $challenge['success'] ) ) {
			return rest_ensure_response(
				array(
					'success'       => true,
					'message'       => $challenge['message'] ?? '',
					'transient_key' => $challenge['transient_key'] ?? '',
					'auth_type'     => $challenge['whatsapp_auth_type'] ?? ( 'firebase' === $method ? 'firebase' : 'otp' ),
				)
			);
		} else {
			return new WP_Error( 'send_failed', $challenge['message'] ?? esc_html__( 'Failed to send challenge.', 'automation-web-platform' ), array( 'status' => 500 ) );
		}
	}

	/**
	 * Verify OTP challenge.
	 *
	 * @param WP_REST_Request $request Request.
	 * @return WP_REST_Response|WP_Error
	 */
	public function verify_otp( $request ) {
		$transient_key = sanitize_text_field( $request->get_param( 'transient_key' ) );
		$entered_code  = sanitize_text_field( $request->get_param( 'code' ) );
		$id_token      = sanitize_text_field( $request->get_param( 'idToken' ) ); // Firebase.
		$billing_phone = sanitize_text_field( $request->get_param( 'billing_phone' ) );
		$billing_email = sanitize_text_field( $request->get_param( 'billing_email' ) );

		$session_id = $this->get_cart_session_id();
		if ( ! $session_id ) {
			return new WP_Error( 'no_session', esc_html__( 'No active session', 'automation-web-platform' ), array( 'status' => 400 ) );
		}

		$method = $this->get_wawp_setting( WAWP_Settings_Registry::AC_POPUP_VERIFICATION_METHOD, 'none' );
		if ( 'none' === $method ) {
			return new WP_Error( 'not_required', esc_html__( 'Verification not enabled.', 'automation-web-platform' ), array( 'status' => 400 ) );
		}

		$verified       = false;
		$verified_phone = '';
		$message        = '';

		if ( 'firebase' === $method ) {
			if ( empty( $id_token ) ) {
				return new WP_Error( 'missing_token', esc_html__( 'Firebase ID Token is required.', 'automation-web-platform' ), array( 'status' => 400 ) );
			}
			$verify_res = WAWP_OTP_Service::get_instance()->verify_firebase_token( $id_token );
			if ( ! empty( $verify_res['success'] ) ) {
				$verified       = true;
				$verified_phone = $verify_res['phone'];
			} else {
				$message = $verify_res['message'] ?? esc_html__( 'Firebase token verification failed.', 'automation-web-platform' );
			}
		} else {
			if ( empty( $transient_key ) ) {
				return new WP_Error( 'missing_key', esc_html__( 'Transient key is required.', 'automation-web-platform' ), array( 'status' => 400 ) );
			}

			// If it's empty code, this might be polling for WhatsApp interactive list approval status.
			if ( empty( $entered_code ) ) {
				$status_res = WAWP_OTP_Service::get_instance()->check_challenge_status( $transient_key );
				if ( ! empty( $status_res['success'] ) && ! empty( $status_res['verified'] ) ) {
					$verified       = true;
					$verified_phone = $status_res['data']['recipient'] ?? '';
				} else {
					return rest_ensure_response(
						array(
							'success'  => false,
							'verified' => false,
							'status'   => $status_res['status'] ?? 'pending',
							'message'  => $status_res['message'] ?? esc_html__( 'Verification pending...', 'automation-web-platform' ),
						)
					);
				}
			} else {
				// Regular OTP code verification.
				$verify_res = WAWP_OTP_Service::get_instance()->verify_challenge( $entered_code, $transient_key );
				if ( ! empty( $verify_res['success'] ) ) {
					$verified       = true;
					$verified_phone = $verify_res['data']['recipient'] ?? '';
				} else {
					$message = $verify_res['message'] ?? esc_html__( 'Incorrect verification code.', 'automation-web-platform' );
				}
			}
		}

		if ( $verified ) {
			// Normalization: clean the digits in phone number.
			$clean_phone = $this->get_digits_only( ! empty( $verified_phone ) ? $verified_phone : $billing_phone );

			// Capture the billing details in database.
			$params = array(
				'billing_phone' => $clean_phone,
			);
			if ( ! empty( $billing_email ) ) {
				$params['billing_email'] = sanitize_email( $billing_email );
			}

			$res = array();
			if ( WAWP()->abandoned_carts ) {
				$res = WAWP()->abandoned_carts->capture_billing_logic( $session_id, $params );
			}

			return rest_ensure_response(
				array(
					'success' => true,
					'message' => esc_html__( 'Phone verified and cart captured successfully!', 'automation-web-platform' ),
					'data'    => array(
						'status'  => 'captured',
						'billing' => $res,
					),
				)
			);
		} else {
			return new WP_Error( 'verify_failed', $message, array( 'status' => 400 ) );
		}
	}
}
