<?php

defined('ABSPATH') || exit;

class ADAPAYFWC_GateWay extends WC_Payment_Gateway
{
  protected $log;
  public $coinApiKey, $orderTimeout, $coinMarketCapKey, $blockfrostAPIKey, $walletAddress;

  public function __construct()
  {

    add_filter('woocommerce_currencies', [$this, 'addCardano']);
    add_filter('woocommerce_currency_symbol', [$this, 'addCardanoSymbol'], 10, 2);


    // Basic settings
    $this->log                  = wc_get_logger();
    $this->id                   = 'ada_payment';
    $this->title             = __('Ada Payment', 'adapayments-for-woocommerce');
    $this->method_description       = __('Connect wallet and pay with ada', 'adapayments-for-woocommerce');
    $this->order_button_text = __('Sign Transaction ', 'adapayments-for-woocommerce');


    $this->init_form_fields();
    $this->init_settings();


    $this->walletAddress             = $this->get_option('walletAddress');
    $this->coinApiKey              = $this->get_option('coinApiKey');
    $this->coinMarketCapKey         = $this->get_option('coinMarketCapKey');
    $this->orderTimeout              = $this->get_option('orderTimeout');

    add_action('woocommerce_update_options_payment_gateways_' . $this->id, [
      $this,
      'process_admin_options',
    ]);
    add_filter('woocommerce_thankyou_order_received_text', array($this, 'order_received_text'), 10, 2);
    add_action('wp_enqueue_scripts', [$this, 'enqueue_cart_data'], 99);
  }

  public function init_form_fields()
  {
    $this->form_fields = array(
      'enabled'                 => array(
        'title'   => __('Enable/Disable', 'adapayments-for-woocommerce'),
        'type'    => 'checkbox',
        'label'   => __('Enable Cardano (ADA) payments', 'adapayments-for-woocommerce'),
        'default' => false,
      ),
      'title'       => array(
        'title'       => __('Title', 'adapayments-for-woocommerce'),
        'type'        => 'text',
        'description' => __(
          'This controls the title which user sees during checkout.',
          'adapayments-for-woocommerce'
        ),
        'default'     => _x('Cardano (ADA)', 'Cardano payment method', 'adapayments-for-woocommerce'),
        'desc_tip'    => true,
      ),
      'description'             => array(
        'title'       => __('Description', 'adapayments-for-woocommerce'),
        'type'        => 'textarea',
        'description' => __(
          "payment method description that the customer will see on your checkout.",
          'adapayments-for-woocommerce'
        ),
        'default'     => __("Pay with Cardano (ADA)! After placing your order payment details will be displayed.", "adapayments-for-woocommerce"),
        'desc_tip'    => true,
      ),
      'network'          => array(
        'title'       => __(
          'Cardano Network',
          'adapayments-for-woocommerce'
        ),
        'type'        => 'select',
        'description' => __(
          "Choose whether you'd like to run in mainnet or testnet mode.",
          'adapayments-for-woocommerce'
        ),
        'default'     => 'mainnet',
        'options'     => array(
          'mainnet' => 'Mainnet',
          'preview' => 'Preview',
        ),
      ),
      'coinApiKey'           => array(
        'title'       => __(
          'Coin API Key',
          'adapayments-for-woocommerce'
        ),
        'type'        => 'text',
        'description' => __('Get your API key at: https://www.coinapi.io/', 'adapayments-for-woocommerce'),
        'required'    => true,
      ),
      'coinMarketCapKey'          => array(
        'title'       => __('CoinMarketCap API Key', 'adapayments-for-woocommerce'),
        'type'        => 'text',
        'description' => __(
          ' Get your API key at: https://coinmarketcap.com/',
          'adapayments-for-woocommerce'
        ),
        'required'    => false,
      ),
      'walletAddress'           => array(
        'title'       => __('Shelley Wallet Address', 'adapayments-for-woocommerce'),
        'type'        => 'text',
        'description' => __('Cardano Shelley wallet address', 'adapayments-for-woocommerce'),
        'default'     => '',
        'desc_tip'    => true,
      ),
      'orderTimeout'            => array(
        'title'       => __('Order Timeout', 'adapayments-for-woocommerce'),
        'type'        => 'select',
        'description' => __(
          'This is the time to keep orders on hold before cancelling them due to non-payment.',
          'adapayments-for-woocommerce'
        ),
        'default'     => '3600',
        'options'     => array(
          '0'     => 'Never',
          '300'   => '5 Minutes',
          '600'   => '10 Minutes',
          '1800'  => '30 Minutes',
          '3600'  => '1 Hour',
          '7200'  => '2 Hours',
          '14400' => '4 Hours',
          '21600' => '6 Hours',
          '43200' => '12 Hours',
          '86400' => '24 Hours',
        ),
      ),
      'processFeeLabel'         => array(
        'title'       => __('Processing Fee Label', 'adapayments-for-woocommerce'),
        'type'        => 'text',
        'default'     => 'Processing Fee',
        'description' => __(
          'The label for the processing fee that will be shown to the user on cart and checkout pages.',
          'adapayments-for-woocommerce'
        ),
      ),
    );
  }


