<?php
if (!defined('ABSPATH'))
  exit;

class WC_Gateway_SPG_Crypto extends WC_Payment_Gateway
{
  public function is_available()
  {
    if (!parent::is_available())
      return false;

    // TEMP: licensing disabled
    return true;
  }

  /**
   * Add "Back to store" button on Thank You page (only for this gateway)
   */
  public function spg_add_back_to_store_button()
  {
    if (!function_exists('is_order_received_page') || !is_order_received_page())
      return;
    if (!function_exists('wc_get_order'))
      return;

    $order_id = absint(get_query_var('order-received'));
    if (!$order_id)
      return;

    $order = wc_get_order($order_id);
    if (!$order)
      return;

    if ($order->get_payment_method() !== $this->id)
      return;

    $shop_url = function_exists('wc_get_page_permalink')
      ? wc_get_page_permalink('shop')
      : home_url('/');

    ?>
    <script>
      (function () {
        var title = document.querySelector('.title-not-breadcrumbs .container .page-title');
        if (!title) return;

        if (document.querySelector('.spg-back-to-store')) return;

        var container = title.closest('.container');
        if (container) container.classList.add('spg-ty-title-wrap');

        var btn = document.createElement('a');
        btn.className = 'spg-back-to-store';
        btn.href = <?php echo json_encode(esc_url($shop_url)); ?>;
        btn.textContent = 'back to store';

        if (container) container.appendChild(btn);
      })();
    </script>
    <?php
  }

  private function spg_format_crypto_amount_from_usd($usd_total, $coin)
  {
    $usd_total = (float) $usd_total;
    $coin = strtoupper(trim((string) $coin));
    if ($usd_total <= 0 || $coin === '')
      return '';

    // Stablecoins (treat 1:1)
    if (in_array($coin, ['USDT', 'USDC', 'DAI', 'BUSD', 'TUSD', 'EURC'], true)) {
      return number_format($usd_total, 2, '.', '') . ' ' . $coin;
    }

    if (!class_exists('SPG_Rates'))
      return '';

    $price = (float) SPG_Rates::get_usd_price($coin);
    if ($price <= 0)
      return '';

    $amt = $usd_total / $price;

    // Format like your JS (trim trailing zeros)
    $s = number_format($amt, 8, '.', '');
    $s = rtrim(rtrim($s, '0'), '.');

    return ($s !== '' ? $s . ' ' . $coin : '');
  }

  public function spg_schedule_cancel_after_order($order_id, $posted_data, $order)
  {
    if (!($order instanceof WC_Order))
      $order = wc_get_order((int) $order_id);
    if (!$order)
      return;

    if ($order->get_payment_method() !== $this->id)
      return;
    if ($this->get_option('payment_timer_enabled', 'disabled') !== 'enabled')
      return;

    // do not reschedule if already has expires
    $expires_at = (int) $order->get_meta('_spg_timer_expires_at');
    if ($expires_at <= 0) {
      $mins = (int) $this->get_option('payment_timer_minutes', 30);
      if ($mins < 1)
        $mins = 1;
      if ($mins > 1440)
        $mins = 1440;

      $expires_at = time() + ($mins * 60);
      $order->update_meta_data('_spg_timer_expires_at', (string) $expires_at);
      $order->save();
    }

    // schedule cancel (Action Scheduler if available)
    if (function_exists('as_schedule_single_action')) {
      if (!function_exists('as_next_scheduled_action') || !as_next_scheduled_action('spg_timer_cancel_unpaid_order', [(int) $order->get_id()], 'spg-crypto')) {
        as_schedule_single_action($expires_at, 'spg_timer_cancel_unpaid_order', [(int) $order->get_id()], 'spg-crypto');
      }
    } else {
      wp_schedule_single_event($expires_at, 'spg_timer_cancel_unpaid_order', [(int) $order->get_id()]);
    }
  }

  public function __construct()
  {
    $this->id = 'spg_crypto_manual';
    $this->method_title = __('CDP', 'spg-crypto-manual');
    $this->method_description = '';
    $this->has_fields = true;

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

    // keep license key in the gateway settings array for UI
    $this->settings['license_key'] = class_exists('SPG_License')
      ? (string) get_option(SPG_License::OPT_KEY, '')
      : '';

    $this->title = $this->get_option('title');
    $this->description = $this->get_option('description');

    // Gateway icon (shown on checkout next to the title)
    $this->icon = plugin_dir_url(__FILE__) . '../assets/img/gateway-icon.png';

    // IMPORTANT: no API key inputs in admin UI (keys are in class-spg-api.php).
    $this->order_button_text = __('next', 'spg-crypto-manual');

    add_action('woocommerce_update_options_payment_gateways_' . $this->id, [$this, 'process_admin_options']);
    add_action('woocommerce_update_options_payment_gateways_' . $this->id, ['SPG_Wallets_Admin', 'save_wallets'], 20);
    add_action('wp_footer', [$this, 'spg_add_back_to_store_button'], 30);
    add_action('wp_enqueue_scripts', [$this, 'enqueue_assets']);
    add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_assets']);
    add_action('woocommerce_checkout_create_order', [$this, 'save_wallet_selection'], 20, 2);
    add_action('woocommerce_thankyou_' . $this->id, [$this, 'render_thankyou_instructions'], 20, 1);
    add_action('woocommerce_checkout_order_processed', [$this, 'spg_schedule_cancel_after_order'], 20, 3);
  }

  /**
   * ✅ FIXED: reliably enqueue admin wallets JS/CSS on WC settings screen
   * (the old $tab/$section approach sometimes fails because WC_Admin_Settings::$tab/$section is not set at enqueue time)
   */
  public function enqueue_admin_assets($hook)
  {
    if ($hook !== 'woocommerce_page_wc-settings') {
      return;
    }

    wp_enqueue_media();

    wp_enqueue_script(
      'spg-admin-wallets',
      SPG_URL . 'assets/js/admin-wallets.js',
      ['jquery'],
      SPG_VERSION,
      true
    );

    wp_enqueue_style(
      'spg-admin-wallets',
      SPG_URL . 'assets/css/admin-wallets.css',
      [],
      SPG_VERSION
    );
  }

  private function spg_qr_enabled()
  {
    return $this->get_option('qr_enabled', 'yes') === 'yes';
  }

  private function spg_qr_size_px()
  {
    $px = (int) $this->get_option('qr_size_px', 220);
    if ($px < 120)
      $px = 120;
    if ($px > 600)
      $px = 600;
    return $px;
  }

