<?php

namespace Elementor_Pay_Addons\Shared;

class Utils
{
	public static function format_stripe_amount( $amount ) {
		return number_format($amount / 100, 2, '.', '');
	}

	public static function format_stripe_date( $seconds ) {
    // Convert seconds to GMT datetime string
    $dt_gmt = gmdate('Y-m-d H:i:s', $seconds);

    // Convert from GMT to local time zone based on WP settings
    $dt = get_date_from_gmt($dt_gmt, 'Y-m-d H:i:s');

    // Format according to WordPress date settings
    return date_i18n(get_option('date_format'), strtotime($dt));
	}

	public static function format_stripe_time( $seconds ) {
    // Convert seconds to GMT datetime string
    $dt_gmt = gmdate('Y-m-d H:i:s', $seconds);
    
    // Convert from GMT to local time zone based on WP settings
    $dt = get_date_from_gmt($dt_gmt, 'Y-m-d H:i:s');
    
    // Format according to WordPress date and time settings
    $format = get_option('date_format') . ' ' . get_option('time_format');
    return date_i18n($format, strtotime($dt));
	}

	public static function format_amount_with_symbol( $amount, $currency ) {
		$amount_in_dollars = $amount / 100;
		if ( class_exists( 'NumberFormatter' ) ) {
			$formatter = new \NumberFormatter( get_locale(), \NumberFormatter::CURRENCY );
			return $formatter->formatCurrency( $amount_in_dollars, $currency );
		}
		$symbol = self::get_currency_symbol( $currency );
		return $symbol . number_format($amount_in_dollars, 2, '.', '');
	}

  /**
   * Checks Stripe minimum order value authorized per currency
   */
  public static function get_minimum_amount($currency)
  {
    // Check order amount
    switch ($currency) {
      case 'USD':
      case 'CAD':
      case 'EUR':
      case 'CHF':
      case 'AUD':
      case 'SGD':
        $minimum_amount = 50;
        break;
      case 'GBP':
        $minimum_amount = 30;
        break;
      case 'DKK':
        $minimum_amount = 250;
        break;
      case 'NOK':
      case 'SEK':
        $minimum_amount = 300;
        break;
      case 'JPY':
        $minimum_amount = 5000;
        break;
      case 'MXN':
        $minimum_amount = 1000;
        break;
      case 'HKD':
        $minimum_amount = 400;
        break;
      default:
        $minimum_amount = 50;
        break;
    }

    return $minimum_amount;
  }

  public static function get_formatted_address($args = array(), $separator = '<br/>')
  {
    $address_string = $args['line1'] . $separator;

    if(!empty($args['line2'])) {
      $address_string .= $args['line2'] . $separator; 
    }
    
    $address_string .= $args['city'] . ", " . $args['state'] . " " . $args['postal_code'] . " ";
    $address_string .= $args['country'];

    // We're done!
    return $address_string;
  }