  public function addCardano($currencies)
  {
    $currencies['ADA'] = __('Cardano (ADA)', 'adapayments-for-woocommerce');

    return $currencies;
  }


  public function addCardanoSymbol($currency_symbol, $currency)
  {
    if ($currency == 'ADA') {
      $currency_symbol = '₳';
    }

    return $currency_symbol;
  }

  public function get_dynamic_description(): string
  {
      $description = $this->get_option('description', '');
      $ada_info    = '';

      if (! is_admin() && WC()->cart && WC()->cart->get_total('edit') > 0) {
          $settings   = get_option('woocommerce_ada_payment_settings');
          $currency   = get_woocommerce_currency();
          $cart_total = (float) WC()->cart->get_total('edit');
          $ada_price  = ADAPAYFWC_get_ada_price_in_currency($currency, $settings);

          if ($ada_price > 0) {
              $ada_amount = $cart_total / $ada_price;

              $ada_info = sprintf(
                ' %s %s ADA (1 ADA = %s %s)',
                esc_html__('≈', 'adapayments-for-woocommerce'),
                number_format($ada_amount, 2),
                number_format($ada_price, 2),
                $currency
              );
          }
      }

      return $description . $ada_info;
  }

  public function get_description(): string
  {
      return $this->get_dynamic_description();
  }

  public function process_payment($order_id)
  {
    $order = wc_get_order($order_id);
    WC()->cart->empty_cart();

    $return_url = $this->get_return_url($order);

    // Legacy::process_legacy_payment does:
    //   $result->set_payment_details( array_merge( …, $gateway_result ) )
    // and PaymentResult::set_payment_details() iterates every entry and
    // casts each *value* to string — (string) $value on a nested array
    // triggers "Array to string conversion".
    //
    // So ALL values must be scalars. The JS reads
    //   paymentDetails.redirect_url
    // from the flattened response object, so include redirect_url at the
    // top level — set_payment_details will include it as a {key, value} pair
    // that WC Blocks reduces back to an object client-side.
    return array(
      'result'       => 'success',
      'redirect'     => $return_url,
      'redirect_url' => (string) $return_url,
    );
  }
  /**
   * Custom ada payment order received text.
   *
   * @since 3.9.0
   * @param string   $text Default text.
   * @param WC_Order $order Order data.
   * @return string
   */
  public function order_received_text($text, $order)
  {
    if ($order && $this->id === $order->get_payment_method()) {
      return esc_html__('Thank you for your payment. Your transaction has been completed, and a receipt for your purchase has been emailed to you.', 'adapayments-for-woocommerce');
    }

    return $text;
  }

