<?php
/**
 * User Account View
 *
 * Renders login, registration, license verification, or account details
 * depending on stored state, license status, and optional action query var.
 *
 * @package    MOMCS_Sync
 * @subpackage MOMCS_Sync\views\src\common\pages\account
 */

declare(strict_types=1);

namespace MOMCS_Sync\Views\Src\Common\Pages\Account;

use MOMCS_Sync\Views\Src\Common\Components\Header_View;
use MOMCS_Sync\Includes\Common\Services\User_Service;
use MOMCS_Sync\Includes\Common\Utils\Utils;
use MOMCS_Sync\Includes\Plans\Premium\Handlers\License_Handler;
use MOMCS\LicenseLibrary\Mo_License_Service;

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

/**
 * Class User_Account_View
 *
 * Handles rendering of account-related views including login,
 * registration, license verification, and account details.
 */
class User_Account_View {

	/**
	 * Render the user account view.
	 *
	 * Flow:
	 * 1. If user not logged in -> show login/register form
	 * 2. If user logged in but license not verified -> show license verification form
	 * 3. If user logged in and license verified -> show account details with license info
	 *
	 * @return void
	 */
	public function render(): void {
		$action  = Utils::get_current_page_parameter_value( 'action', '' );
		$service = new User_Service();
		$user    = $service->get_user();

		echo '<div class="wrap momcs-sync-wrap momcs-account-modern">';
		echo '<h1 class="screen-reader-text">' . esc_html__( 'Multi-channel for WooCommerce', 'multi-channel-for-woocommerce' ) . '</h1>';
		( new Header_View( 'account' ) )->render();
		echo '<div class="momcs-sync-content">';

		// Check user login status.
		$is_logged_in = is_array( $user ) && ( $user['logged_in'] ?? false );

		if ( ! $is_logged_in ) {
			// User not logged in - show login/register forms.
			if ( 'login' === $action ) {
				$this->render_login();
			} else {
				$this->render_register();
			}
		} elseif ( Utils::is_premium_plan() ) {
			if ( ! Mo_License_Service::is_customer_license_verified() ) {
				$this->render_license_verification( $user );
			} else {
				$this->render_details( $user, true );
			}
		} else {
			// Free plan: account summary without license library or license UI.
			$this->render_details( $user, false );
		}

		echo '</div></div>';
	}

	/**
	 * Render the user account details.
	 *
	 * @param array $user               User details.
	 * @param bool  $show_license_block When true (premium), show license row, badges, and refresh control.
	 * @return void
	 */
	private function render_details( array $user, bool $show_license_block ): void {
		$license_status = null;
		if ( $show_license_block && class_exists( License_Handler::class ) ) {
			$license_status = License_Handler::get_license_status();
		}

		$expiry_date = is_array( $license_status ) ? (string) ( $license_status['expiry_date'] ?? '' ) : '';
		$is_expired  = is_array( $license_status ) ? (bool) ( $license_status['is_expired'] ?? false ) : false;
		$status_code = is_array( $license_status ) ? (string) ( $license_status['status_code'] ?? '' ) : '';
		$is_trial    = is_array( $license_status ) ? (bool) ( $license_status['is_trial'] ?? false ) : false;

		$change_confirm = $show_license_block
			? __( 'This will log you out and clear your license. You will need to re-login and re-verify your license. Continue?', 'multi-channel-for-woocommerce' )
			: __( 'This will log you out of your miniOrange account on this site. Continue?', 'multi-channel-for-woocommerce' );
		?>
		<div class="momcs-connect-card">
			<?php $this->render_sync_queue_style_notice( $this->consume_notice() ); ?>
			<h2><?php esc_html_e( 'miniOrange Account', 'multi-channel-for-woocommerce' ); ?></h2>

			<table class="form-table momcs-account-table">
				<tbody>
					<tr>
						<th scope="row"><?php esc_html_e( 'Email', 'multi-channel-for-woocommerce' ); ?></th>
						<td><?php echo esc_html( (string) ( $user['email'] ?? '' ) ); ?></td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Customer ID', 'multi-channel-for-woocommerce' ); ?></th>
						<td><?php echo esc_html( (string) ( $user['customer_id'] ?? '' ) ); ?></td>
					</tr>
					<?php if ( $show_license_block ) : ?>
					<tr>
						<th scope="row"><?php esc_html_e( 'License Expiry', 'multi-channel-for-woocommerce' ); ?></th>
						<td>
							<?php echo esc_html( $expiry_date ); ?>
							<?php $this->render_license_status_badge( $is_expired, $status_code, $is_trial ); ?>
						</td>
					</tr>
					<?php endif; ?>
				</tbody>
			</table>

			<div class="momcs-account-actions">
				<?php if ( $show_license_block ) : ?>
					<form method="post">
						<?php wp_nonce_field( 'momcs_refresh_license_nonce' ); ?>
						<input type="hidden" name="option" value="momcs_refresh_license" />
						<button type="submit" class="button button-secondary">
							<span class="dashicons dashicons-update"></span>
							<?php esc_html_e( 'Refresh License', 'multi-channel-for-woocommerce' ); ?>
						</button>
					</form>
				<?php endif; ?>

				<form method="post">
					<?php wp_nonce_field( 'momcs_change_miniorange_account_nonce' ); ?>
					<input type="hidden" name="option" value="momcs_change_miniorange_account" />
					<button type="submit" class="button button-secondary" onclick="return confirm('<?php echo esc_js( $change_confirm ); ?>');">
						<?php esc_html_e( 'Change Account', 'multi-channel-for-woocommerce' ); ?>
					</button>
				</form>
			</div>
		</div>
		<?php
	}

