<?php

namespace Dobare\Customer_Credit;

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

class Dobare_Customer_Credit_Service
{
	/**
	 * Get customer credit data for the current user using existing membership utilities
	 *
	 * @return array
	 */
	public static function get_customer_credit_data(): array
	{
		$default_data = array(
			"is_active"      => false,
			"credit_amount"  => 0,
			"user_phone"     => null,
			"user_name"      => null,
			"position"       => self::get_position()
		);

		if (\Dobare\Utils\Dobare_Utils::is_credit_temporarily_disabled()) {
			return $default_data;
		}

		// Check if feature is enabled
		if (!self::is_feature_enabled()) {
			return $default_data;
		}

		// Extract user phone number using existing patterns
		$user_phone = self::extract_user_phone();
		if (empty($user_phone)) {
			return $default_data;
		}

		// Check cache first for better performance
		$transient_name = 'dobare_customer_credit_' . md5($user_phone);
		$cached_membership = \get_transient($transient_name);

		if ($cached_membership !== false && $cached_membership instanceof Dobare_Membership) {
			$membership = $cached_membership;
		} else {
			// Use existing membership utility for API call and data parsing
			$membership = Dobare_Core::get_membership($user_phone);

			// Cache the result if it's a valid membership object
			if ($membership instanceof Dobare_Membership) {
				// Cache for 5 minutes to avoid excessive API calls
				\set_transient($transient_name, $membership, 5 * MINUTE_IN_SECONDS);
			}
		}

		// Check if we got a valid membership object
		if ($membership instanceof Dobare_Membership) {
			return array(
				"is_active"      => true,
				"credit_amount"  => $membership->gift_credit_amount,
				"user_phone"     => $membership->phone,
				"user_name"      => $membership->name,
				"position"       => self::get_position()
			);
		}

		return $default_data;
	}

	/**
	 * Extract user phone number from customer data or session
	 *
	 * @return string|null
	 */
	private static function extract_user_phone(): ?string
	{
		// Ensure WooCommerce session is initialized for REST API context
		if (function_exists('WC') && WC()) {
			// Initialize session if not already done
			if (is_null(WC()->session)) {
				try {
					if (method_exists(WC(), 'initialize_session')) {
						WC()->initialize_session();
					}
				} catch (\Exception $e) {
					// Continue with other methods
				}
			}

			// Initialize customer if user is logged in but customer isn't set
			if (is_user_logged_in() && (is_null(WC()->customer) || WC()->customer->get_id() == 0)) {
				try {
					WC()->customer = new \WC_Customer(get_current_user_id());
				} catch (\Exception $e) {
					// Continue with other methods
				}
			}
		}

		// First check customer data (for saved customers)
		if (function_exists('WC') && \WC()->customer) {
			$customer = \WC()->customer;
			$phone = $customer->get_billing_phone() ?: $customer->get_shipping_phone();

			if (!empty($phone)) {
				return Dobare_Utils::validate_and_normalize_phone_number($phone);
			}
		}

		// Check WooCommerce session for direct phone storage
		if (function_exists('WC') && \WC()->session) {
			// Check direct phone storage in session
			$session_phone = \WC()->session->get('billing_phone');
			if (!empty($session_phone)) {
				return Dobare_Utils::validate_and_normalize_phone_number($session_phone);
			}

			$session_phone = \WC()->session->get('shipping_phone');
			if (!empty($session_phone)) {
				return Dobare_Utils::validate_and_normalize_phone_number($session_phone);
			}
		}

		// Check if user is logged in and get phone from user meta (fallback)
		if (is_user_logged_in()) {
			$user_id = get_current_user_id();

			// Try billing phone from user meta
			$phone = get_user_meta($user_id, 'billing_phone', true);
			if (!empty($phone)) {
				return Dobare_Utils::validate_and_normalize_phone_number($phone);
			}

			// Try creating WC customer directly if not initialized
			if (function_exists('WC')) {
				try {
					$customer = new \WC_Customer($user_id);
					$phone = $customer->get_billing_phone() ?: $customer->get_shipping_phone();
					if (!empty($phone)) {
						return Dobare_Utils::validate_and_normalize_phone_number($phone);
					}
				} catch (\Exception $e) {
					// Continue to session fallback
				}
			}
		}

		// Then check session checkout data (for form input during checkout)
		if (function_exists('WC') && \WC()->session) {
			$checkout_data = \WC()->session->get('checkout_data');
			if (!empty($checkout_data)) {
				$phone = $checkout_data['billing_phone'] ?? $checkout_data['shipping_phone'] ?? null;
				if (!empty($phone)) {
					return Dobare_Utils::validate_and_normalize_phone_number($phone);
				}
			}
		}

		return null;
	}

	/**
	 * Check if customer credit indicator feature is enabled
	 *
	 * @return bool
	 */
	public static function is_feature_enabled(): bool
	{
		return (bool) Dobare_Utils::dob_get_option('customer_credit_indicator_enabled', false);
	}

	/**
	 * Enable or disable the customer credit indicator feature
	 *
	 * @param bool $enabled
	 * @return bool
	 */
	public static function set_feature_enabled(bool $enabled): bool
	{
		return Dobare_Utils::dob_update_option('customer_credit_indicator_enabled', $enabled);
	}

	/**
	 * Get the position setting for customer credit indicator
	 *
	 * @return string Either 'L' (Left) or 'R' (Right), defaults to 'R'
	 */
	public static function get_position(): string
	{
		$position = Dobare_Utils::dob_get_option('customer_credit_indicator_position', 'R');

		// Validate position value, default to 'R' if invalid
		if (!in_array($position, ['L', 'R'], true)) {
			$position = 'R';
		}

		return $position;
	}

	/**
	 * Set the position for customer credit indicator
	 *
	 * @param string $position Either 'L' (Left) or 'R' (Right)
	 * @return bool True on success, false on failure
	 */
	public static function set_position(string $position): bool
	{
		// Validate position value
		if (!in_array($position, ['L', 'R'], true)) {
			return false;
		}

		return Dobare_Utils::dob_update_option('customer_credit_indicator_position', $position);
	}
}