  public function enqueue_cart_data()
  {
    if ( is_admin() ) return;

    $is_blocks  = function_exists('wc_blocks_is_checkout_page') && wc_blocks_is_checkout_page()
               || function_exists('has_block') && has_block( 'woocommerce/checkout' );
    $is_shortcode = ! $is_blocks && is_checkout() && ! is_order_received_page();
    $is_thankyou = is_order_received_page();

    if ( ! $is_blocks && ! $is_shortcode && ! $is_thankyou ) return;

    $order = null;
    if ( $is_thankyou ) {
        $order_id = absint( get_query_var( 'order-received' ) );
        $order    = wc_get_order( $order_id );
        if ( ! $order || $order->get_payment_method() !== 'ada_payment' ) return;
    }

    $settings       = get_option( 'woocommerce_ada_payment_settings' );
    $store_currency = $order ? $order->get_currency() : get_woocommerce_currency();
    $order_total    = $order ? (float) $order->get_total() : 0;
    $ada_price      = ADAPAYFWC_get_ada_price_in_currency( $store_currency, $settings );
    $ada_amount     = $ada_price > 0 ? $order_total / $ada_price : 0;

    $data = array(
        'storeAddress' => $settings['walletAddress'] ?? null,
        'adaLovelace'  => (int) round( $ada_amount * 1000000 ),
        'order_total_usd'=> $order_total,
        'ada_amount'    => number_format( $ada_amount, 2 ),
        'store_currency'=> $store_currency,
        'usd_ada_rate'  => $ada_price,
        'cart_totals'   => WC()->session ? WC()->session->get( 'cart_totals' ) : null,
        'api_endpoint'  => $this->base_api_endpoint(),
        'nonce'         => wp_create_nonce( 'wp_rest' ),
        'network_id'    => $settings && str_contains( $settings['network'], 'preview' ) ? 0 : 1,
    );

    $handle = 'ADAPAYFWC_thankyou_script';
    if ( ! wp_script_is( $handle, 'enqueued' ) && ! wp_script_is( $handle, 'done' ) ) {
        $asset_path = ADAPAYFWC_PLUGIN_DIR . 'build/index.asset.php';
        $deps       = array( 'jquery' );
        if ( file_exists( $asset_path ) ) {
            $asset = require $asset_path;
            $deps  = isset( $asset['dependencies'] ) ? array_merge( $deps, $asset['dependencies'] ) : $deps;
        }
        wp_enqueue_script( $handle, ADAPAYFWC_PLUGIN_URL . 'build/index.js', $deps, null, true );
        wp_localize_script( $handle, 'ADAPAYFWC_cart_data', $data );
    }

    $currency_symbol = html_entity_decode( get_woocommerce_currency_symbol( $store_currency ), ENT_QUOTES, 'UTF-8' );

    // --- Blocks checkout: inject ADA row into the order summary ---
    if ( $is_blocks && $ada_price > 0 ) {
        $cart_total = (float) ( WC()->session ? ( WC()->session->get( 'cart_totals' )['total'] ?? 0 ) : 0 );
        $ada_qty    = $cart_total / $ada_price;
        $rate_str   = esc_js( number_format( $ada_price, 2 ) );
        $ada_str    = esc_js( number_format( $ada_qty, 2 ) );
        $sym        = esc_js( $currency_symbol );

        add_action( 'wp_footer', function () use ( $ada_str, $rate_str, $sym, $ada_price, $cart_total ) {
            ?><script>
(function(){
    var d = typeof ADAPAYFWC_cart_data !== 'undefined' ? ADAPAYFWC_cart_data : null;
    if (!d || !d.usd_ada_rate) return;
    var rate = d.usd_ada_rate, total = (d.cart_totals && parseFloat(d.cart_totals.total)) || 0, ada = total / rate, sym = (d.cart_totals && d.cart_totals.currency_symbol) || '';

    function getPM() {
        try { if (typeof wp !== 'undefined' && wp.data) { var st = wp.data.select('wc/store/payment'); if (st && typeof st.getActivePaymentMethod === 'function') return st.getActivePaymentMethod(); } } catch(e) {}
        return 'ada_payment';
    }

    function insert() {
        var target = document.querySelector('.wc-block-components-totals-footer-item') || document.querySelector('.wc-block-components-order-summary .wc-block-components-totals-wrapper:last-child') || document.querySelector('.wc-block-checkout__order-summary .wc-block-components-totals-wrapper:last-child');
        if (!target || target.querySelector('.ada-summary-row')) return false;
        var el = document.createElement('div');
        el.className = 'ada-summary-row';
        el.style.cssText = 'display:flex;flex-direction:column;font-size:0.875em;padding:0.5em 1em;border-top:1px solid #ddd;';
        el.innerHTML = '<div>\u2248 <?php echo $ada_str; ?> ADA</div><div style="font-size:0.85em;opacity:0.7;">1 ADA = <?php echo $sym; ?> <?php echo $rate_str; ?></div>';
        el.style.display = (getPM() === 'ada_payment') ? '' : 'none';
        target.appendChild(el);
        if (typeof wp !== 'undefined' && wp.data) wp.data.subscribe(function(){ var r=document.querySelector('.ada-summary-row');if(r)r.style.display=(getPM()==='ada_payment')?'':'none'; });
        return true;
    }

    if (insert()) return;
    var mo = new MutationObserver(function(){ if (insert()) mo.disconnect(); });
    mo.observe(document.body, { childList: true, subtree: true });
    var t = 0, iv = setInterval(function(){ if (insert() || t++ > 40) clearInterval(iv); }, 250);
})();
</script><?php
        }, 100 );
    }

    // --- Shortcode checkout: register action for ADA row + jQuery toggle ---
    if ( $is_shortcode && $ada_price > 0 ) {
        add_action( 'woocommerce_review_order_after_order_total', [ $this, 'add_ada_summary_classic' ] );
        wc_enqueue_js( "
            $('form.checkout').on('change','input[name=\"payment_method\"]',function(){
                $('.ada-summary-row').toggle($(this).val()==='ada_payment');
            });
            if($('input[name=\"payment_method\"][value=\"ada_payment\"]').is(':checked'))$('.ada-summary-row').show();
        " );
    }
  }

  public function add_ada_summary_classic(): void
  {
      if ( ! WC()->cart || WC()->cart->is_empty() ) return;

      $settings       = get_option( 'woocommerce_ada_payment_settings' );
      $currency       = get_woocommerce_currency();
      $ada_price      = ADAPAYFWC_get_ada_price_in_currency( $currency, $settings );
      if ( $ada_price <= 0 ) return;

      $cart_total     = (float) WC()->cart->get_total('edit');
      $ada_qty        = $cart_total / $ada_price;
      $currency_symbol = html_entity_decode( get_woocommerce_currency_symbol( $currency ), ENT_QUOTES, 'UTF-8' );
      ?>
      <tr class="ada-summary-row" style="display:none;">
          <th><?php esc_html_e( 'Cardano (ADA)', 'adapayments-for-woocommerce' ); ?></th>
          <td>
              <div>≈ <?php echo esc_html( number_format( $ada_qty, 2 ) ); ?> ADA</div>
              <div style="font-size:0.85em;opacity:0.7;">1 ADA = <?php echo esc_html( number_format( $ada_price, 2 ) . ' ' . $currency_symbol ); ?></div>
          </td>
      </tr>
      <?php
  }

  function base_api_endpoint()
  {
    $permalink_structure = get_option('permalink_structure');

    if (!empty($permalink_structure)) {
      $api_base_url = home_url('/wp-json/adapayments-woocommerce/v1');
    } else {
      $api_base_url = home_url('?rest_route=/adapayments-woocommerce/v1');
    }

    return $api_base_url;
  }
}