  public function render_thankyou_instructions($order_id)
  {
    $order = wc_get_order((int) $order_id);
    if (!$order)
      return;

    // safety: only for this gateway
    if ($order->get_payment_method() !== $this->id)
      return;

    // Settings
    $qr_enabled = $this->spg_qr_enabled();
    $qr_px = $this->spg_qr_size_px();

    // Order meta
    $coin = (string) $order->get_meta('_spg_wallet_coin');
    $network = (string) $order->get_meta('_spg_wallet_network');
    $address = (string) $order->get_meta('_spg_wallet_address');
    $tag = (string) $order->get_meta('_spg_wallet_tag');
    $icons_enabled = $this->spg_icons_enabled();
    $icon_url = $icons_enabled ? $this->spg_icon_url($coin, $network) : '';

    // Totals
    $total = $order->get_formatted_order_total();

    // Crypto amount estimate from USD total (falls back to '')
    $usd_total_raw = (float) $order->get_total();
    $amount_crypto = '';
    if (method_exists($this, 'spg_format_crypto_amount_from_usd')) {
      $amount_crypto = (string) $this->spg_format_crypto_amount_from_usd($usd_total_raw, $coin);
    }

    // Timer on thank-you (time until auto-cancel, if set)
    $expires_at = (int) $order->get_meta('_spg_timer_expires_at');

    // Note (decode if stored as HTML entities)
    $note_raw = (string) $this->get_option('checkout_note', '');
    $note = html_entity_decode($note_raw, ENT_QUOTES, 'UTF-8');

    // QR
    $qr = '';
    if ($qr_enabled && $address !== '' && class_exists('SPG_QR')) {
      $qr = SPG_QR::get_url($address, $coin, $network, $tag);
    }

    // Load template
    $template = trailingslashit(SPG_PATH) . 'templates/thankyou-instructions.php';
    if (!file_exists($template))
      return;

    // Variables for template
    $vars = [
      'coin' => $coin,
      'network' => $network,
      'address' => $address,
      'tag' => $tag,
      'total' => $total,
      'amount_crypto' => $amount_crypto,
      'expires_at' => $expires_at,
      'show_address' => $this->spg_show_address(),
      'icons_enabled' => $icons_enabled,
      'icon_url' => $icon_url,

      'qr' => $qr,
      'qr_enabled' => $qr_enabled,
      'qr_px' => $qr_px,

      'note' => $note,
      'order' => $order,
    ];

    extract($vars, EXTR_SKIP);
    include $template;
  }

  /**
   * Cancel unpaid order when timer expires
   */
  public function cancel_unpaid_order_timer($order_id)
  {
    $order = wc_get_order((int) $order_id);
    if (!$order)
      return;

    // Only cancel if still unpaid
    if (!$order->is_paid() && in_array($order->get_status(), ['pending', 'on-hold'])) {
      $order->update_status('cancelled', __('Payment timer expired - order automatically cancelled.', 'spg-crypto-manual'));
    }
  }

