<?php

namespace Dobare\My_Account;

use Dobare\Core\Dobare_Core;
use Dobare\Core\Dobare_Membership_Extended;
use Dobare\Utils\Dobare_Utils;

class Dobare_My_Account {

	public function __construct() {
		// Add Dobare fields to my-account form
		add_action( 'woocommerce_edit_account_form', array( $this, 'add_dobare_fields_to_account_form' ) );
		
		// Save Dobare fields
		add_action( 'woocommerce_save_account_details', array( $this, 'save_dobare_account_fields' ), 10, 1 );
		
		// Enqueue styles
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_my_account_styles' ) );
	}

	/**
	 * Enqueue styles for my-account page
	 */
	public function enqueue_my_account_styles() {
		if ( is_account_page() ) {
			
			// Enqueue Persian Datepicker assets from local copies (per WP guideline).
			$persian_assets_base = plugin_dir_url( DOBARE_MAIN_PLUGIN_FILE ) . 'assets/vendor/persian-datepicker/';

			wp_enqueue_style(
				'dobare-persian-datepicker',
				$persian_assets_base . 'persian-datepicker.min.css',
				array(),
				DOBARE_VERSION
			);
			
			wp_enqueue_style(
				'dobare-my-account',
				plugin_dir_url( DOBARE_MAIN_PLUGIN_FILE ) . 'includes/my-account/my-account.css',
				array(),
				DOBARE_VERSION
			);
			
			// Enqueue Persian Date library
			wp_enqueue_script(
				'dobare-persian-date',
				$persian_assets_base . 'persian-date.min.js',
				array(),
				DOBARE_VERSION,
				true
			);
			
			// Enqueue Persian Datepicker JS
			wp_enqueue_script(
				'dobare-persian-datepicker',
				$persian_assets_base . 'persian-datepicker.min.js',
				array( 'jquery', 'dobare-persian-date' ),
				DOBARE_VERSION,
				true
			);
			
			// Enqueue our custom script
			wp_enqueue_script(
				'dobare-my-account',
				plugin_dir_url( DOBARE_MAIN_PLUGIN_FILE ) . 'includes/my-account/my-account.js',
				array( 'jquery', 'dobare-persian-datepicker' ),
				DOBARE_VERSION,
				true
			);
		}
	}

	/**
	 * Get current user's Dobare data
	 *
	 * @return Dobare_Membership_Extended|null
	 */
	private function get_current_user_dobare_data() {
		if ( ! is_user_logged_in() ) {
			return null;
		}

		$user_id = get_current_user_id();
		$customer = new \WC_Customer( $user_id );
		$phone = $customer->get_billing_phone();

		// If billing phone is empty, try alternative sources used by authentication plugins
		if ( empty( $phone ) ) {
			// Check Digits plugin
			$digits_phone = get_user_meta( $user_id, 'digits_phone', true );
			if ( ! empty( $digits_phone ) ) {
				$phone = $digits_phone;
			}
			
			// Check Digits alternative field
			if ( empty( $phone ) ) {
				$digits_phone_no = get_user_meta( $user_id, 'digits_phone_no', true );
				if ( ! empty( $digits_phone_no ) ) {
					$phone = $digits_phone_no;
				}
			}
			
			// Check Mobits plugin
			if ( empty( $phone ) ) {
				$mobits_phone = get_user_meta( $user_id, 'mobits_mobile_number', true );
				if ( ! empty( $mobits_phone ) ) {
					$phone = $mobits_phone;
				}
			}
			
			// Check Mobits alternative field
			if ( empty( $phone ) ) {
				$mobits_mobile = get_user_meta( $user_id, 'mobits_mobile', true );
				if ( ! empty( $mobits_mobile ) ) {
					$phone = $mobits_mobile;
				}
			}
			
			// Check direct user meta billing_phone (Voorodak and others)
			if ( empty( $phone ) ) {
				$meta_billing_phone = get_user_meta( $user_id, 'billing_phone', true );
				if ( ! empty( $meta_billing_phone ) ) {
					$phone = $meta_billing_phone;
				}
			}
			
			// Try shipping phone as last resort
			if ( empty( $phone ) ) {
				$shipping_phone = $customer->get_shipping_phone();
				if ( ! empty( $shipping_phone ) ) {
					$phone = $shipping_phone;
				}
			}
		}

		if ( empty( $phone ) ) {
			return null;
		}

		$normalized_phone = Dobare_Utils::validate_and_normalize_phone_number( $phone );
		
		if ( empty( $normalized_phone ) ) {
			return null;
		}

		// Check cache first
		$transient_name = 'dobare_my_account_' . md5( $normalized_phone );
		$cached_member = \get_transient( $transient_name );

		if ( $cached_member !== false && $cached_member instanceof Dobare_Membership_Extended ) {
			return $cached_member;
		}

		// Fetch from API
		$member = Dobare_Core::get_member_extended( $normalized_phone );
		
		if ( $member instanceof Dobare_Membership_Extended ) {
			// Cache for 5 minutes
			\set_transient( $transient_name, $member, 5 * MINUTE_IN_SECONDS );
			return $member;
		}

		return null;
	}