	/**
	 * Render the license status badge.
	 *
	 * @param bool   $is_expired  Whether license is expired.
	 * @param string $status_code Status code from license check.
	 * @param bool   $is_trial    Whether this is a trial license.
	 * @return void
	 */
	private function render_license_status_badge( bool $is_expired, string $status_code, bool $is_trial ): void {
		if ( $is_trial ) {
			echo '<span class="momcs-license-badge momcs-badge-trial">' . esc_html__( 'Trial', 'multi-channel-for-woocommerce' ) . '</span>';
		} elseif ( $is_expired ) {
			echo '<span class="momcs-license-badge momcs-badge-error">' . esc_html__( 'Expired', 'multi-channel-for-woocommerce' ) . '</span>';
		} elseif ( 'LICENSE_IN_GRACE' === $status_code ) {
			echo '<span class="momcs-license-badge momcs-badge-warning">' . esc_html__( 'In Grace Period', 'multi-channel-for-woocommerce' ) . '</span>';
		} else {
			echo '<span class="momcs-license-badge momcs-badge-success">' . esc_html__( 'Valid', 'multi-channel-for-woocommerce' ) . '</span>';
		}
	}

	/**
	 * Render the license verification form.
	 *
	 * Shown when user is logged in but license is not yet verified.
	 *
	 * @param array $user User details.
	 * @return void
	 */
	private function render_license_verification( array $user ): void {
		?>
		<div class="momcs-connect-card">
			<?php $this->render_sync_queue_style_notice( $this->consume_notice() ); ?>
			<h2><?php esc_html_e( 'Verify Your License', 'multi-channel-for-woocommerce' ); ?></h2>
			
			<p class="description">
				<?php esc_html_e( 'Please enter your license key to activate the plugin.', 'multi-channel-for-woocommerce' ); ?>
				<a href="https://portal.miniorange.com/viewlicense" target="_blank" rel="noopener noreferrer">
					<?php esc_html_e( 'View your license key', 'multi-channel-for-woocommerce' ); ?>
				</a>
			</p>

			<div class="momcs-license-info">
				<p>
					<span>
						<strong><?php esc_html_e( 'Logged in as:', 'multi-channel-for-woocommerce' ); ?></strong> 
						<?php echo esc_html( (string) ( $user['email'] ?? '' ) ); ?>
					</span>
					<form method="post" style="display: inline; margin: 0;">
						<?php wp_nonce_field( 'momcs_change_miniorange_account_nonce' ); ?>
						<input type="hidden" name="option" value="momcs_change_miniorange_account" />
						<button type="submit" class="button-link" onclick="return confirm('<?php echo esc_js( __( 'This will log you out and clear your license. You will need to re-login and re-verify your license. Continue?', 'multi-channel-for-woocommerce' ) ); ?>');">
							<?php esc_html_e( '(Change Account)', 'multi-channel-for-woocommerce' ); ?>
						</button>
					</form>
				</p>
			</div>

			<?php $this->render_license_terms_conditions(); ?>

			<form id="momcs_license_form" method="post">
				<?php wp_nonce_field( 'momcs_verify_license_nonce' ); ?>
				<input type="hidden" name="option" value="momcs_verify_license" />

				<p>
					<label for="momcs_license_key" class="momcs-form-label">
						<?php esc_html_e( 'License Key', 'multi-channel-for-woocommerce' ); ?>
					</label>
					<input type="text" 
						   id="momcs_license_key" 
						   name="momcs_license_key" 
						   class="regular-text" 
						   placeholder="<?php esc_attr_e( 'Enter your license key', 'multi-channel-for-woocommerce' ); ?>"
						   required />
				</p>

				<p>
					<label for="momcs_accept_terms_license" class="momcs-form-label" style="display: block; font-weight: normal;">
						<input type="checkbox" id="momcs_accept_terms_license" name="momcs_accept_terms" value="1" required />
						<?php esc_html_e( 'I accept the above Terms and Conditions', 'multi-channel-for-woocommerce' ); ?>
					</label>
				</p>

				<p>
					<button type="submit" class="button button-primary">
						<?php esc_html_e( 'Verify License', 'multi-channel-for-woocommerce' ); ?>
					</button>
				</p>
			</form>
		</div>
		<?php
	}

