<?php
/**
 * Dobare EnterX Integration Class
 *
 * Handles integration between Dobare and EnterX plugins for referral code synchronization.
 * Listens to EnterX authentication events and syncs member data with Dobare external API.
 *
 * @package Dobare
 * @since 1.3.3
 */

namespace Dobare\Core;

use Dobare\Abstracts\Dobare_REST_Controller;
use Dobare\Utils\Dobare_Utils;

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

/**
 * Class Dobare_Enterx_Integration
 *
 * Integrates EnterX OTP login plugin with Dobare customer loyalty system.
 */
class Dobare_Enterx_Integration
{
	/**
	 * Constructor
	 *
	 * Registers WordPress action hooks to listen for EnterX authentication events.
	 */
	/**
	 * Stores validation error to be returned via filter
	 *
	 * @var \WP_Error|null
	 */
	private $validation_error = null;

	public function __construct()
	{
		// Hook into EnterX before-login event to sync member data
		add_action('enterx_before_user_login', array($this, 'sync_member_with_referral'), 10, 3);
		
		// Hook into validation filter to return errors
		add_filter('enterx_before_user_login_validation', array($this, 'return_validation_error'), 10, 4);
	}

	/**
	 * Return validation error if one was set during sync
	 *
	 * @param mixed  $error         Current error (null if none)
	 * @param int    $user_id       WordPress user ID
	 * @param string $phone         User's phone number
	 * @param string $referral_code Referral code
	 *
	 * @return \WP_Error|null
	 */
	public function return_validation_error($error, $user_id, $phone, $referral_code)
	{
		// If we have a validation error from sync, return it
		if ($this->validation_error !== null) {
			return $this->validation_error;
		}
		
		// Otherwise return the existing error (or null)
		return $error;
	}