	/**
	 * Add Dobare fields to WooCommerce account details form
	 */
	public function add_dobare_fields_to_account_form() {
		$member = $this->get_current_user_dobare_data();

		if ( ! $member ) {
			return;
		}

		echo '<fieldset class="dobare-account-fields">';
		echo '<legend>' . esc_html__( 'اطلاعات باشگاه مشتریان', 'dobare' ) . '</legend>';

		// Display-only fields
		$this->render_readonly_field(
			__( 'مقدار اعتبار', 'dobare' ),
			number_format( $member->gift_credit_amount ) . ' ' . Dobare_Utils::get_currency_word()
		);

		$this->render_readonly_field(
			__( 'مقدار امتیاز', 'dobare' ),
			'<span class="dobare-points-unavailable">0</span>'
		);

		$this->render_readonly_field(
			__( 'کد معرف', 'dobare' ),
			'<span class="dobare-referral-code">' . esc_html( $member->referral_code ) . '</span>' .
			'<button type="button" class="dobare-copy-btn" onclick="navigator.clipboard.writeText(\'' . esc_js( $member->referral_code ) . '\'); this.textContent=\'کپی شد!\';" title="' . esc_attr__( 'کپی', 'dobare' ) . '">' . __( 'کپی', 'dobare' ) . '</button>'
		);

		// Editable date fields
		$this->render_date_field(
			'dobare_birth_date',
			__( 'تاریخ تولد', 'dobare' ),
			$member->birth_date
		);

		$this->render_date_field(
			'dobare_marriage_date',
			__( 'تاریخ ازدواج', 'dobare' ),
			$member->marriage_date
		);

		echo '</fieldset>';
	}

	/**
	 * Render a readonly field
	 *
	 * @param string $label Field label
	 * @param string $value Field value (can contain HTML)
	 */
	private function render_readonly_field( string $label, string $value ) {
		?>
		<p class="woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide dobare-readonly-field">
			<label><?php echo esc_html( $label ); ?></label>
			<span class="dobare-readonly-value"><?php echo $value; // Already escaped where needed ?></span>
		</p>
		<?php
	}

