<?php
/**
 * User Account Handler
 *
 * Handles POST submissions for miniOrange login, registration,
 * and change-account operations on our plugin admin pages.
 *
 * License-related operations are handled by Premium_Account_Handler
 * which extends this class for premium plan functionality.
 *
 * @package    MOMCS_Sync
 * @subpackage MOMCS_Sync\includes\common\handlers
 */

declare(strict_types=1);

namespace MOMCS_Sync\Includes\Common\Handlers;

use MOMCS_Sync\Includes\Common\Services\User_Service;
use MOMCS_Sync\Includes\Common\Utils\Utils;

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

/**
 * Class User_Account_Handler
 *
 * Handles POST submissions for user account operations.
 * Can be extended by premium handlers for additional functionality.
 */
class User_Account_Handler {

	/**
	 * Transient key for admin notices across redirects.
	 */
	protected const NOTICE_TRANSIENT = 'momcs_miniorange_notice';

	/**
	 * Initialize hooks.
	 *
	 * @return void
	 */
	public function init(): void {
		add_action( 'admin_init', array( $this, 'handle_post' ) );
	}

	/**
	 * Handle POST submissions on our plugin pages only.
	 *
	 * @return void
	 */
	public function handle_post(): void {
		if ( ! empty( $_SERVER['REQUEST_METHOD'] ) && 'POST' !== $_SERVER['REQUEST_METHOD'] ) {
			return;
		}

		// Process only on our plugin pages.
		$page = Utils::get_current_page_parameter_value( 'page', '' );
		if ( false === strpos( $page, 'momcs-sync' ) ) {
			return;
		}

		$service = new User_Service();

		// Change account - clears all user and license data.
		if ( $this->verify_nonce( 'momcs_change_miniorange_account_nonce' ) ) {
			$service->clear_user();
			$this->add_admin_notice( __( 'Account cleared. Please log in again.', 'multi-channel-for-woocommerce' ), 'success' );
			wp_safe_redirect( admin_url( 'admin.php?page=momcs-sync-account&action=login' ) );
			exit;
		}

		// Login.
		if ( $this->verify_nonce( 'momcs_verify_customer_nonce' ) ) {
			// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified in verify_nonce() above.
			$email    = isset( $_POST['momcs_user_email'] ) ? sanitize_email( wp_unslash( $_POST['momcs_user_email'] ) ) : '';
			// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified in verify_nonce() above.
			$password = isset( $_POST['momcs_user_password'] ) ? (string) sanitize_text_field( wp_unslash( $_POST['momcs_user_password'] ) ) : '';
			$result   = $service->verify_and_store_customer( $email, $password );
			if ( is_wp_error( $result ) ) {
				$this->add_admin_notice( $result->get_error_message(), 'error' );
				wp_safe_redirect( admin_url( 'admin.php?page=momcs-sync-account&action=login' ) );
				exit;
			}
			$this->add_admin_notice( __( 'Successfully logged in. Please verify your license to continue.', 'multi-channel-for-woocommerce' ), 'success' );
			wp_safe_redirect( admin_url( 'admin.php?page=momcs-sync-account' ) );
			exit;
		}

		// Registration.
		if ( $this->verify_nonce( 'momcs_register_customer_nonce' ) ) {
			// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified in verify_nonce() above.
			$email    = isset( $_POST['momcs_register_user_email'] ) ? sanitize_email( wp_unslash( $_POST['momcs_register_user_email'] ) ) : '';
			// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified in verify_nonce() above.
			$password = isset( $_POST['momcs_register_user_password'] ) ? (string) sanitize_text_field( wp_unslash( $_POST['momcs_register_user_password'] ) ) : '';
			// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified in verify_nonce() above.
			$confirm  = isset( $_POST['momcs_register_user_confirm_password'] ) ? (string) sanitize_text_field( wp_unslash( $_POST['momcs_register_user_confirm_password'] ) ) : '';
			if ( $password !== $confirm ) {
				$this->add_admin_notice( __( 'The passwords do not match.', 'multi-channel-for-woocommerce' ), 'error' );
				wp_safe_redirect( admin_url( 'admin.php?page=momcs-sync-account&action=register' ) );
				exit;
			}
			$result = $service->create_and_store_customer( $email, $password );
			if ( is_wp_error( $result ) ) {
				$this->add_admin_notice( $result->get_error_message(), 'error' );
				wp_safe_redirect( admin_url( 'admin.php?page=momcs-sync-account&action=register' ) );
				exit;
			}
			if ( is_array( $result ) && ( $result['status'] ?? '' ) === 'SUCCESS' ) {
				// Auto-login after successful signup.
				$login = $service->verify_and_store_customer( $email, $password );
				if ( is_wp_error( $login ) ) {
					$this->add_admin_notice( sprintf( '%s %s', __( 'Account created successfully.', 'multi-channel-for-woocommerce' ), __( 'Please sign in to continue.', 'multi-channel-for-woocommerce' ) ), 'success' );
					wp_safe_redirect( admin_url( 'admin.php?page=momcs-sync-account&action=login' ) );
					exit;
				}
				$this->add_admin_notice( __( 'Account created and logged in successfully. Please verify your license.', 'multi-channel-for-woocommerce' ), 'success' );
				wp_safe_redirect( admin_url( 'admin.php?page=momcs-sync-account' ) );
				exit;
			}
			$msg = is_array( $result ) ? ( $result['message'] ?? __( 'Registration failed.', 'multi-channel-for-woocommerce' ) ) : __( 'Registration failed.', 'multi-channel-for-woocommerce' );
			$this->add_admin_notice( $msg, 'error' );
			wp_safe_redirect( admin_url( 'admin.php?page=momcs-sync-account&action=register' ) );
			exit;
		}
	}

	/**
	 * Verify nonce for a given action.
	 *
	 * @param string $action Nonce action name.
	 * @return bool True if valid, false otherwise.
	 */
	protected function verify_nonce( string $action ): bool {
		return isset( $_POST['_wpnonce'] )
			&& current_user_can( 'manage_options' )
			&& wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ), $action );
	}

	/**
	 * Persist a notice across redirects and render later in the view.
	 *
	 * @param string $message Message text.
	 * @param string $type    success|error|warning|info.
	 * @return void
	 */
	protected function add_admin_notice( string $message, string $type = 'success' ): void {
		set_transient(
			self::NOTICE_TRANSIENT,
			array(
				'message' => $message,
				'type'    => $type,
			),
			60
		);
	}
}