	/**
	 * Sync member data with Dobare external API
	 *
	 * Called when EnterX fires the 'enterx_before_user_login' action.
	 * Creates or updates a member in the Dobare system with referral code.
	 * If referral code validation fails, stores error in $validation_error property.
	 *
	 * @param int    $user_id       WordPress user ID
	 * @param string $phone         User's phone number
	 * @param string $referral_code Referral code entered during registration (optional)
	 *
	 * @return void
	 */
	public function sync_member_with_referral($user_id, $phone, $referral_code)
	{
		// Reset validation error for this sync attempt
		$this->validation_error = null;
		
		error_log('[Dobare EnterX Integration] START - User ID: ' . $user_id . ', Phone: ' . substr($phone, 0, 4) . '****' . substr($phone, -3) . ', Referral Code: ' . ($referral_code ? 'YES (' . $referral_code . ')' : 'NO'));

		// Validate user exists
		$user = get_userdata($user_id);
		if (!$user) {
			error_log('[Dobare EnterX Integration] ERROR: User not found for ID ' . $user_id);
			return;
		}
		error_log('[Dobare EnterX Integration] User found: ' . $user->user_login);

		// Normalize phone number
		$normalized_phone = Dobare_Utils::validate_and_normalize_phone_number($phone);
		if (empty($normalized_phone)) {
			error_log('[Dobare EnterX Integration] ERROR: Phone normalization failed for ' . $phone);
			return;
		}
		error_log('[Dobare EnterX Integration] Phone normalized: ' . substr($normalized_phone, 0, 4) . '****' . substr($normalized_phone, -3));

		// Check if Dobare API key is configured
		$api_key = Dobare_Utils::get_dob_api_key();
		if (empty($api_key)) {
			error_log('[Dobare EnterX Integration] ERROR: API key not configured');
			return;
		}
		error_log('[Dobare EnterX Integration] API key found: ' . substr($api_key, 0, 10) . '...');

		// Prepare member data
		$name = trim($user->first_name . ' ' . $user->last_name);
		if (empty($name)) {
			$name = $user->display_name;
		}
		error_log('[Dobare EnterX Integration] Member name: ' . $name);

		$sanitized_referral = '';
		if (!empty($referral_code)) {
			$sanitized_referral = sanitize_text_field($referral_code);
			error_log('[Dobare EnterX Integration] Referral code added to payload: ' . $referral_code);
		}

		$body = Dobare_Core::build_member_request_body(
			$normalized_phone,
			$name,
			$sanitized_referral !== '' ? $sanitized_referral : null
		);

		error_log('[Dobare EnterX Integration] Request body: ' . json_encode($body));

		// Call Dobare API to create/update member
		try {
			error_log('[Dobare EnterX Integration] Calling Dobare API: POST v1/members/');
			$response = Dobare_REST_Controller::dobare_remote_post(
				'v1/members/',
				$body,
				array('API-KEY' => $api_key)
			);

			error_log('[Dobare EnterX Integration] API response type: ' . gettype($response));
			error_log('[Dobare EnterX Integration] API response: ' . json_encode($response));

			// Handle API response
			if (is_wp_error($response)) {
				error_log('[Dobare EnterX Integration] ERROR: WP_Error - ' . $response->get_error_message());
				// Don't block login for network/connection errors
				return;
			} elseif (isset($response['status']) && $response['status'] >= 400) {
				error_log('[Dobare EnterX Integration] ERROR: HTTP ' . $response['status']);
				
				// Try to extract detailed error messages
				if (isset($response['data'])) {
					error_log('[Dobare EnterX Integration] Response data: ' . json_encode($response['data']));
				}
				
				// Check if this is specifically a referral code validation error
				$is_referral_error = false;
				if ($response['status'] === 400 && !empty($referral_code)) {
					// Check if error is about referred_by_code field
					if (isset($response['data']['meta']['detail']['referred_by_code'])) {
						$is_referral_error = true;
						error_log('[Dobare EnterX Integration] REFERRAL CODE VALIDATION FAILED: ' . json_encode($response['data']['meta']['detail']['referred_by_code']));
					}
					// Also check global error messages for referral-related errors
					elseif (isset($response['data']['meta']['detail']['global_error_messages'])) {
						$global_errors = $response['data']['meta']['detail']['global_error_messages'];
						foreach ($global_errors as $error) {
							if (stripos($error, 'referral') !== false || stripos($error, 'معرف') !== false || stripos($error, 'referred_by') !== false) {
								$is_referral_error = true;
								error_log('[Dobare EnterX Integration] REFERRAL CODE VALIDATION FAILED (global): ' . $error);
								break;
							}
						}
					}
				}
				
				// Log referral code validation errors but DO NOT block login
				// Referral validation happens in the previous step (registration form)
				// This hook fires during OTP verification and should not block login
				if ($is_referral_error) {
					error_log('[Dobare EnterX Integration] REFERRAL ERROR DETECTED (not blocking login): Invalid referral code "' . $referral_code . '"');
					error_log('[Dobare EnterX Integration] Referral validation should happen in registration form, not during OTP verification');
					// DO NOT SET validation_error - allow login to continue
				}
				
				// For other 400+ errors, just log and allow login to continue
				$error_message = 'Unknown error';
				if (isset($response['data']['meta']['detail']['global_error_messages'])) {
					$error_message = implode(', ', $response['data']['meta']['detail']['global_error_messages']);
				} elseif (isset($response['data']['meta']['detail'])) {
					$error_message = json_encode($response['data']['meta']['detail']);
				} elseif (isset($response['data']['message'])) {
					$error_message = $response['data']['message'];
				}
				
				error_log('[Dobare EnterX Integration] ERROR: API returned error ' . $response['status'] . ' - ' . $error_message . ' (allowing login to continue)');
			} else {
				error_log('[Dobare EnterX Integration] SUCCESS: Member synced successfully');
			}
		} catch (\Exception $e) {
			error_log('[Dobare EnterX Integration] EXCEPTION: ' . $e->getMessage());
			error_log('[Dobare EnterX Integration] Stack trace: ' . $e->getTraceAsString());
		}

		// Save phone number to WooCommerce billing details if not already set
		try {
			$customer = new \WC_Customer($user_id, true);
			if (empty($customer->get_billing_phone())) {
				$customer->set_billing_phone($phone);
				$customer->save();
				error_log('[Dobare EnterX Integration] Phone saved to WooCommerce billing: ' . substr($phone, 0, 4) . '****' . substr($phone, -3));
			} else {
				error_log('[Dobare EnterX Integration] Phone already exists in WooCommerce billing, not overwriting');
			}
			
			// Also save to user meta for consistency
			if (empty(get_user_meta($user_id, 'billing_phone', true))) {
				update_user_meta($user_id, 'billing_phone', $phone);
				error_log('[Dobare EnterX Integration] Phone saved to user meta');
			}
		} catch (\Exception $e) {
			error_log('[Dobare EnterX Integration] ERROR saving phone to WooCommerce: ' . $e->getMessage());
		}

		error_log('[Dobare EnterX Integration] END');
	}
}