  public static function get_currencies()
  {
    $currencies = array(
      'USD' => array(__('US Dollars (USD)', 'pay-addons-for-elementor'), '$'),
      'EUR' => array(__('Euros (EUR)', 'pay-addons-for-elementor'), '€'),
      'GBP' => array(__('Pounds Sterling (GBP)', 'pay-addons-for-elementor'), '£'),
      'AUD' => array(__('Australian Dollars (AUD)', 'pay-addons-for-elementor'), 'AU$'),
      'AED' => array(__('United Arab Emirates Dirham (AED)', 'pay-addons-for-elementor'), 'د.إ'),
      'ARS' => array(__('Argentine Peso (ARS)', 'pay-addons-for-elementor'), 'ARS'),
      'BAM' => array(__('Bosnia and Herzegovina Convertible Mark (BAM)', 'pay-addons-for-elementor'), 'KM'),
      'BGN' => array(__('Bulgarian Lev (BGN)', 'pay-addons-for-elementor'), 'Лв.'),
      'BRL' => array(__('Brazilian Real (BRL)', 'pay-addons-for-elementor'), 'R$'),
      'CAD' => array(__('Canadian Dollars (CAD)', 'pay-addons-for-elementor'), 'CA$'),
      'CLP' => array(__('Chilean Peso (CLP)', 'pay-addons-for-elementor'), 'CLP'),
      'CNY' => array(__('Chinese Yuan (CNY)', 'pay-addons-for-elementor'), 'CN￥'),
      'COP' => array(__('Colombian Peso (COP)', 'pay-addons-for-elementor'), 'COL$'),
      'CZK' => array(__('Czech Koruna (CZK)', 'pay-addons-for-elementor'), 'Kč'),
      'DKK' => array(__('Danish Krone (DKK)', 'pay-addons-for-elementor'), 'kr'),
      'DOP' => array(__('Dominican Peso (DOP)', 'pay-addons-for-elementor'), 'RD$'),
      'EGP' => array(__('Egyptian Pound (EGP)', 'pay-addons-for-elementor'), 'E£'),
      'HKD' => array(__('Hong Kong Dollar (HKD)', 'pay-addons-for-elementor'), 'HK$'),
      'HUF' => array(__('Hungarian Forint (HUF)', 'pay-addons-for-elementor'), 'Ft'),
      'INR' => array(__('Indian Rupee (INR)', 'pay-addons-for-elementor'), '₹'),
      'IDR' => array(__('Indonesia Rupiah (IDR)', 'pay-addons-for-elementor'), 'Rp'),
      'ILS' => array(__('Israeli Shekel (ILS)', 'pay-addons-for-elementor'), '₪'),
      'JPY' => array(__('Japanese Yen (JPY)', 'pay-addons-for-elementor'), '¥'),
      'LBP' => array(__('Lebanese Pound (LBP)', 'pay-addons-for-elementor'), 'ل.ل'),
      'MYR' => array(__('Malaysian Ringgits (MYR)', 'pay-addons-for-elementor'), 'RM'),
      'MXN' => array(__('Mexican Peso (MXN)', 'pay-addons-for-elementor'), 'MX$'),
      'NZD' => array(__('New Zealand Dollar (NZD)', 'pay-addons-for-elementor'), 'NZ$'),
      'NOK' => array(__('Norwegian Krone (NOK)', 'pay-addons-for-elementor'), 'kr'),
      'PEN' => array(__('Peruvian Nuevo Sol (PEN)', 'pay-addons-for-elementor'), 'S/'),
      'PHP' => array(__('Philippine Pesos (PHP)', 'pay-addons-for-elementor'), '₱'),
      'PLN' => array(__('Polish Zloty (PLN)', 'pay-addons-for-elementor'), 'zł'),
      'RON' => array(__('Romanian Leu (RON)', 'pay-addons-for-elementor'), 'lei'),
      'RUB' => array(__('Russian Ruble (RUB)', 'pay-addons-for-elementor'), '₽'),
      'SAR' => array(__('Saudi Riyal (SAR)', 'pay-addons-for-elementor'), 'ر.س'),
      'SGD' => array(__('Singapore Dollar (SGD)', 'pay-addons-for-elementor'), 'SG$'),
      'ZAR' => array(__('South African Rand (ZAR)', 'pay-addons-for-elementor'), 'R'),
      'KRW' => array(__('South Korean Won (KRW)', 'pay-addons-for-elementor'), '₩'),
      'SEK' => array(__('Swedish Krona (SEK)', 'pay-addons-for-elementor'), 'kr'),
      'CHF' => array(__('Swiss Franc (CHF)', 'pay-addons-for-elementor'), 'CHF'),
      'TWD' => array(__('Taiwan New Dollars (TWD)', 'pay-addons-for-elementor'), 'NT$'),
      'THB' => array(__('Thai Baht (THB)', 'pay-addons-for-elementor'), '฿'),
      'TRY' => array(__('Turkish Lira (TRY)', 'pay-addons-for-elementor'), '₺'),
      'UYU' => array(__('Uruguayan Peso (UYU)', 'pay-addons-for-elementor'), '$U'),
      'VND' => array(__('Vietnamese Dong (VND)', 'pay-addons-for-elementor'), '₫'),
    );

    return $currencies;
  }

  public static function get_currencies_options() {
    $currenciesOptions = [];
		$all_currencies = self::get_currencies();
		foreach($all_currencies as $cur => $val) {
			$currenciesOptions[$cur] = $val[1] . ' ' . $val[0];
		}
    return $currenciesOptions;
  }

