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

class SPG_Wallets_Admin
{

  const OPTION_NAME = 'spg_wallets';

  public static function init(): void
  {
    add_action('admin_enqueue_scripts', [__CLASS__, 'enqueue_admin_assets']);
  }

  public static function enqueue_admin_assets(string $hook): void
  {
    if (strpos($hook, 'wc-settings') === false)
      return;

    // Only load on gateway section to avoid loading everywhere
    $section = '';

    if (class_exists('WC_Admin_Settings')) {
      $section = isset(WC_Admin_Settings::$section) ? (string) WC_Admin_Settings::$section : '';
    }
    if ($section !== 'spg_crypto_manual')
      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
    );
  }

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

  private static function norm_net(string $net): string
  {
    $net = strtoupper(trim($net));
    $net = preg_replace('/[^A-Z0-9]/', '', $net);

    // keep consistent with your gateway normalizer
    if ($net === 'ETH' || $net === 'ERC')
      $net = 'ERC20';
    if ($net === 'BSC' || $net === 'BEP')
      $net = 'BEP20';
    if ($net === 'TRON' || $net === 'TRC')
      $net = 'TRC20';
    if ($net === 'MATIC' || $net === 'POL' || $net === 'POLYGONNETWORK' || $net === 'POLYGON')
      $net = 'POLYGON';
    if ($net === 'SOLANA')
      $net = 'SOL';
    if ($net === 'STELLAR')
      $net = 'XLM';
    if ($net === 'CARDANO')
      $net = 'ADA';

    return $net;
  }

  /**
   * Save wallets table from gateway settings page.
   * Supports:
   * - currency_key (dropdown)
   * - tag/memo (XRP/XLM)
   * - contract/decimals (EVM tokens)
   */
public static function save_wallets(): void
{
  // ✅ Nonce
  $nonce = isset($_POST['spg_wallets_nonce']) ? sanitize_text_field(wp_unslash($_POST['spg_wallets_nonce'])) : '';
  if ($nonce === '' || ! wp_verify_nonce($nonce, 'spg_wallets_save')) {
    wp_die(esc_html__('Security check failed.', 'spg-crypto-manual'));
  }

  // ✅ Read + sanitize immediately
  $raw = [];
  if (isset($_POST['spg_wallets'])) {
    // We sanitize immediately below (wc_clean on the full array)
    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
    $raw = wc_clean(wp_unslash($_POST['spg_wallets']));
  }
  $raw = is_array($raw) ? $raw : [];

  $out = [];
  $idx = 0;

  foreach ($raw as $row) {
    if (!is_array($row)) {
      continue;
    }

    $currency_key = isset($row['currency_key']) ? sanitize_text_field((string) $row['currency_key']) : '';
    $currency_key = strtoupper(preg_replace('/[^A-Z0-9_]/', '', $currency_key));

    $coin = isset($row['coin']) ? sanitize_text_field((string) $row['coin']) : '';
    $net  = isset($row['network']) ? sanitize_text_field((string) $row['network']) : '';

    $addr = isset($row['address']) ? sanitize_text_field((string) $row['address']) : '';
    $qr   = isset($row['qr']) ? esc_url_raw((string) $row['qr']) : '';
    $note = isset($row['note']) ? sanitize_textarea_field((string) $row['note']) : '';
    $en   = !empty($row['enabled']) ? 1 : 0;

    $tag = isset($row['tag']) ? sanitize_text_field((string) $row['tag']) : '';

    $contract = isset($row['contract']) ? sanitize_text_field((string) $row['contract']) : '';
    $contract = strtolower(trim($contract));
    $decimals = isset($row['decimals']) ? (int) $row['decimals'] : 0;

    $coin = self::norm_coin($coin);
    $net  = self::norm_net($net);

    if (($coin === '' || $net === '') && $currency_key !== '' && $currency_key !== '__CUSTOM__') {
      if (function_exists('spg_currency_meta')) {
        $meta = spg_currency_meta($currency_key);
        if (is_array($meta) && isset($meta[1], $meta[2])) {
          $coin = self::norm_coin((string) $meta[1]);
          $net  = self::norm_net((string) $meta[2]);

          if ($decimals <= 0 && isset($meta[3]) && $meta[3] !== null) {
            $decimals = (int) $meta[3];
          }
        }
      }
    }

    if ($coin === '' || $addr === '') {
      continue;
    }

    if ($decimals < 0)  $decimals = 0;
    if ($decimals > 30) $decimals = 30;

    if ($contract !== '' && !preg_match('/^0x[a-f0-9]{40}$/', $contract)) {
      $contract = '';
    }
    if ($contract === '') {
      $decimals = 0;
    }

    $key = sanitize_title($coin . '-' . $net . '-' . $idx);

    $out[] = [
      'key'          => $key,
      'enabled'      => $en,
      'currency_key' => $currency_key,
      'coin'         => $coin,
      'network'      => $net,
      'address'      => $addr,
      'tag'          => $tag,
      'qr'           => $qr,
      'note'         => $note,
      'contract'     => $contract,
      'decimals'     => $decimals,
    ];

    $idx++;
  }

  update_option(self::OPTION_NAME, $out);
}
}

SPG_Wallets_Admin::init();