	/**
	 * Render an editable date field
	 *
	 * @param string $field_name Field name
	 * @param string $label Field label
	 * @param string|null $value Current value (Gregorian YYYY-MM-DD format)
	 */
	private function render_date_field( string $field_name, string $label, $value ) {
		// Convert Gregorian date to Persian for display
		$display_value = '';
		if ( ! empty( $value ) ) {
			try {
				$date = new \DateTime( $value );
				$display_value = $date->format( 'Y/m/d' ); // Will be converted to Persian by JS
			} catch ( \Exception $e ) {
				$display_value = '';
			}
		}
		?>
		<p class="woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide">
			<label for="<?php echo esc_attr( $field_name ); ?>">
				<?php echo esc_html( $label ); ?>
			</label>
			<div class="dobare-date-field-wrapper">
				<input 
					type="text" 
					class="woocommerce-Input woocommerce-Input--text input-text dobare-date-input" 
					name="<?php echo esc_attr( $field_name ); ?>" 
					id="<?php echo esc_attr( $field_name ); ?>" 
					data-gregorian-value="<?php echo esc_attr( $value ?? '' ); ?>"
					value="<?php echo esc_attr( $display_value ); ?>"
					placeholder="YYYY/MM/DD"
					readonly
				/>
				<span class="dobare-calendar-icon" onclick="document.getElementById('<?php echo esc_attr( $field_name ); ?>').focus();">
					<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
						<rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect>
						<line x1="16" y1="2" x2="16" y2="6"></line>
						<line x1="8" y1="2" x2="8" y2="6"></line>
						<line x1="3" y1="10" x2="21" y2="10"></line>
					</svg>
				</span>
			</div>
		</p>
		<?php
	}

	/**
	 * Save Dobare account fields when user saves account details
	 *
	 * @param int $user_id User ID
	 */
	public function save_dobare_account_fields( int $user_id ) {
		if ( ! isset( $_POST['dobare_birth_date'] ) && ! isset( $_POST['dobare_marriage_date'] ) ) {
			return;
		}

		$customer = new \WC_Customer( $user_id );
		$phone = $customer->get_billing_phone();

		if ( empty( $phone ) ) {
			wc_add_notice( __( 'برای ذخیره اطلاعات دوباره، شماره تلفن الزامی است.', 'dobare' ), 'error' );
			return;
		}

		$normalized_phone = Dobare_Utils::validate_and_normalize_phone_number( $phone );
		
		if ( empty( $normalized_phone ) ) {
			wc_add_notice( __( 'شماره تلفن نامعتبر است.', 'dobare' ), 'error' );
			return;
		}

		$birth_date = isset( $_POST['dobare_birth_date'] ) ? sanitize_text_field( wp_unslash( $_POST['dobare_birth_date'] ) ) : null;
		$marriage_date = isset( $_POST['dobare_marriage_date'] ) ? sanitize_text_field( wp_unslash( $_POST['dobare_marriage_date'] ) ) : null;
		
		// Validate date format (YYYY-MM-DD)
		if ( ! empty( $birth_date ) && ! preg_match( '/^\d{4}-\d{2}-\d{2}$/', $birth_date ) ) {
			$birth_date = null;
		}
		if ( ! empty( $marriage_date ) && ! preg_match( '/^\d{4}-\d{2}-\d{2}$/', $marriage_date ) ) {
			$marriage_date = null;
		}

		$update_data = array();
		
		if ( ! empty( $birth_date ) ) {
			$update_data['birth_date'] = $birth_date;
		}
		
		if ( ! empty( $marriage_date ) ) {
			$update_data['marriage_date'] = $marriage_date;
		}

		if ( empty( $update_data ) ) {
			return;
		}

		$response = Dobare_Core::update_member( $normalized_phone, $update_data );

		if ( is_wp_error( $response ) ) {
			wc_add_notice( 
				__( 'خطا در ذخیره اطلاعات: ', 'dobare' ) . $response->get_error_message(), 
				'error' 
			);
			return;
		}

		if ( isset( $response['status'] ) && $response['status'] >= 200 && $response['status'] < 300 ) {
			$transient_name = 'dobare_my_account_' . md5( $normalized_phone );
			\delete_transient( $transient_name );

			wc_add_notice( __( 'اطلاعات دوباره با موفقیت ذخیره شد.', 'dobare' ), 'success' );
		} else {
			$error_message = __( 'خطا در ذخیره اطلاعات در سرور دوباره.', 'dobare' );
			
			if ( isset( $response['data']['meta']['detail']['global_error_messages'] ) ) {
				$api_errors = $response['data']['meta']['detail']['global_error_messages'];
				$error_message .= ' ' . implode( ' ', $api_errors );
			}
			
			wc_add_notice( $error_message, 'error' );
		}
	}
}