  public static function get_supported_payment_methods($currency) {
    $default_methods = [
      'automatic' => __('Automatic collect', 'pay-addons-for-elementor'),
      'card' => __('Card', 'pay-addons-for-elementor'),
    ];
    $usd_methods = [
      'automatic' => __('Automatic collect', 'pay-addons-for-elementor'),
      'card' => __('Card', 'pay-addons-for-elementor'),
      'affirm' => __('Affirm', 'pay-addons-for-elementor'),
      'afterpay_clearpay' => __('Afterpay (Clearpay)', 'pay-addons-for-elementor'),
      'alipay' => __('Alipay', 'pay-addons-for-elementor'),
      'cashapp' => __('Cash App Pay', 'pay-addons-for-elementor'),
      'klarna' => __('Klarna', 'pay-addons-for-elementor'),
      'us_bank_account'=> __('ACH Direct Debit', 'pay-addons-for-elementor'),
      'wechat_pay' => __('WeChat Pay', 'pay-addons-for-elementor'),
    ];
    $payment_methods = array(
      'USD' => $usd_methods,
      'CAD' => $usd_methods,
      'CNY' => [
        'automatic' => __('Automatic collect', 'pay-addons-for-elementor'),
        'card' => __('Card', 'pay-addons-for-elementor'),
        'alipay' => __('Alipay', 'pay-addons-for-elementor'),
        'wechat_pay' => __('WeChat Pay', 'pay-addons-for-elementor'),
      ],
      'HKD' => [
        'automatic' => __('Automatic collect', 'pay-addons-for-elementor'),
        'card' => __('Card', 'pay-addons-for-elementor'),
        'alipay' => __('Alipay', 'pay-addons-for-elementor'),
        'wechat_pay' => __('WeChat Pay', 'pay-addons-for-elementor'),
      ],
      'SGD' => [
        'automatic' => __('Automatic collect', 'pay-addons-for-elementor'),
        'card' => __('Card', 'pay-addons-for-elementor'),
        'alipay' => __('Alipay', 'pay-addons-for-elementor'),
        'grabpay' => __('GrabPay', 'pay-addons-for-elementor'),
        'paynow' => __('PayNow', 'pay-addons-for-elementor'),
        'wechat_pay' => __('WeChat Pay', 'pay-addons-for-elementor'),
      ],
      'JPY' => [
        'automatic' => __('Automatic collect', 'pay-addons-for-elementor'),
        'card' => __('Card', 'pay-addons-for-elementor'),
        'konbini' => __('Konbini', 'pay-addons-for-elementor'),
      ],
      'EUR' => [
        'automatic' => __('Automatic collect', 'pay-addons-for-elementor'),
        'bancontact' => __('Bancontact', 'pay-addons-for-elementor'),
        'blik' => __('BLIK', 'pay-addons-for-elementor'),
        'card' => __('Card', 'pay-addons-for-elementor'),
        'eps' => __('EPS', 'pay-addons-for-elementor'),
        'giropay' => __('giropay', 'pay-addons-for-elementor'),
        'ideal' => __('iDEAL', 'pay-addons-for-elementor'),
        'klarna' => __('Klarna', 'pay-addons-for-elementor'),
        'p24' => __('P24 (Przelewy24)', 'pay-addons-for-elementor'),
        'revolut_pay' => __('Revolut Pay', 'pay-addons-for-elementor'),
        'sepa_debit' => __('SEPA Direct Debit', 'pay-addons-for-elementor'),
        'sofort' => __('SOFORT', 'pay-addons-for-elementor'),
      ],
      'GBP' => [
        'automatic' => __('Automatic collect', 'pay-addons-for-elementor'),
        'bacs_debit' => __('Bacs Direct Debit', 'pay-addons-for-elementor'),
        'card' => __('Card', 'pay-addons-for-elementor'),
      ],
      'AUD' => [
        'automatic' => __('Automatic collect', 'pay-addons-for-elementor'),
        'au_becs_debit' => __('BECS Direct Debit', 'pay-addons-for-elementor'),
        'card' => __('Card', 'pay-addons-for-elementor'),
      ],
      'MYR' => [
        'automatic' => __('Automatic collect', 'pay-addons-for-elementor'),
        'card' => __('Card', 'pay-addons-for-elementor'),
        'fpx' => __('FPX', 'pay-addons-for-elementor'),
      ],
      'BRL' => [
        'automatic' => __('Automatic collect', 'pay-addons-for-elementor'),
        'boleto' => __('Boleto', 'pay-addons-for-elementor'),
        'card' => __('Card', 'pay-addons-for-elementor'),
        'pix' => __('Pix', 'pay-addons-for-elementor'),
      ],
      'MXN' => [
        'automatic' => __('Automatic collect', 'pay-addons-for-elementor'),
        'card' => __('Card', 'pay-addons-for-elementor'),
        'oxxo' => __('OXXO', 'pay-addons-for-elementor'),
      ],
      'PLN' => [
        'automatic' => __('Automatic collect', 'pay-addons-for-elementor'),
        'blik' => __('BLIK', 'pay-addons-for-elementor'),
        'card' => __('Card', 'pay-addons-for-elementor'),
        'p24' => __('P24 (Przelewy24)', 'pay-addons-for-elementor'),
      ],
      'SEK' => [
        'automatic' => __('Automatic collect', 'pay-addons-for-elementor'),
        'card' => __('Card', 'pay-addons-for-elementor'),
        'swish' => __('Swish', 'pay-addons-for-elementor'),
      ],
      'CHF' => [
        'automatic' => __('Automatic collect', 'pay-addons-for-elementor'),
        'card' => __('Card', 'pay-addons-for-elementor'),
        'twint' => __('Twint', 'pay-addons-for-elementor'),
      ],
      'NZD' => [
        'automatic' => __('Automatic collect', 'pay-addons-for-elementor'),
        'card' => __('Card', 'pay-addons-for-elementor'),
        'afterpay_clearpay' => __('Afterpay (Clearpay)', 'pay-addons-for-elementor'),
      ],
      'KRW' => [
        'automatic' => __('Automatic collect', 'pay-addons-for-elementor'),
        'card' => __('Card', 'pay-addons-for-elementor'),
        'kakao_pay' => __('Kakao Pay', 'pay-addons-for-elementor'),
        'kr_card' => __('Korean Local Cards', 'pay-addons-for-elementor'),
        'naver_pay' => __('Naver Pay', 'pay-addons-for-elementor'),
        'payco' => __('Payco', 'pay-addons-for-elementor'),
        'samsung_pay' => __('Samsung Pay', 'pay-addons-for-elementor'),
      ],
      'THB' => [
        'automatic' => __('Automatic collect', 'pay-addons-for-elementor'),
        'card' => __('Card', 'pay-addons-for-elementor'),
        'promptpay' => __('PromptPay', 'pay-addons-for-elementor'),
      ],
    );

    return $payment_methods[$currency] ?? $default_methods;
  }