  /**
   * Admin settings fields (ONLY fields here — never echo HTML here)
   */
  public function init_form_fields()
  {
    $this->form_fields = [
      'enabled' => [
        'title' => __('Turn crypto payments on or off', 'spg-crypto-manual'),
        'type' => 'checkbox',
        'label' => __('Enable this payment method to let customers pay with crypto at checkout.', 'spg-crypto-manual'),
        'default' => 'no',
      ],

      'title' => [
        'title' => __('What customers see as the payment option name', 'spg-crypto-manual'),
        'type' => 'text',
        'default' => __('CDP fast crypto gateway', 'spg-crypto-manual'),
      ],

      'description' => [
        'title' => __('A short tip to guide customers', 'spg-crypto-manual'),
        'type' => 'textarea',
        'default' => __('e.g., “Pick your wallet, send crypto — we auto-confirm supported networks.”', 'spg-crypto-manual'),
      ],

      'wallets' => [
        'title' => __('Add wallets you’ll accept', 'spg-crypto-manual'),
        'type' => 'spg_wallets',
        'description' => __('Auto-confirmation works automatically for supported networks (like BTC, ETH, TRON).', 'spg-crypto-manual'),
      ],

      'primary_currency' => [
        'title' => __('Default currency shown first', 'spg-crypto-manual'),
        'type' => 'select',
        'default' => 'random',
        'options' => $this->get_primary_currency_options(),
        'description' => __('Pick which coin appears by default (e.g., USDT TRC20). “Random” picks any available wallet.', 'spg-crypto-manual'),
      ],

      'checkout_note' => [
        'title' => __('Custom note under wallet details', 'spg-crypto-manual'),
        'type' => 'textarea',
        'default' => '',
        'description' => __('Add helpful instructions (HTML allowed: bold, links, line breaks).', 'spg-crypto-manual'),
      ],
      'paid_order_status' => [
        'title' => __('Order status after payment confirmation', 'spg-crypto-manual'),
        'type' => 'select',
        'default' => 'processing',
        'options' => [
          'processing' => __('Processing', 'spg-crypto-manual'),
          'completed' => __('Completed', 'spg-crypto-manual'),
        ],
        'description' => __('Choose what status to set when crypto payment is confirmed automatically.', 'spg-crypto-manual'),
      ],
      'qr_enabled' => [
        'title' => __('Show QR code for easy scanning?', 'spg-crypto-manual'),
        'type' => 'select',
        'default' => 'yes',
        'options' => [
          'yes' => __('Enabled', 'spg-crypto-manual'),
          'no' => __('Disabled (show address only)', 'spg-crypto-manual'),
        ],
        'description' => __('Enabled = QR + address. Disabled = address only.', 'spg-crypto-manual'),
      ],

      'qr_size_px' => [
        'title' => __('How big should the QR code be?', 'spg-crypto-manual'),
        'type' => 'number',
        'default' => 220,
        'css' => 'width:120px;',
        'description' => __('Default: 220px — big enough to scan on phones.', 'spg-crypto-manual'),
      ],
      'show_address_with_qr' => [
        'title' => __('Always show wallet address?', 'spg-crypto-manual'),
        'type' => 'select',
        'default' => 'yes',
        'options' => [
          'yes' => __('Show address (recommended)', 'spg-crypto-manual'),
          'no' => __('Hide address (QR only)', 'spg-crypto-manual'),
        ],
        'description' => __('Recommended: Yes — gives users a fallback if QR fails.', 'spg-crypto-manual'),
      ],
      'show_coin_icons' => [
        'title' => __('Show coin icons next to currency?', 'spg-crypto-manual'),
        'type' => 'select',
        'default' => 'yes',
        'options' => [
          'yes' => __('Enabled', 'spg-crypto-manual'),
          'no' => __('Disabled', 'spg-crypto-manual'),
        ],
        'description' => __('Makes it instantly clear which crypto is selected (e.g., ₿).', 'spg-crypto-manual'),
      ],

      'payment_timer_enabled' => [
        'title' => __('Countdown timer during checkout?', 'spg-crypto-manual'),
        'type' => 'select',
        'default' => 'enabled',
        'options' => [
          'disabled' => __('Disabled', 'spg-crypto-manual'),
          'enabled' => __('Enabled', 'spg-crypto-manual'),
        ],
        'description' => __('
Enabled = shows time left to pay. When it hits 0, order cancels automatically.
', 'spg-crypto-manual'),
      ],

      'payment_timer_minutes' => [
        'title' => __('How long do customers have to pay?', 'spg-crypto-manual'),
        'type' => 'number',
        'default' => 30,
        'css' => 'width:120px;',
        'description' => __('Default: 30 minutes. Adjust based on your network speed & customer behavior.', 'spg-crypto-manual'),
      ],

      'payment_timer_html' => [
        'title' => __('Customize the HTML used to design the payment timer block shown during checkout.', 'spg-crypto-manual'),
        'type' => 'textarea',
        'default' => '<div class="mcc_payment_timer">
  <div class="timer">
    <p>Awaiting payment<br>
    <span class="timer_check_text">(checked every 15 secs)</span></p>
    <span class="hours_minutes">--:--</span>
  </div>
  <div class="paid mcc_hidden">
    <svg width="90px" height="90px" viewBox="0 0 133 133" version="1.1" xmlns="http://www.w3.org/2000/svg">
      <g id="check-group" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
        <circle id="filled-circle" fill="#78B348" cx="66.5" cy="66.5" r="54.5"></circle>
        <circle id="white-circle" fill="#FFFFFF" cx="66.5" cy="66.5" r="55.5"></circle>
        <circle id="outline" stroke="#78B348" stroke-width="4" cx="66.5" cy="66.5" r="54.5"></circle>
        <polyline id="check" stroke="#FFFFFF" stroke-width="4" points="41 70 56 85 92 49"></polyline>
      </g>
    </svg>
    <p>Payment complete!</p>
  </div>
</div>',
        'description' => __('HTML used to display the timer under the gateway description on checkout.', 'spg-crypto-manual'),
      ],
    ];
  }

  /**
   * Custom renderer: license key input + buttons INLINE
   */
  public function generate_spg_license_key_html($key, $data)
  {
    $field_key = $this->get_field_key($key);
    $value = $this->get_option($key);

    $desc = isset($data['description']) ? $data['description'] : '';
    $nonce = wp_create_nonce('spg_license_nonce');

    ob_start(); ?>
    <tr valign="top">
      <th scope="row" class="titledesc">
        <label for="<?php echo esc_attr($field_key); ?>"><?php echo esc_html($data['title'] ?? ''); ?></label>
      </th>
      <td class="forminp">
        <div style="display:flex; align-items:center; gap:8px; flex-wrap:wrap;">
          <input class="regular-text" type="text" id="<?php echo esc_attr($field_key); ?>"
            name="<?php echo esc_attr($field_key); ?>" value="<?php echo esc_attr($value); ?>"
            placeholder="DIR-1234-5678-9123-4567-1MO" />
          <button type="button" class="button button-primary"
            id="spg_license_activate"><?php echo esc_html__('activate', 'spg-crypto-manual'); ?></button>
          <button type="button" class="button"
            id="spg_license_deactivate"><?php echo esc_html__('deactivate', 'spg-crypto-manual'); ?></button>
          <input type="hidden" id="spg_license_nonce" value="<?php echo esc_attr($nonce); ?>">
        </div>

        <?php if ($desc): ?>
          <p class="description" style="margin-top:8px;"><?php echo wp_kses_post($desc); ?></p>
        <?php endif; ?>
      </td>
    </tr>
    <?php
    return ob_get_clean();
  }

  /**
   * Wallet repeater renderer (your current working one)
   */
  public function generate_spg_wallets_html($key, $data)
  {
    $wallets = spg_get_wallets();
    $catalog = function_exists('spg_currency_catalog') ? spg_currency_catalog() : [];

    ob_start(); ?>
    <tr valign="top">
      <th scope="row" class="titledesc">
        <label><?php echo esc_html($data['title'] ?? __('wallets', 'spg-crypto-manual')); ?></label>
      </th>
      <td class="forminp">

        <?php if (!empty($data['description'])): ?>
          <p class="description"><?php echo esc_html($data['description']); ?></p>
        <?php endif; ?>

        <?php
        // ✅ FIXED: required nonce for SPG_Wallets_Admin::save_wallets()
        wp_nonce_field('spg_wallets_save', 'spg_wallets_nonce');
        ?>

        <style>
          .spg-tag-wrap {
            display: none;
            margin-top: 6px;
          }

          .spg-tag-wrap input {
            width: 260px;
            max-width: 100%;
          }

          .spg-currency-select {
            min-width: 320px;
          }

          .spg-address-input {
            min-width: 420px;
          }

          .spg-wallets-table td {
            vertical-align: top;
          }
        </style>

        <table class="widefat spg-wallets-table" id="spg_wallets_table">
          <thead>
            <tr>
              <th style="width:60px;"><?php echo esc_html__('On', 'spg-crypto-manual'); ?></th>
              <th style="min-width:320px;"><?php echo esc_html__('Currency', 'spg-crypto-manual'); ?></th>
              <th><?php echo esc_html__('Wallet', 'spg-crypto-manual'); ?></th>
              <th style="width:90px;"></th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($wallets as $i => $w): ?>
              <?php
              $coin = (string) ($w['coin'] ?? '');
              $net = (string) ($w['network'] ?? '');
              $currency_key = (string) ($w['currency_key'] ?? '');

              if ($currency_key === '') {
                $currency_key = function_exists('spg_currency_guess_key')
                  ? spg_currency_guess_key($coin, $net)
                  : '__CUSTOM__';
              }

              $tag = (string) ($w['tag'] ?? '');
              $contract = (string) ($w['contract'] ?? '');
              $decimals = (string) ($w['decimals'] ?? '');

              $ck = strtoupper((string) $coin);
              $show_tag = ($ck === 'XRP' || $ck === 'XLM');
              ?>
              <tr class="spg-wallet-row" data-index="<?php echo (int) $i; ?>">
                <td>
                  <input type="checkbox" name="spg_wallets[<?php echo (int) $i; ?>][enabled]" value="1" <?php checked(!empty($w['enabled'])); ?> />
                </td>

                <td>
                  <select class="spg-currency-select" name="spg_wallets[<?php echo (int) $i; ?>][currency_key]">
                    <option value="__CUSTOM__" <?php selected($currency_key, '__CUSTOM__'); ?>>
                      <?php echo esc_html__('Custom (enter coin + choose network)', 'spg-crypto-manual'); ?>
                    </option>

                    <?php foreach ($catalog as $k2 => $row): ?>
                      <?php
                      $label = (string) ($row[0] ?? $k2);
                      $coin2 = (string) ($row[1] ?? '');
                      $net2 = (string) ($row[2] ?? '');
                      $dec2 = isset($row[3]) ? (string) $row[3] : '';
                      ?>
                      <option value="<?php echo esc_attr($k2); ?>" <?php selected($currency_key, $k2); ?>
                        data-coin="<?php echo esc_attr($coin2); ?>" data-network="<?php echo esc_attr($net2); ?>"
                        data-decimals="<?php echo esc_attr($dec2); ?>">
                        <?php echo esc_html($label); ?>
                      </option>
                    <?php endforeach; ?>
                  </select>

                  <div class="spg-custom-wrap"
                    style="<?php echo ($currency_key === '__CUSTOM__') ? '' : 'display:none;'; ?> margin-top:6px;">
                    <input type="text" class="spg-custom-coin" value="<?php echo esc_attr($coin); ?>"
                      placeholder="USDT / AAVE / ..." style="width:120px; margin-right:6px;">
                    <select class="spg-custom-net" style="width:140px;">
                      <?php
                      $nets = ['TRC20', 'ERC20', 'BEP20', 'POLYGON', 'BASE', 'BTC', 'BCH', 'LTC', 'DOGE', 'DASH', 'DGB', 'MAZA', 'XVG', 'TRX', 'XRP', 'XLM', 'SOL', 'ADA'];
                      $net_norm = strtoupper(preg_replace('/[^A-Z0-9]/', '', $net));
                      foreach ($nets as $n):
                        ?>
                        <option value="<?php echo esc_attr($n); ?>" <?php selected($net_norm, $n); ?>>
                          <?php echo esc_html($n); ?>
                        </option>
                      <?php endforeach; ?>
                    </select>
                  </div>

                  <div class="spg-tag-wrap" style="<?php echo $show_tag ? '' : 'display:none;'; ?>">
                    <label
                      style="margin:8px 0 4px;"><?php echo esc_html__('Tag / Memo (required)', 'spg-crypto-manual'); ?></label>
                    <input type="text" class="spg-tag" name="spg_wallets[<?php echo (int) $i; ?>][tag]"
                      value="<?php echo esc_attr($tag); ?>"
                      placeholder="<?php echo esc_attr($ck === 'XRP' ? 'Destination Tag' : 'Memo'); ?>" />
                  </div>

                  <!-- These are what must update when currency changes -->
                  <input type="hidden" class="spg-hidden-coin" name="spg_wallets[<?php echo (int) $i; ?>][coin]"
                    value="<?php echo esc_attr($coin); ?>">
                  <input type="hidden" class="spg-hidden-net" name="spg_wallets[<?php echo (int) $i; ?>][network]"
                    value="<?php echo esc_attr($net); ?>">
                  <input type="hidden" class="spg-adv-contract" name="spg_wallets[<?php echo (int) $i; ?>][contract]"
                    value="<?php echo esc_attr($contract); ?>">
                  <input type="hidden" class="spg-adv-decimals" name="spg_wallets[<?php echo (int) $i; ?>][decimals]"
                    value="<?php echo esc_attr($decimals); ?>">
                </td>

                <td>
                  <input type="text" class="spg-address-input" name="spg_wallets[<?php echo (int) $i; ?>][address]"
                    value="<?php echo esc_attr($w['address'] ?? ''); ?>" placeholder="Wallet address" />
                </td>

                <td>
                  <button type="button"
                    class="button-link-delete spg-remove"><?php echo esc_html__('remove', 'spg-crypto-manual'); ?></button>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>

        <p style="margin-top:10px;">
          <button type="button" class="button" id="spg_add_wallet">+
            <?php echo esc_html__('add crypto wallet', 'spg-crypto-manual'); ?></button>
        </p>

        <!-- ✅ Template for new rows -->
        <script type="text/html" id="tmpl-spg-wallet-row">
              <tr class="spg-wallet-row" data-index="{{i}}">
                <td>
                  <input type="checkbox" name="spg_wallets[{{i}}][enabled]" value="1" checked />
                </td>

                <td>
                  <select class="spg-currency-select" name="spg_wallets[{{i}}][currency_key]">
                    <option value="__CUSTOM__" selected><?php echo esc_html__('Custom (enter coin + choose network)', 'spg-crypto-manual'); ?></option>

                    <?php foreach ($catalog as $k2 => $row): ?>
                        <?php
                        $label = (string) ($row[0] ?? $k2);
                        $coin2 = (string) ($row[1] ?? '');
                        $net2 = (string) ($row[2] ?? '');
                        $dec2 = isset($row[3]) ? (string) $row[3] : '';
                        ?>
                        <option
                          value="<?php echo esc_attr($k2); ?>"
                          data-coin="<?php echo esc_attr($coin2); ?>"
                          data-network="<?php echo esc_attr($net2); ?>"
                          data-decimals="<?php echo esc_attr($dec2); ?>">
                          <?php echo esc_html($label); ?>
                        </option>
                    <?php endforeach; ?>
                  </select>

                  <div class="spg-custom-wrap" style="margin-top:6px;">
                    <input type="text" class="spg-custom-coin" value="" placeholder="USDT / AAVE / ..." style="width:120px; margin-right:6px;">
                    <select class="spg-custom-net" style="width:140px;">
                      <?php foreach (['TRC20', 'ERC20', 'BEP20', 'POLYGON', 'BASE', 'BTC', 'BCH', 'LTC', 'DOGE', 'DASH', 'DGB', 'MAZA', 'XVG', 'TRX', 'XRP', 'XLM', 'SOL', 'ADA'] as $n): ?>
                          <option value="<?php echo esc_attr($n); ?>"><?php echo esc_html($n); ?></option>
                      <?php endforeach; ?>
                    </select>
                  </div>

                  <div class="spg-tag-wrap" style="display:none; margin-top:6px;">
                    <label style="margin:8px 0 4px;"><?php echo esc_html__('Tag / Memo (required)', 'spg-crypto-manual'); ?></label>
                    <input type="text" class="spg-tag" name="spg_wallets[{{i}}][tag]" value="" placeholder="Memo / Destination Tag" />
                  </div>

                  <input type="hidden" class="spg-hidden-coin" name="spg_wallets[{{i}}][coin]" value="">
                  <input type="hidden" class="spg-hidden-net" name="spg_wallets[{{i}}][network]" value="">
                  <input type="hidden" class="spg-adv-contract" name="spg_wallets[{{i}}][contract]" value="">
                  <input type="hidden" class="spg-adv-decimals" name="spg_wallets[{{i}}][decimals]" value="">
                </td>

                <td>
                  <input type="text" class="spg-address-input" name="spg_wallets[{{i}}][address]" value="" placeholder="Wallet address" />
                </td>

                <td>
                  <button type="button" class="button-link-delete spg-remove"><?php echo esc_html__('remove', 'spg-crypto-manual'); ?></button>
                </td>
              </tr>
            </script>

      </td>
    </tr>
    <?php
    return ob_get_clean();
  }

  private function spg_icons_enabled()
  {
    return $this->get_option('show_coin_icons', 'yes') === 'yes';
  }
  public function spg_get_paid_status(): string
  {
    $status = (string) $this->get_option('paid_order_status', 'processing');

    if (!in_array($status, ['processing', 'completed'], true)) {
      $status = 'processing';
    }

    return $status;
  }
  private function spg_icon_url($coin, $network)
  {
    $coin = strtolower(trim((string) $coin));
    $net = strtolower(trim((string) $network));
    if ($coin === '' || $net === '')
      return '';

    $file = $coin . '-' . $net . '.png';
    $path = rtrim(SPG_PATH, '/\\') . '/assets/coins/' . $file;
    if (!file_exists($path))
      return '';

    return rtrim(SPG_URL, '/\\') . '/assets/coins/' . $file;
  }

  public function generate_spg_license_actions_html($key, $data)
  {
    $status = class_exists('SPG_License') ? get_option(SPG_License::OPT_STATUS, 'inactive') : 'inactive';
    $expires = class_exists('SPG_License') ? (int) get_option(SPG_License::OPT_EXPIRES, 0) : 0;
    $err = class_exists('SPG_License') ? (string) get_option(SPG_License::OPT_LAST_ERR, '') : '';

    $format_date = function ($ts) {
      if (!$ts)
        return '';
      if (function_exists('wp_date'))
        return strtoupper(wp_date('d M Y', $ts));
      return strtoupper(date_i18n('d M Y', $ts));
    };

    ob_start(); ?>
    <tr valign="top">
      <th scope="row" class="titledesc">
        <label><?php echo esc_html($data['title'] ?? __('license status', 'spg-crypto-manual')); ?></label>
      </th>
      <td class="forminp">
        <?php if ($status === 'active' && $expires > time()): ?>
          <p><strong><?php echo esc_html__('Active', 'spg-crypto-manual'); ?></strong> —
            <?php echo esc_html__('expires:', 'spg-crypto-manual'); ?>
            <?php echo esc_html($format_date($expires)); ?>
          </p>
        <?php elseif (class_exists('SPG_License')): ?>
          <?php $trial_left = (int) SPG_License::trial_seconds_left(); ?>
          <?php if ($trial_left > 0): ?>
            <?php $trial_end = time() + $trial_left; ?>
            <p><?php echo esc_html__('Your plugin trial license will end on', 'spg-crypto-manual'); ?>
              <strong><?php echo esc_html($format_date($trial_end)); ?></strong>
            </p>
          <?php endif; ?>
        <?php endif; ?>

        <?php if ($err): ?>
          <p style="color:#b00020;"><?php echo esc_html($err); ?></p>
        <?php endif; ?>

        <p class="description"><?php echo esc_html__('Activation requires an active subscription.', 'spg-crypto-manual'); ?>
        </p>
      </td>
    </tr>
    <?php
    return ob_get_clean();
  }

  public function enqueue_assets()
  {
    if (!is_checkout())
      return;

    wp_enqueue_style('spg-checkout', SPG_URL . 'assets/css/checkout.css', [], SPG_VERSION);
    wp_enqueue_script('spg-checkout', SPG_URL . 'assets/js/checkout.js', ['jquery'], SPG_VERSION, true);

    // Rates (optional)
    $rates = [];
    if (class_exists('SPG_Rates') && method_exists('SPG_Rates', 'get_all_usd_prices')) {
      $rates = SPG_Rates::get_all_usd_prices();
    }

    $qr_enabled = $this->spg_qr_enabled();
    $qr_size_px = $this->spg_qr_size_px();
    $icons_enabled = $this->spg_icons_enabled();

    $wallets = spg_get_wallets_enabled();

    foreach ($wallets as &$w) {
      $addr = (string) ($w['address'] ?? '');
      $coin = (string) ($w['coin'] ?? '');
      $net = (string) ($w['network'] ?? '');
      $tag = (string) ($w['tag'] ?? '');

      // ✅ QR (only if enabled)
      if ($qr_enabled && $addr !== '' && class_exists('SPG_QR')) {
        $w['qr'] = SPG_QR::get_url($addr, $coin, $net, $tag);
      } else {
        $w['qr'] = '';
      }

      // ✅ ICON (only if enabled)
      $w['icon'] = $icons_enabled ? $this->spg_icon_url($coin, $net) : '';
    }
    unset($w);

    wp_localize_script('spg-checkout', 'SPG_DATA', [
      'wallets' => $wallets,
      'rates_usd' => $rates,
      'primary_currency' => $this->get_option('primary_currency', 'random'),

      'qr_enabled' => $qr_enabled,
      'qr_size_px' => $qr_size_px,
      'icons_enabled' => $icons_enabled,

      // timer settings can stay even if checkout timer HTML is gone (harmless)
      'timer_enabled' => ($this->get_option('payment_timer_enabled', 'disabled') === 'enabled'),
      'timer_minutes' => (int) $this->get_option('payment_timer_minutes', 30),

      'i18n' => ['copied' => __('Copied!', 'spg-crypto-manual')],
    ]);
  }

  public function payment_fields()
  {
    $wallets = spg_get_wallets_enabled();

    echo '<div class="spg-wrap">';

    if (!empty($this->description)) {
      echo wp_kses_post(wpautop($this->description));
    }

    if (empty($wallets)) {
      echo '<p class="spg-warning">' . esc_html__('This payment method is not configured yet. Please choose another method.', 'spg-crypto-manual') . '</p>';
      echo '</div>';
      return;
    }

    $primary = (string) $this->get_option('primary_currency', 'random');
    $icons_enabled = $this->spg_icons_enabled();

    // ✅ Single label line (icon + label)
    echo '<p style="display:flex;align-items:center;gap:10px;flex-wrap:wrap;">';
    if ($icons_enabled) {
      echo '<img id="spg_coin_icon" src="" alt="" style="width:22px;height:22px;display:none;border-radius:4px;" onerror="this.style.display=\'none\';" />';
    }
    echo '<label for="spg_wallet_choice"><strong>' . esc_html__('choose crypto/network', 'spg-crypto-manual') . '</strong></label>';
    echo '</p>';

    echo '<select id="spg_wallet_choice" class="spg-wallet-select" name="spg_wallet_choice" required>';
    echo '<option value="">' . esc_html__('Select…', 'spg-crypto-manual') . '</option>';

    // ✅ extra safety: prevent duplicates
    $seen = [];

    foreach ($wallets as $w) {
      $key = trim((string) ($w['key'] ?? ''));
      $coin = trim((string) ($w['coin'] ?? ''));
      $net = trim((string) ($w['network'] ?? ''));

      if ($key === '' || $coin === '' || $net === '')
        continue;
      if (isset($seen[$key]))
        continue;
      $seen[$key] = true;

      $label = function_exists('spg_wallet_select_label')
        ? spg_wallet_select_label($coin, $net)
        : trim($coin . ' ' . $net);

      echo '<option value="' . esc_attr($key) . '" ' . selected($primary, $key, false) . '>' . esc_html($label) . '</option>';
    }

    echo '</select>';

    $note = trim((string) $this->get_option('checkout_note'));
    if ($note !== '') {
      echo '<div class="Binance_manual_payment_basic_info">' . wp_kses_post($note) . '</div>';
    }

    // wallet selection → order meta
    echo '<input type="hidden" name="spg_wallet_coin" id="spg_wallet_coin" value="" />';
    echo '<input type="hidden" name="spg_wallet_network" id="spg_wallet_network" value="" />';
    echo '<input type="hidden" name="spg_wallet_address" id="spg_wallet_address" value="" />';
    echo '<input type="hidden" name="spg_wallet_qr" id="spg_wallet_qr" value="" />';

    // EVM token metadata
    echo '<input type="hidden" name="spg_wallet_contract" id="spg_wallet_contract" value="" />';
    echo '<input type="hidden" name="spg_wallet_decimals" id="spg_wallet_decimals" value="" />';

    // XRP destination tag / XLM memo
    echo '<input type="hidden" name="spg_wallet_tag" id="spg_wallet_tag" value="" />';

    // ✅ nonce for checkout POSTs (wallet selection etc.)
    wp_nonce_field('spg_cdp_checkout', 'spg_cdp_nonce');

    echo '</div>'; // .spg-wrap
  }

  public function validate_fields()
  {
    // Only validate when THIS gateway is selected
    $pm = isset($_POST['payment_method']) ? sanitize_text_field(wp_unslash($_POST['payment_method'])) : '';
    if ($pm !== $this->id) {
      return true;
    }

    // ✅ nonce check
    $nonce = isset($_POST['spg_cdp_nonce']) ? sanitize_text_field(wp_unslash($_POST['spg_cdp_nonce'])) : '';
    if ($nonce === '' || !wp_verify_nonce($nonce, 'spg_cdp_checkout')) {
      wc_add_notice(__('Security check failed. Please refresh the page and try again.', 'spg-crypto-manual'), 'error');
      return false;
    }

    $choice = isset($_POST['spg_wallet_choice']) ? sanitize_text_field(wp_unslash($_POST['spg_wallet_choice'])) : '';
    if ($choice === '') {
      wc_add_notice(__('Please select a crypto/network.', 'spg-crypto-manual'), 'error');
      return false;
    }

    return true;
  }

  public function process_payment($order_id)
  {
    $order = wc_get_order($order_id);

    $order->update_status('on-hold', __('Awaiting crypto payment confirmation.', 'spg-crypto-manual'));

    wc_reduce_stock_levels($order_id);
    WC()->cart->empty_cart();

    return [
      'result' => 'success',
      'redirect' => $this->get_return_url($order),
    ];
  }

  // ---------- Normalizers ----------
  private function spg_norm_net($net)
  {
    $net = strtoupper((string) $net);
    $net = preg_replace('/[^A-Z0-9]/', '', $net);

    if ($net === 'ETH' || $net === 'ERC')
      $net = 'ERC20';
    if ($net === 'BSC' || $net === 'BEP')
      $net = 'BEP20';
    if ($net === 'TRON' || $net === 'TRC')
      $net = 'TRC20';
    if ($net === 'DOGECOIN')
      $net = 'DOGE';
    if ($net === 'MATIC' || $net === 'POL' || $net === 'POLYGONNETWORK' || $net === 'POLYGON')
      $net = 'POLYGON';
    if ($net === 'BASE')
      $net = 'BASE';
    if ($net === 'SOLANA')
      $net = 'SOL';
    if ($net === 'STELLAR' || $net === 'XLM')
      $net = 'XLM';
    if ($net === 'CARDANO')
      $net = 'ADA';

    return $net;
  }

  private function spg_norm_coin($coin)
  {
    $coin = strtoupper(trim((string) $coin));
    return preg_replace('/[^A-Z0-9]/', '', $coin);
  }

  private function spg_show_address()
  {
    // If QR is disabled, address MUST be shown.
    if (!$this->spg_qr_enabled())
      return true;

    // QR enabled -> follow setting
    return $this->get_option('show_address_with_qr', 'yes') === 'yes';
  }

  private function get_primary_currency_options()
  {
    $opts = ['random' => __('Random', 'spg-crypto-manual')];

    if (!function_exists('spg_get_wallets'))
      return $opts;

    $i = 0;
    foreach (spg_get_wallets() as $w) {
      if (empty($w['enabled'])) {
        $i++;
        continue;
      }

      $coin = strtolower(trim((string) ($w['coin'] ?? '')));
      $net = strtolower(trim((string) ($w['network'] ?? '')));

      // ✅ Ensure key matches checkout option values like "usdt-trc20-0"
      $key = (string) ($w['key'] ?? '');
      if ($key === '') {
        $coin_slug = preg_replace('/[^a-z0-9]+/', '-', $coin);
        $net_slug = preg_replace('/[^a-z0-9]+/', '-', $net);
        $key = trim($coin_slug, '-') . '-' . trim($net_slug, '-') . '-' . $i;
      }

      $label = function_exists('spg_wallet_select_label')
        ? spg_wallet_select_label((string) ($w['coin'] ?? ''), (string) ($w['network'] ?? ''))
        : strtoupper(trim(($w['coin'] ?? '') . ' ' . ($w['network'] ?? '')));
      if ($key && $label)
        $opts[$key] = $label;

      $i++;
    }

    return $opts;
  }

  private function spg_is_evm_net($net)
  {
    return in_array($net, ['ERC20', 'BEP20', 'POLYGON', 'BASE'], true);
  }

  private function spg_usd_to_sats($usd, $price_usd_per_coin)
  {
    $usd = (float) $usd;
    $price = (float) $price_usd_per_coin;
    if ($usd <= 0 || $price <= 0)
      return 0;

    $coin_amt = $usd / $price;
    $sats = (int) round($coin_amt * 100000000);
    return max(0, $sats);
  }

  public function save_wallet_selection($order, $data)
  {
    // Only for this gateway
    $pm = isset($_POST['payment_method']) ? sanitize_text_field(wp_unslash($_POST['payment_method'])) : '';
    if ($pm !== $this->id) {
      return;
    }

    // ✅ nonce check
    $nonce = isset($_POST['spg_cdp_nonce']) ? sanitize_text_field(wp_unslash($_POST['spg_cdp_nonce'])) : '';
    if ($nonce === '' || !wp_verify_nonce($nonce, 'spg_cdp_checkout')) {
      return;
    }

    // Safely read posted values
    $wallet_choice = isset($_POST['spg_wallet_choice']) ? sanitize_text_field(wp_unslash($_POST['spg_wallet_choice'])) : '';
    $wallet_coin = isset($_POST['spg_wallet_coin']) ? sanitize_text_field(wp_unslash($_POST['spg_wallet_coin'])) : '';
    $wallet_network = isset($_POST['spg_wallet_network']) ? sanitize_text_field(wp_unslash($_POST['spg_wallet_network'])) : '';
    $wallet_address = isset($_POST['spg_wallet_address']) ? sanitize_text_field(wp_unslash($_POST['spg_wallet_address'])) : '';
    $wallet_qr = isset($_POST['spg_wallet_qr']) ? esc_url_raw(wp_unslash($_POST['spg_wallet_qr'])) : '';
    $wallet_contract = isset($_POST['spg_wallet_contract']) ? sanitize_text_field(wp_unslash($_POST['spg_wallet_contract'])) : '';
    $wallet_decimals = isset($_POST['spg_wallet_decimals']) ? sanitize_text_field(wp_unslash($_POST['spg_wallet_decimals'])) : '';
    $wallet_tag = isset($_POST['spg_wallet_tag']) ? sanitize_text_field(wp_unslash($_POST['spg_wallet_tag'])) : '';

    // Save chosen wallet basics
    $order->update_meta_data('_spg_wallet_choice', $wallet_choice);
    $order->update_meta_data('_spg_wallet_coin', $wallet_coin);
    $order->update_meta_data('_spg_wallet_network', $wallet_network);
    $order->update_meta_data('_spg_wallet_address', $wallet_address);
    $order->update_meta_data('_spg_wallet_qr', $wallet_qr);

    // Save token metadata (optional)
    $order->update_meta_data('_spg_wallet_contract', $wallet_contract);
    $order->update_meta_data('_spg_wallet_decimals', $wallet_decimals);

    // Save tag/memo
    $order->update_meta_data('_spg_wallet_tag', $wallet_tag);

    /**
     * ✅ FIXED: these were used below without being defined
     * (this can break your poller blocks silently depending on PHP settings)
     */
    $coin = $this->spg_norm_coin($wallet_coin);
    $net = $this->spg_norm_net($wallet_network);
    $total_str = (string) $order->get_total();

    // ===== Payment timer (server-side cancel meta + schedule) =====
    if ($this->get_option('payment_timer_enabled', 'disabled') === 'enabled') {

      // If already set (e.g. retry checkout), do not overwrite
      $expires_at = (int) $order->get_meta('_spg_timer_expires_at');

      if ($expires_at <= 0) {
        $mins = (int) $this->get_option('payment_timer_minutes', 30);
        if ($mins < 1)
          $mins = 1;
        if ($mins > 1440)
          $mins = 1440;

        $expires_at = time() + ($mins * 60);
        $order->update_meta_data('_spg_timer_expires_at', (string) $expires_at);

        // ✅ ensure meta is persisted before scheduling
        $order->save();
      }

      // ✅ Schedule cancel action (avoid duplicates)
      if (function_exists('as_schedule_single_action')) {
        $args = [(int) $order->get_id()];
        $group = 'spg-crypto';

        $already = function_exists('as_next_scheduled_action')
          ? as_next_scheduled_action('spg_timer_cancel_unpaid_order', $args, $group)
          : false;

        if (!$already) {
          as_schedule_single_action($expires_at, 'spg_timer_cancel_unpaid_order', $args, $group);
        }
      } else {
        // WP-Cron fallback
        wp_schedule_single_event($expires_at, 'spg_timer_cancel_unpaid_order', [(int) $order->get_id()]);
      }
    }

    // ===== TRON USDT TRC20 =====
    if (
      $coin === 'USDT'
      && $net === 'TRC20'
      && class_exists('SPG_Tron_Poller')
      && method_exists('SPG_Tron_Poller', 'usdt_to_micro')
    ) {
      $micro = SPG_Tron_Poller::usdt_to_micro($total_str);
      $order->update_meta_data('_spg_expected_usdt_micro', (string) $micro);
      $order->update_meta_data('_spg_payment_status', 'pending');

      if (method_exists('SPG_Tron_Poller', 'schedule_order_check')) {
        SPG_Tron_Poller::schedule_order_check($order->get_id());
      }
    }

    // ===== XRP =====
    if (
      $coin === 'XRP'
      && $net === 'XRP'
      && class_exists('SPG_XRP_Poller')
      && method_exists('SPG_XRP_Poller', 'build_expected_meta')
    ) {
      $meta = SPG_XRP_Poller::build_expected_meta($total_str);
      if (!empty($meta)) {
        foreach ($meta as $k => $v)
          $order->update_meta_data($k, $v);

        $order->update_meta_data('_spg_payment_status', 'pending');
        if (method_exists('SPG_XRP_Poller', 'schedule_order_check')) {
          SPG_XRP_Poller::schedule_order_check($order->get_id());
        }
      }
    }

    // ===== EVM (tokens + native) =====
    if (
      $this->spg_is_evm_net($net)
      && class_exists('SPG_EVM_Poller')
      && method_exists('SPG_EVM_Poller', 'to_base_units_str')
    ) {
      $order->update_meta_data('_spg_expected_amount_str', $total_str);

      $contract = strtolower(trim((string) $wallet_contract));
      $decimals = (int) $wallet_decimals;

      if ($contract && strpos($contract, '0x') === 0 && strlen($contract) === 42 && $decimals > 0) {
        $order->update_meta_data('_spg_evm_net', $net);
        $order->update_meta_data('_spg_evm_coin', $coin);
        $order->update_meta_data('_spg_evm_contract', $contract);
        $order->update_meta_data('_spg_evm_decimals', (string) $decimals);

        $expected_units = SPG_EVM_Poller::to_base_units_str($total_str, $decimals);
        $order->update_meta_data('_spg_expected_token_units', (string) $expected_units);

        $order->update_meta_data('_spg_payment_status', 'pending');
        if (method_exists('SPG_EVM_Poller', 'schedule_order_check')) {
          SPG_EVM_Poller::schedule_order_check($order->get_id());
        }
      } else {
        $native_ok = (
          ($coin === 'ETH' && in_array($net, ['ERC20', 'BASE'], true)) ||
          ($coin === 'BNB' && $net === 'BEP20') ||
          ($coin === 'MATIC' && $net === 'POLYGON')
        );

        if ($native_ok && class_exists('SPG_Rates')) {
          $price = (float) SPG_Rates::get_usd_price($coin);
          $usd_total = (float) str_replace(',', '.', (string) $total_str);

          if ($price > 0 && $usd_total > 0) {
            $coin_amt = $usd_total / $price;
            $expected_wei = SPG_EVM_Poller::to_base_units_str((string) $coin_amt, 18);

            $order->update_meta_data('_spg_evm_net', $net);
            $order->update_meta_data('_spg_evm_coin', $coin);
            $order->update_meta_data('_spg_evm_rate_usd', (string) $price);
            $order->update_meta_data('_spg_evm_expected_wei', (string) $expected_wei);
            $order->update_meta_data('_spg_evm_min_accept_wei', (string) $expected_wei);

            $order->update_meta_data('_spg_payment_status', 'pending');
            if (method_exists('SPG_EVM_Poller', 'schedule_order_check')) {
              SPG_EVM_Poller::schedule_order_check($order->get_id());
            }
          }
        }
      }
    }

    // ===== SOL =====
    if (
      ($coin === 'SOL' || $net === 'SOL')
      && class_exists('SPG_SOL_Poller')
      && method_exists('SPG_SOL_Poller', 'build_expected_meta')
    ) {
      $meta = SPG_SOL_Poller::build_expected_meta($total_str);
      if (!empty($meta)) {
        foreach ($meta as $k => $v)
          $order->update_meta_data($k, $v);
        $order->update_meta_data('_spg_payment_status', 'pending');

        if (method_exists('SPG_SOL_Poller', 'schedule_order_check')) {
          SPG_SOL_Poller::schedule_order_check($order->get_id());
        }
      }
    }

    // ===== XLM =====
    if (
      ($coin === 'XLM' || $net === 'XLM')
      && class_exists('SPG_XLM_Poller')
      && method_exists('SPG_XLM_Poller', 'build_expected_meta')
    ) {
      $memo = $wallet_tag;
      if ($memo !== '') {
        $meta = SPG_XLM_Poller::build_expected_meta($total_str);
        if (!empty($meta)) {
          foreach ($meta as $k => $v)
            $order->update_meta_data($k, $v);
          $order->update_meta_data('_spg_payment_status', 'pending');

          if (method_exists('SPG_XLM_Poller', 'schedule_order_check')) {
            SPG_XLM_Poller::schedule_order_check($order->get_id());
          }
        }
      }
    }

    // ===== ADA =====
    if (
      ($coin === 'ADA' || $net === 'ADA')
      && class_exists('SPG_ADA_Poller')
      && method_exists('SPG_ADA_Poller', 'build_expected_meta')
    ) {
      $meta = SPG_ADA_Poller::build_expected_meta($total_str);
      if (!empty($meta)) {
        foreach ($meta as $k => $v)
          $order->update_meta_data($k, $v);
        $order->update_meta_data('_spg_payment_status', 'pending');

        if (method_exists('SPG_ADA_Poller', 'schedule_order_check')) {
          SPG_ADA_Poller::schedule_order_check($order->get_id());
        }
      }
    }

    // ===== UTXO FAMILY: set expected sats metas for UTXO poller =====
    if (
      in_array($coin, ['BTC', 'LTC', 'BCH', 'DOGE', 'DASH', 'DGB', 'MAZA', 'XVG'], true)
      && class_exists('SPG_Rates')
    ) {
      $usd_total = (float) str_replace(',', '.', (string) $total_str);
      $price = (float) SPG_Rates::get_usd_price($coin);

      if ($usd_total > 0 && $price > 0) {
        $expected_sats = $this->spg_usd_to_sats($usd_total, $price);

        $tol_usd = min(0.50, $usd_total * 0.005);
        $tol_sats = $this->spg_usd_to_sats($tol_usd, $price);

        $min_accept_sats = max(0, $expected_sats - $tol_sats);

        $order->update_meta_data('_spg_utxo_coin', $coin);
        $order->update_meta_data('_spg_utxo_expected_sats', (string) $expected_sats);
        $order->update_meta_data('_spg_utxo_min_accept_sats', (string) $min_accept_sats);
        $order->update_meta_data('_spg_payment_status', 'pending');
      }
    }
  }
}