<?php
/**
 * Blocksy 登录/注册弹窗自定义样式
 * 
 * 提供对 Blocksy 主题账户弹窗的自定义样式功能
 */

namespace Tooto_Elementor;

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

class Blocksy_Account_Modal {
	/**
	 * @var Blocksy_Account_Modal|null
	 */
	private static $instance = null;

	/**
	 * 获取单例实例
	 *
	 * @return Blocksy_Account_Modal
	 */
	public static function instance(): self {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	private function __construct() {
		$this->init();
	}

	/**
	 * 初始化功能
	 */
	private function init(): void {
		// 注册样式和脚本
		add_action( 'wp_enqueue_scripts', [ $this, 'enqueue_assets' ], 999 );
		
		// 添加内联样式
		add_action( 'wp_head', [ $this, 'add_inline_styles' ], 999 );

		// 添加注册表单字段
		add_action( 'woocommerce_register_form', [ $this, 'add_registration_fields' ], 10 );
		add_action( 'blocksy:account:modal:register:start', [ $this, 'add_registration_fields' ], 10 );
		
		// 确保表单支持文件上传
		add_action( 'wp_footer', [ $this, 'add_form_enctype' ], 999 );
		
		// 添加错误弹窗 HTML
		add_action( 'wp_footer', [ $this, 'add_error_dialog_html' ], 999 );

		// 验证注册表单字段
		add_action( 'woocommerce_register_post', [ $this, 'validate_registration_fields' ], 10, 3 );
		add_filter( 'woocommerce_registration_errors', [ $this, 'validate_registration_fields_filter' ], 10, 3 );

		// 保存注册表单数据
		add_action( 'woocommerce_created_customer', [ $this, 'save_registration_fields' ], 10, 3 );
		add_action( 'user_register', [ $this, 'save_registration_fields_standard' ], 10, 1 );

		// 处理文件上传
		add_action( 'wp_ajax_tooto_upload_registration_file', [ $this, 'handle_file_upload' ] );
		add_action( 'wp_ajax_nopriv_tooto_upload_registration_file', [ $this, 'handle_file_upload' ] );
	}

	/**
	 * 注册和加载资源文件
	 */
	public function enqueue_assets(): void {
		// 加载 Google 字体 Bebas Neue
		wp_enqueue_style(
			'tooto-google-fonts-bebas-neue',
			'https://fonts.googleapis.com/css2?family=Bebas+Neue&display=swap',
			[],
			null
		);

		// 注册样式（依赖 Google 字体）
		wp_register_style(
			'tooto-blocksy-account-modal',
			TOOTO_EA_URL . 'assets/css/tooto-blocksy-account-modal.css',
			[ 'tooto-google-fonts-bebas-neue' ],
			TOOTO_EA_VERSION
		);

		// 注册脚本
		wp_register_script(
			'tooto-blocksy-account-modal',
			TOOTO_EA_URL . 'assets/js/tooto-blocksy-account-modal.js',
			[ 'jquery' ],
			TOOTO_EA_VERSION,
			true
		);

		// 加载样式和脚本
		wp_enqueue_style( 'tooto-blocksy-account-modal' );
		wp_enqueue_script( 'tooto-blocksy-account-modal' );

		// 传递 AJAX URL 和 nonce
		wp_localize_script( 'tooto-blocksy-account-modal', 'tootoAccountModal', [
			'ajaxUrl' => admin_url( 'admin-ajax.php' ),
			'nonce' => wp_create_nonce( 'tooto-register-nonce' ),
		] );
	}

	/**
	 * 添加内联样式
	 */
	public function add_inline_styles(): void {
		?>
		<style type="text/css" id="tooto-blocksy-account-modal-custom-styles">
		/* Blocksy 账户弹窗自定义样式 */
		/* 可以在这里添加需要高优先级的样式 */
		</style>
		<?php
	}

	/**
	 * 确保注册表单支持文件上传
	 */
	public function add_form_enctype(): void {
		?>
		<script type="text/javascript">
		(function($) {
			$(document).ready(function() {
				// 确保注册表单支持文件上传
				var $registerForm = $('#account-modal #registerform');
				if ($registerForm.length && !$registerForm.attr('enctype')) {
					$registerForm.attr('enctype', 'multipart/form-data');
				}
			});
		})(jQuery);
		</script>
		<?php
	}

	/**
	 * 添加注册表单字段
	 */
	public function add_registration_fields(): void {
		// 商店类型选项
		$store_type_options = [
			'' => __( 'Select Store Type', 'tooto-elementor' ),
			'retail' => __( 'Retail Store', 'tooto-elementor' ),
			'wholesale' => __( 'Wholesale', 'tooto-elementor' ),
			'online' => __( 'Online Store', 'tooto-elementor' ),
			'distributor' => __( 'Distributor', 'tooto-elementor' ),
			'other' => __( 'Other', 'tooto-elementor' ),
		];

		// 获取已提交的值（用于错误后回显）
		$store_name = isset( $_POST['tooto_store_name'] ) ? \sanitize_text_field( \wp_unslash( $_POST['tooto_store_name'] ) ) : '';
		$store_type = isset( $_POST['tooto_store_type'] ) ? \sanitize_text_field( \wp_unslash( $_POST['tooto_store_type'] ) ) : '';
		$store_address = isset( $_POST['tooto_store_address'] ) ? \sanitize_textarea_field( \wp_unslash( $_POST['tooto_store_address'] ) ) : '';
		$tax_number = isset( $_POST['tooto_tax_number'] ) ? \sanitize_text_field( \wp_unslash( $_POST['tooto_tax_number'] ) ) : '';
		$monthly_purchase = isset( $_POST['tooto_monthly_purchase_amount'] ) ? \sanitize_text_field( \wp_unslash( $_POST['tooto_monthly_purchase_amount'] ) ) : '';
		?>
		<p>
			<label for="tooto_store_name"><?php echo esc_html__( 'Store name / Company name', 'tooto-elementor' ); ?></label>
			<input type="text" name="tooto_store_name" id="tooto_store_name" class="input" value="<?php echo esc_attr( $store_name ); ?>" size="20" autocomplete="organization">
		</p>

		<p>
			<label for="tooto_store_type"><?php echo esc_html__( 'Store type', 'tooto-elementor' ); ?></label>
			<select name="tooto_store_type" id="tooto_store_type" class="tooto-select-hidden" style="display: none;">
				<?php foreach ( $store_type_options as $value => $label ) : ?>
					<option value="<?php echo esc_attr( $value ); ?>" <?php selected( $store_type, $value ); ?>>
						<?php echo esc_html( $label ); ?>
					</option>
				<?php endforeach; ?>
			</select>
			<div class="tooto-custom-select" data-target="tooto_store_type">
				<div class="tooto-custom-select-trigger">
					<span class="tooto-custom-select-value">
						<?php
						$selected_label = $store_type && isset( $store_type_options[ $store_type ] ) 
							? $store_type_options[ $store_type ] 
							: $store_type_options[''];
						echo esc_html( $selected_label );
						?>
					</span>
					<svg class="tooto-custom-select-arrow" width="12" height="8" viewBox="0 0 12 8" fill="none" xmlns="http://www.w3.org/2000/svg">
						<path d="M1 1L6 6L11 1" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
					</svg>
				</div>
				<ul class="tooto-custom-select-options">
					<?php foreach ( $store_type_options as $value => $label ) : ?>
						<li class="tooto-custom-select-option <?php echo ( $store_type === $value ) ? 'selected' : ''; ?>" data-value="<?php echo esc_attr( $value ); ?>">
							<?php echo esc_html( $label ); ?>
						</li>
					<?php endforeach; ?>
				</ul>
			</div>
		</p>

		<p>
			<label for="tooto_store_address"><?php echo esc_html__( 'Store address / Website', 'tooto-elementor' ); ?></label>
			<input type="text" name="tooto_store_address" id="tooto_store_address" class="input" value="<?php echo esc_attr( $store_address ); ?>" size="20" autocomplete="street-address">
		</p>

		<p>
			<label for="tooto_tax_number"><?php echo esc_html__( 'Tax number', 'tooto-elementor' ); ?></label>
			<input type="text" name="tooto_tax_number" id="tooto_tax_number" class="input" value="<?php echo esc_attr( $tax_number ); ?>" size="20" autocomplete="off">
		</p>

		<p>
			<label for="tooto_monthly_purchase_amount"><?php echo esc_html__( 'Estimated Monthly Purchase Amount', 'tooto-elementor' ); ?></label>
			<input type="text" name="tooto_monthly_purchase_amount" id="tooto_monthly_purchase_amount" class="input" value="<?php echo esc_attr( $monthly_purchase ); ?>" size="20" autocomplete="off">
		</p>

		<p>
			<label for="tooto_application_form"><?php echo esc_html__( 'Application Form', 'tooto-elementor' ); ?></label>
			<div class="tooto-file-upload-wrapper">
				<input type="file" name="tooto_application_form" id="tooto_application_form" class="tooto-file-input" accept=".pdf,.doc,.docx,.jpg,.jpeg,.png" style="display: none;">
				<button type="button" class="tooto-upload-button" data-target="tooto_application_form">
					<?php echo esc_html__( 'Upload', 'tooto-elementor' ); ?>
				</button>
				<span class="tooto-file-name" data-target="tooto_application_form"></span>
				<?php
				$example_url = get_option( 'tooto_application_form_example_url' );
				if ( ! empty( $example_url ) ) : ?>
					<a href="<?php echo esc_url( $example_url ); ?>" class="tooto-download-example" target="_blank"><?php echo esc_html__( 'Download Example', 'tooto-elementor' ); ?></a>
				<?php endif; ?>
			</div>
		</p>

		<p>
			<label for="tooto_reseller_certificate"><?php echo esc_html__( 'Reseller Certificate', 'tooto-elementor' ); ?></label>
			<div class="tooto-file-upload-wrapper">
				<input type="file" name="tooto_reseller_certificate" id="tooto_reseller_certificate" class="tooto-file-input" accept=".pdf,.doc,.docx,.jpg,.jpeg,.png" style="display: none;">
				<button type="button" class="tooto-upload-button" data-target="tooto_reseller_certificate">
					<?php echo esc_html__( 'Upload', 'tooto-elementor' ); ?>
				</button>
				<span class="tooto-file-name" data-target="tooto_reseller_certificate"></span>
			</div>
		</p>
		<?php
	}

	/**
	 * 验证注册表单字段（WooCommerce 钩子）
	 *
	 * @param string $username 用户名
	 * @param string $email 邮箱
	 * @param \WP_Error $errors 错误对象
	 */
	public function validate_registration_fields( string $username, string $email, \WP_Error $errors ): void {
		// Store name 是必填项
		if ( empty( $_POST['tooto_store_name'] ) ) {
			$errors->add( 'tooto_store_name_error', __( 'Store name / Company name is required.', 'tooto-elementor' ) );
		}
	}

	/**
	 * 验证注册表单字段（过滤器）
	 *
	 * @param \WP_Error $errors 错误对象
	 * @param string $username 用户名
	 * @param string $email 邮箱
	 * @return \WP_Error
	 */
	public function validate_registration_fields_filter( \WP_Error $errors, string $username, string $email ): \WP_Error {
		// Store name 是必填项
		if ( empty( $_POST['tooto_store_name'] ) ) {
			$errors->add( 'tooto_store_name_error', __( 'Store name / Company name is required.', 'tooto-elementor' ) );
		}

		return $errors;
	}

	/**
	 * 输出错误弹窗 HTML 结构
	 */
	public function add_error_dialog_html(): void {
		?>
		<div id="tooto-error-dialog" class="tooto-error-dialog ct-overlay-skip" style="display: none;" data-ignore-overlay-click="true">
			<div class="tooto-error-dialog-overlay"></div>
			<div class="tooto-error-dialog-content">
				<button type="button" class="tooto-error-dialog-close" aria-label="<?php echo esc_attr__( 'Close', 'tooto-elementor' ); ?>">
					<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
						<path d="M12 4L4 12M4 4L12 12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
					</svg>
				</button>
				<div class="tooto-error-dialog-header">
					<h3 class="tooto-error-dialog-title"><?php echo esc_html__( 'Error', 'tooto-elementor' ); ?></h3>
				</div>
				<div class="tooto-error-dialog-body">
					<div class="tooto-error-dialog-message"></div>
				</div>
				<div class="tooto-error-dialog-footer">
					<button type="button" class="tooto-error-dialog-button"><?php echo esc_html__( 'OK', 'tooto-elementor' ); ?></button>
				</div>
			</div>
		</div>
		<?php
	}

	/**
	 * 保存注册表单数据（WooCommerce 钩子）
	 *
	 * @param int $customer_id 客户 ID
	 * @param array $new_customer_data 新客户数据
	 * @param string $password_generated 是否生成密码
	 */
	public function save_registration_fields( int $customer_id, array $new_customer_data, string $password_generated ): void {
		$this->save_registration_data( $customer_id );
	}

	/**
	 * 保存注册表单数据（标准 WordPress 钩子）
	 *
	 * @param int $user_id 用户 ID
	 */
	public function save_registration_fields_standard( int $user_id ): void {
		// 只在非 WooCommerce 注册时调用
		if ( ! did_action( 'woocommerce_created_customer' ) ) {
			$this->save_registration_data( $user_id );
		}
	}

	/**
	 * 保存注册数据
	 *
	 * @param int $user_id 用户 ID
	 */
	private function save_registration_data( int $user_id ): void {
		// 保存文本字段
		$fields = [
			'tooto_store_name' => \sanitize_text_field( $_POST['tooto_store_name'] ?? '' ),
			'tooto_store_address' => \sanitize_textarea_field( $_POST['tooto_store_address'] ?? '' ),
			'tooto_tax_number' => \sanitize_text_field( $_POST['tooto_tax_number'] ?? '' ),
			'tooto_store_type' => \sanitize_text_field( $_POST['tooto_store_type'] ?? '' ),
			'tooto_store_website' => \esc_url_raw( $_POST['tooto_store_address'] ?? '' ), // Store address 可能包含网站
			'tooto_monthly_purchase_amount' => \sanitize_text_field( $_POST['tooto_monthly_purchase_amount'] ?? '' ),
		];

		foreach ( $fields as $key => $value ) {
			if ( ! empty( $value ) ) {
				\update_user_meta( $user_id, $key, $value );
			}
		}

		// 处理文件上传
		$this->handle_registration_file_uploads( $user_id );
	}

	/**
	 * 处理注册时的文件上传
	 *
	 * @param int $user_id 用户 ID
	 */
	private function handle_registration_file_uploads( int $user_id ): void {
		// 处理 Application Form
		if ( ! empty( $_FILES['tooto_application_form']['name'] ) ) {
			$file_id = $this->upload_file( $_FILES['tooto_application_form'] );
			if ( $file_id ) {
				\update_user_meta( $user_id, 'tooto_application_form', $file_id );
			}
		}

		// 处理 Reseller Certificate
		if ( ! empty( $_FILES['tooto_reseller_certificate']['name'] ) ) {
			$file_id = $this->upload_file( $_FILES['tooto_reseller_certificate'] );
			if ( $file_id ) {
				\update_user_meta( $user_id, 'tooto_reseller_certificate', $file_id );
			}
		}
	}

	/**
	 * 上传文件
	 *
	 * @param array $file 文件数组
	 * @return int|false 附件 ID 或 false
	 */
	private function upload_file( array $file ) {
		if ( ! function_exists( 'wp_handle_upload' ) ) {
			require_once( \ABSPATH . 'wp-admin/includes/file.php' );
		}

		$upload_overrides = [ 'test_form' => false ];
		$movefile = \wp_handle_upload( $file, $upload_overrides );

		if ( $movefile && ! isset( $movefile['error'] ) ) {
			$filename = $movefile['file'];
			$filetype = \wp_check_filetype( \basename( $filename ), null );

			$attachment = [
				'post_mime_type' => $filetype['type'],
				'post_title' => \preg_replace( '/\.[^.]+$/', '', \basename( $filename ) ),
				'post_content' => '',
				'post_status' => 'inherit'
			];

			$attach_id = \wp_insert_attachment( $attachment, $filename );
			require_once( \ABSPATH . 'wp-admin/includes/image.php' );
			$attach_data = \wp_generate_attachment_metadata( $attach_id, $filename );
			\wp_update_attachment_metadata( $attach_id, $attach_data );

			return $attach_id;
		}

		return false;
	}

	/**
	 * 处理 AJAX 文件上传
	 */
	public function handle_file_upload(): void {
		\check_ajax_referer( 'tooto-register-nonce', 'nonce' );

		if ( empty( $_FILES['file'] ) ) {
			\wp_send_json_error( [ 'message' => __( 'No file uploaded.', 'tooto-elementor' ) ] );
		}

		$file_id = $this->upload_file( $_FILES['file'] );
		if ( $file_id ) {
			\wp_send_json_success( [ 'file_id' => $file_id, 'url' => \wp_get_attachment_url( $file_id ) ] );
		} else {
			\wp_send_json_error( [ 'message' => __( 'File upload failed.', 'tooto-elementor' ) ] );
		}
	}
}