	/**
	 * Render the license terms and conditions section.
	 *
	 * Displays the terms and conditions that users must accept before verifying their license.
	 *
	 * @return void
	 */
	private function render_license_terms_conditions(): void {
		?>
		<div class="momcs-license-terms">
			<ol class="momcs-license-terms-list">
				<li>
					<?php esc_html_e( 'License key you have entered here is associated with this site instance. In future, if you are re-installing the plugin or your site for any reason, you should deactivate the plugin from the current WordPress domain. It would free your License Key and allow you to activate this plugin on other domains/sites.', 'multi-channel-for-woocommerce' ); ?>
				</li>
				<li>
					<strong><?php esc_html_e( 'This is not a developer\'s license.', 'multi-channel-for-woocommerce' ); ?></strong>
					<?php esc_html_e( 'You may not modify the content or any part thereof, except as explicitly permitted under this plugin. Making any kind of change to the plugin\'s code may make the plugin unusable.', 'multi-channel-for-woocommerce' ); ?>
				</li>
			</ol>
		</div>
		<?php
	}

	/**
	 * Render the login form.
	 *
	 * @return void
	 */
	private function render_login(): void {
		?>
		<div class="momcs-connect-card">
			<?php $this->render_sync_queue_style_notice( $this->consume_notice() ); ?>
			<h2><?php esc_html_e( 'Sign in to miniOrange', 'multi-channel-for-woocommerce' ); ?></h2>
			<form id="momcs_login_form" method="post">
				<?php wp_nonce_field( 'momcs_verify_customer_nonce' ); ?>
				<input type="hidden" name="option" value="momcs_login_form" />

				<p>
					<label for="momcs_user_email" class="momcs-form-label"><?php esc_html_e( 'Email', 'multi-channel-for-woocommerce' ); ?></label>
					<input type="email" id="momcs_user_email" name="momcs_user_email" class="regular-text" required />
				</p>
				<p>
					<label for="momcs_user_password" class="momcs-form-label"><?php esc_html_e( 'Password', 'multi-channel-for-woocommerce' ); ?></label>
					<input type="password" id="momcs_user_password" name="momcs_user_password" class="regular-text" required />
				</p>
				<p>
					<label for="momcs_accept_terms_login" class="momcs-form-label" style="display:block; font-weight: normal;">
						<input type="checkbox" id="momcs_accept_terms_login" name="momcs_accept_terms" value="1" required />
						<?php echo esc_html__( 'I have read and agree to the', 'multi-channel-for-woocommerce' ); ?>
						<a href="<?php echo esc_url( 'https://plugins.miniorange.com/end-user-license-agreement' ); ?>" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'end user agreement', 'multi-channel-for-woocommerce' ); ?></a>
						<?php echo esc_html__( 'and', 'multi-channel-for-woocommerce' ); ?>
						<a href="<?php echo esc_url( 'https://plugins.miniorange.com/wp-content/uploads/2023/08/Plugins-Privacy-Policy.pdf' ); ?>" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'plugin privacy policy', 'multi-channel-for-woocommerce' ); ?></a>.
					</label>
				</p>
				<p>
					<button type="submit" class="button button-primary"><?php esc_html_e( 'Sign In', 'multi-channel-for-woocommerce' ); ?></button>
					<a href="https://portal.miniorange.com/forgotpassword" target="_blank" rel="noopener noreferrer" class="button-link"><?php esc_html_e( 'Forgot Password?', 'multi-channel-for-woocommerce' ); ?></a>
				</p>
			</form>
			<p>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=momcs-sync-account&action=register' ) ); ?>">
					<?php esc_html_e( 'Create a new account', 'multi-channel-for-woocommerce' ); ?>
				</a>
			</p>
		</div>
		<?php
	}

	/**
	 * Render the registration form.
	 *
	 * @return void
	 */
	private function render_register(): void {
		?>
		<div class="momcs-connect-card">
			<?php $this->render_sync_queue_style_notice( $this->consume_notice() ); ?>
			<h2><?php esc_html_e( 'Create your miniOrange Account', 'multi-channel-for-woocommerce' ); ?></h2>
			<form id="momcs_register_form" method="post">
				<?php wp_nonce_field( 'momcs_register_customer_nonce' ); ?>
				<input type="hidden" name="option" value="momcs_register_form" />

				<p>
					<label for="momcs_register_user_email" class="momcs-form-label"><?php esc_html_e( 'Email', 'multi-channel-for-woocommerce' ); ?></label>
					<input type="email" id="momcs_register_user_email" name="momcs_register_user_email" class="regular-text" required />
				</p>
				<p>
					<label for="momcs_register_user_password" class="momcs-form-label"><?php esc_html_e( 'Password', 'multi-channel-for-woocommerce' ); ?></label>
					<input type="password" id="momcs_register_user_password" name="momcs_register_user_password" class="regular-text" required />
				</p>
				<p>
					<label for="momcs_register_user_confirm_password" class="momcs-form-label"><?php esc_html_e( 'Confirm Password', 'multi-channel-for-woocommerce' ); ?></label>
					<input type="password" id="momcs_register_user_confirm_password" name="momcs_register_user_confirm_password" class="regular-text" required />
				</p>
				<p>
					<label for="momcs_accept_terms_register" class="momcs-form-label" style="display:block; font-weight: normal;">
						<input type="checkbox" id="momcs_accept_terms_register" name="momcs_accept_terms" value="1" required />
						<?php echo esc_html__( 'I have read and agree to the', 'multi-channel-for-woocommerce' ); ?>
						<a href="<?php echo esc_url( 'https://plugins.miniorange.com/end-user-license-agreement' ); ?>" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'end user agreement', 'multi-channel-for-woocommerce' ); ?></a>
						<?php echo esc_html__( 'and', 'multi-channel-for-woocommerce' ); ?>
						<a href="<?php echo esc_url( 'https://plugins.miniorange.com/wp-content/uploads/2023/08/Plugins-Privacy-Policy.pdf' ); ?>" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'plugin privacy policy', 'multi-channel-for-woocommerce' ); ?></a>.
					</label>
				</p>
				<p>
					<button type="submit" class="button button-primary"><?php esc_html_e( 'Create Account', 'multi-channel-for-woocommerce' ); ?></button>
				</p>
			</form>
			<p>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=momcs-sync-account&action=login' ) ); ?>">
					<?php esc_html_e( 'Already have an account? Sign in', 'multi-channel-for-woocommerce' ); ?>
				</a>
			</p>
		</div>
		<?php
	}

	/**
	 * Consume transient notice and return it once.
	 *
	 * @return array|null
	 */
	private function consume_notice(): ?array {
		$notice = get_transient( 'momcs_miniorange_notice' );
		if ( is_array( $notice ) && ! empty( $notice['message'] ) ) {
			delete_transient( 'momcs_miniorange_notice' );
			return $notice;
		}
		return null;
	}

	/**
	 * Render a notice styled like Sync Audits info box, above the current card.
	 *
	 * @param array|null $notice Notice to render.
	 * @return void
	 */
	private function render_sync_queue_style_notice( ?array $notice ): void {
		if ( ! is_array( $notice ) || empty( $notice['message'] ) ) {
			return;
		}
		echo '<div class="momcs-orders-notice" style="margin: 0 0 15px 0;"><p><span class="dashicons dashicons-info" style="color:#00a0d2;margin-right:5px;"></span>' . esc_html( (string) $notice['message'] ) . '</p></div>';
	}
}