  public static function get_currency_symbol($currency) {
    $currency = strtoupper($currency);
		$all_currencies = self::get_currencies();
    if(array_key_exists($currency, $all_currencies)) {
      return $all_currencies[$currency][1];
    }
    return '$';
  }

  public static function get_pages_options() {
    $pages   = get_pages(
      array(
        'sort_column'  => 'menu_order',
        'sort_order'   => 'ASC',
        'hierarchical' => 0,
      )
    );
    $options = array(
      '' => __('Current page', 'pay-addons-for-elementor'),
      'custom' => __('Custom URL', 'pay-addons-for-elementor'),
    );
    foreach ( $pages as $page ) {
      $options[ get_page_link($page->ID) ] = ! empty( $page->post_title ) ? $page->post_title : '#' . $page->ID;
    }

    return $options;
  }

  public static function make_classname( $dirname ) {
		$dirname    = pathinfo( $dirname, PATHINFO_FILENAME );
		$class_name = explode( '-', $dirname );
		$class_name = array_map( 'ucfirst', $class_name );
		$class_name = implode( '_', $class_name );

		return $class_name;
	}

  public static function format_stripe_desc($name, $desc) {
    return $name . ($desc ? ' - ' . $desc : '');
  }

  public static function trim_metadata($metadata, $max_keys = 49)
  {
    foreach ($metadata as $key => $value) {
      if (is_scalar($value) && strlen((string) $value) >= 500) {
        $metadata[$key] = substr((string) $value, 0, 500);
      }

      if (strlen((string) $key) >= 40) {
        unset($metadata[$key]);
        $newkey = substr((string) $key, 0, 40);
        $metadata[$newkey] = $value;
      }
    }

    return array_slice($metadata, 0, $max_keys, true);
  }

  public static function get_bank_transfer_type(string $currency): string {
    $map = [
      'usd' => 'us_bank_transfer',
      'eur' => 'eu_bank_transfer',
      'gbp' => 'gb_bank_transfer',
      'jpy' => 'jp_bank_transfer',
      'mxn' => 'mx_bank_transfer',
    ];
    return $map[strtolower($currency)] ?? 'us_bank_transfer';
  }

  public static function build_bank_transfer_options(string $currency, string $eu_country = 'DE'): array {
    $type = self::get_bank_transfer_type($currency);
    $options = ['type' => $type];
    if ($type === 'eu_bank_transfer') {
      $options['eu_bank_transfer'] = ['country' => strtoupper($eu_country)];
    }
    return $options;
  }

  public static function get_client_ip() {
    if ( ! empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
        $ip = sanitize_text_field( wp_unslash( $_SERVER['HTTP_CLIENT_IP'] ) );
    } elseif ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
        $ip = sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_FORWARDED_FOR'] ) );
        // In case of multiple IPs in HTTP_X_FORWARDED_FOR, take the first one
        $ip_array = explode( ',', $ip );
        $ip = trim( $ip_array[0] );
    } else {
        $ip = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '127.0.0.1';
    }
    // Validate IP address format
    $ip = filter_var( $ip, FILTER_VALIDATE_IP );
    if ( false === $ip ) {
        $ip = '127.0.0.1';
    }
    return apply_filters( 'wpb_get_ip', $ip );
  }
}