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

/**
 * Render a "CryptoDir payment" block on BOTH:
 * - HPOS order screen (new Woo UI)
 * - Legacy order screen
 */
add_action('woocommerce_admin_order_data_after_order_details', 'spg_render_cryptodir_block_any'); // legacy
add_action('woocommerce_order_edit_page_after_order_details', 'spg_render_cryptodir_block_any'); // HPOS

function spg_norm_net($net)
{
  $net = strtoupper((string)$net);
  $net = strtoupper(preg_replace('/[^A-Z0-9]/', '', $net)); // "TRC 20" => "TRC20"

  // aliases
  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';

  return $net;
}

function spg_coin_is_utxo($coin)
{
  $c = strtoupper(trim((string)$coin));
  return in_array($c, ['BTC', 'LTC', 'BCH', 'DOGE', 'DASH', 'DGB', 'MAZA', 'XVG'], true);
}

function spg_coin_is_sol($coin, $net)
{
  $c = strtoupper(trim((string)$coin));
  $n = spg_norm_net($net);
  return ($c === 'SOL' || $n === 'SOL');
}

function spg_sats_to_coin_str($sats)
{
  $sats = (int)$sats;
  $coin = number_format($sats / 100000000, 8, '.', '');
  return rtrim(rtrim($coin, '0'), '.');
}

function spg_lamports_to_sol_str($lamports)
{
  $lamports = (int)$lamports;
  $sol = number_format($lamports / 1000000000, 9, '.', '');
  return rtrim(rtrim($sol, '0'), '.');
}

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

function spg_evm_tx_explorer($net, $txid)
{
  $net = spg_norm_net($net);

  if ($net === 'BEP20')   return 'https://bscscan.com/tx/' . rawurlencode($txid);
  if ($net === 'POLYGON') return 'https://polygonscan.com/tx/' . rawurlencode($txid);
  if ($net === 'BASE')    return 'https://basescan.org/tx/' . rawurlencode($txid);

  // default ERC20
  return 'https://etherscan.io/tx/' . rawurlencode($txid);
}

function spg_evm_explorer_label($net)
{
  $net = spg_norm_net($net);
  if ($net === 'BEP20')   return __('View on BscScan', 'spg-crypto-manual');
  if ($net === 'POLYGON') return __('View on PolygonScan', 'spg-crypto-manual');
  if ($net === 'BASE')    return __('View on BaseScan', 'spg-crypto-manual');
  return __('View on Etherscan', 'spg-crypto-manual');
}

/**
 * Build Blockchair "chain slug" for UTXO coins (Blockchair-supported ones)
 */
function spg_blockchair_slug_for_utxo($coin)
{
  // ✅ FIX: remove invalid named argument syntax
  $c = strtoupper(trim((string)$coin));

  if ($c === 'BCH')  return 'bitcoin-cash';
  if ($c === 'DOGE') return 'dogecoin';
  if ($c === 'BTC')  return 'bitcoin';
  if ($c === 'LTC')  return 'litecoin';
  if ($c === 'DASH') return 'dash';
  if ($c === 'DGB')  return 'digibyte';

  // MAZA + XVG are handled with their own explorers below
  return strtolower($c);
}

/**
 * Read gateway setting: order status after payment confirmation.
 * Allowed: processing|completed. Fallback: processing
 */
function spg_get_paid_status_from_gateway(): string
{
  $status = 'processing';

  if (function_exists('WC') && WC() && WC()->payment_gateways()) {
    $gws = WC()->payment_gateways()->get_payment_gateways();
    $gw  = $gws['spg_crypto_manual'] ?? null;

    if ($gw && method_exists($gw, 'get_option')) {
      $candidate = (string) $gw->get_option('paid_order_status', 'processing');
      if (in_array($candidate, ['processing', 'completed'], true)) {
        $status = $candidate;
      }
    }
  }

  return $status;
}

function spg_render_cryptodir_block_any($order)
{
  if (is_numeric($order)) $order = wc_get_order((int)$order);
  if (!($order instanceof WC_Order)) return;

  if ($order->get_payment_method() !== 'spg_crypto_manual') {
    return;
  }

  $coin    = (string) $order->get_meta('_spg_wallet_coin');
  $net_raw = (string) $order->get_meta('_spg_wallet_network');
  $net     = spg_norm_net($net_raw);
  $addr    = (string) $order->get_meta('_spg_wallet_address');

  // --- TEMP DEBUG: run matching poller once on view (remove later) ---
  if ($net === 'TRC20' && class_exists('SPG_Tron_Poller') && method_exists('SPG_Tron_Poller', 'check_order')) {
    SPG_Tron_Poller::check_order($order->get_id());
  }
  if (spg_is_evm_net($net) && class_exists('SPG_EVM_Poller') && method_exists('SPG_EVM_Poller', 'check_order')) {
    SPG_EVM_Poller::check_order($order->get_id());
  }
  if (spg_coin_is_utxo($coin) && class_exists('SPG_UTXO_Poller') && method_exists('SPG_UTXO_Poller', 'check_order')) {
    SPG_UTXO_Poller::check_order($order->get_id());
  }
  if (spg_coin_is_sol($coin, $net_raw) && class_exists('SPG_SOL_Poller') && method_exists('SPG_SOL_Poller', 'check_order')) {
    SPG_SOL_Poller::check_order($order->get_id());
  }

  // --- Shared status ---
  $pay_status = (string) $order->get_meta('_spg_payment_status');

  // --- TRON meta ---
  $expected_micro_tron = (string) $order->get_meta('_spg_expected_usdt_micro');
  $txid_tron           = (string) $order->get_meta('_spg_tron_txid');
  $last_checked_tron   = (string) $order->get_meta('_spg_tron_last_checked');

  // --- EVM meta ---
  $expected_amount_str = (string) $order->get_meta('_spg_expected_amount_str'); // "18.00"
  $txid_evm            = (string) $order->get_meta('_spg_evm_txid');
  $last_checked_evm    = (string) $order->get_meta('_spg_evm_last_checked');

  // --- UTXO meta ---
  $utxo_expected_sats   = (string) $order->get_meta('_spg_utxo_expected_sats');
  $utxo_min_accept_sats = (string) $order->get_meta('_spg_utxo_min_accept_sats');
  $utxo_txid            = (string) $order->get_meta('_spg_utxo_txid');
  $utxo_last_checked    = (string) $order->get_meta('_spg_utxo_last_checked');
  $utxo_rate_usd        = (string) $order->get_meta('_spg_utxo_rate_usd');

  // --- SOL meta ---
  $sol_expected_lamports   = (string) $order->get_meta('_spg_sol_expected_lamports');
  $sol_min_accept_lamports = (string) $order->get_meta('_spg_sol_min_accept_lamports');
  $sol_txid                = (string) $order->get_meta('_spg_sol_txid');
  $sol_last_checked        = (string) $order->get_meta('_spg_sol_last_checked');
  $sol_rate_usd            = (string) $order->get_meta('_spg_sol_rate_usd');

  echo '<div class="order_data_column" style="width:100%;margin-top:12px;">';
  echo '<h3 style="margin:0 0 8px;">' . esc_html__('CryptoDir payment', 'spg-crypto-manual') . '</h3>';
  echo '<div style="padding:12px;border:1px solid #dcdcde;border-radius:6px;background:#fff;">';

  echo '<p style="margin:0 0 8px;"><strong>' . esc_html__('Selected:', 'spg-crypto-manual') . '</strong> ' . esc_html(trim("$coin $net_raw")) . '</p>';

  if ($addr) {
    echo '<p style="margin:0 0 8px;"><strong>' . esc_html__('Address:', 'spg-crypto-manual') . '</strong><br>';
    echo '<code style="display:block;word-break:break-all;">' . esc_html($addr) . '</code></p>';
  }

  // Expected amount display:
  if ($net === 'TRC20' && $expected_micro_tron !== '') {
    $expected = rtrim(rtrim(number_format(((int)$expected_micro_tron) / 1000000, 6, '.', ''), '0'), '.');
    echo '<p style="margin:0 0 8px;"><strong>' . esc_html__('Expected:', 'spg-crypto-manual') . '</strong> ' . esc_html($expected) . ' USDT</p>';
  } elseif (spg_is_evm_net($net) && $expected_amount_str !== '') {
    $expected_clean = rtrim(rtrim((string)$expected_amount_str, '0'), '.');
    if ($expected_clean === '') $expected_clean = (string)$expected_amount_str;
    echo '<p style="margin:0 0 8px;"><strong>' . esc_html__('Expected:', 'spg-crypto-manual') . '</strong> ' . esc_html($expected_clean) . ' ' . esc_html(strtoupper(trim($coin))) . '</p>';
  } elseif (spg_coin_is_utxo($coin) && $utxo_expected_sats !== '') {
    $expected_coin = spg_sats_to_coin_str((int)$utxo_expected_sats);
    echo '<p style="margin:0 0 8px;"><strong>' . esc_html__('Expected:', 'spg-crypto-manual') . '</strong> ' . esc_html($expected_coin) . ' ' . esc_html(strtoupper(trim($coin))) . '</p>';

    if ($utxo_min_accept_sats !== '' && (int)$utxo_min_accept_sats > 0) {
      $min_coin = spg_sats_to_coin_str((int)$utxo_min_accept_sats);
      echo '<p style="margin:-4px 0 8px;color:#666;">' . esc_html__('Min accepted:', 'spg-crypto-manual') . ' ' . esc_html($min_coin) . ' ' . esc_html(strtoupper(trim($coin))) . '</p>';
    }

    if ($utxo_rate_usd !== '') {
      echo '<p style="margin:-4px 0 8px;color:#666;">' . esc_html__('Rate used:', 'spg-crypto-manual') . ' ' . esc_html($utxo_rate_usd) . ' USD</p>';
    }
  } elseif (spg_coin_is_sol($coin, $net_raw) && $sol_expected_lamports !== '') {
    $expected_sol = spg_lamports_to_sol_str((int)$sol_expected_lamports);
    echo '<p style="margin:0 0 8px;"><strong>' . esc_html__('Expected:', 'spg-crypto-manual') . '</strong> ' . esc_html($expected_sol) . ' SOL</p>';

    if ($sol_min_accept_lamports !== '' && (int)$sol_min_accept_lamports > 0) {
      $min_sol = spg_lamports_to_sol_str((int)$sol_min_accept_lamports);
      echo '<p style="margin:-4px 0 8px;color:#666;">' . esc_html__('Min accepted:', 'spg-crypto-manual') . ' ' . esc_html($min_sol) . ' SOL</p>';
    }

    if ($sol_rate_usd !== '') {
      echo '<p style="margin:-4px 0 8px;color:#666;">' . esc_html__('Rate used:', 'spg-crypto-manual') . ' ' . esc_html($sol_rate_usd) . ' USD</p>';
    }
  }

  if ($pay_status !== '') {
    echo '<p style="margin:0 0 8px;"><strong>' . esc_html__('Tracking:', 'spg-crypto-manual') . '</strong> ' . esc_html($pay_status) . '</p>';
  }

  // TX links
  if ($net === 'TRC20' && $txid_tron !== '') {
    $scan = 'https://tronscan.org/#/transaction/' . rawurlencode($txid_tron);
    echo '<p style="margin:0 0 8px;"><strong>' . esc_html__('TXID:', 'spg-crypto-manual') . '</strong><br>';
    echo '<code style="display:block;word-break:break-all;">' . esc_html($txid_tron) . '</code> ';
    echo '<a href="' . esc_url($scan) . '" target="_blank" rel="noopener noreferrer">' . esc_html__('View on TronScan', 'spg-crypto-manual') . '</a>';
    echo '</p>';
  }

  if (spg_is_evm_net($net) && $txid_evm !== '') {
    $scan  = spg_evm_tx_explorer($net, $txid_evm);
    $label = spg_evm_explorer_label($net);

    echo '<p style="margin:0 0 8px;"><strong>' . esc_html__('TXID:', 'spg-crypto-manual') . '</strong><br>';
    echo '<code style="display:block;word-break:break-all;">' . esc_html($txid_evm) . '</code> ';
    echo '<a href="' . esc_url($scan) . '" target="_blank" rel="noopener noreferrer">' . esc_html($label) . '</a>';
    echo '</p>';
  }

  // ✅ UTXO TX links (special-case MAZA + XVG)
  if (spg_coin_is_utxo($coin) && $utxo_txid !== '') {
    $c = strtoupper(trim((string)$coin));

    if ($c === 'MAZA') {
      $scan = 'https://mazacha.in/tx/' . rawurlencode($utxo_txid);
      echo '<p style="margin:0 0 8px;"><strong>' . esc_html__('TXID:', 'spg-crypto-manual') . '</strong><br>';
      echo '<code style="display:block;word-break:break-all;">' . esc_html($utxo_txid) . '</code> ';
      echo '<a href="' . esc_url($scan) . '" target="_blank" rel="noopener noreferrer">' . esc_html__('View on Mazacha', 'spg-crypto-manual') . '</a>';
      echo '</p>';
    } elseif ($c === 'XVG') {
      $scan = 'https://verge-blockchain.info/tx/' . rawurlencode($utxo_txid);
      echo '<p style="margin:0 0 8px;"><strong>' . esc_html__('TXID:', 'spg-crypto-manual') . '</strong><br>';
      echo '<code style="display:block;word-break:break-all;">' . esc_html($utxo_txid) . '</code> ';
      echo '<a href="' . esc_url($scan) . '" target="_blank" rel="noopener noreferrer">' . esc_html__('View on Verge Explorer', 'spg-crypto-manual') . '</a>';
      echo '</p>';
    } else {
      $slug = spg_blockchair_slug_for_utxo($coin);
      $scan = 'https://blockchair.com/' . rawurlencode($slug) . '/transaction/' . rawurlencode($utxo_txid);

      echo '<p style="margin:0 0 8px;"><strong>' . esc_html__('TXID:', 'spg-crypto-manual') . '</strong><br>';
      echo '<code style="display:block;word-break:break-all;">' . esc_html($utxo_txid) . '</code> ';
      echo '<a href="' . esc_url($scan) . '" target="_blank" rel="noopener noreferrer">' . esc_html__('View on Blockchair', 'spg-crypto-manual') . '</a>';
      echo '</p>';
    }
  }

  if (spg_coin_is_sol($coin, $net_raw) && $sol_txid !== '') {
    $scan = 'https://solscan.io/tx/' . rawurlencode($sol_txid);
    echo '<p style="margin:0 0 8px;"><strong>' . esc_html__('TXID:', 'spg-crypto-manual') . '</strong><br>';
    echo '<code style="display:block;word-break:break-all;">' . esc_html($sol_txid) . '</code> ';
    echo '<a href="' . esc_url($scan) . '" target="_blank" rel="noopener noreferrer">' . esc_html__('View on Solscan', 'spg-crypto-manual') . '</a>';
    echo '</p>';
  }

  // Last checked (show the relevant one)
  if ($net === 'TRC20' && $last_checked_tron !== '') {
    $ts = (int)$last_checked_tron;
    if ($ts > 0) echo '<p style="margin:0;color:#666;">' . esc_html__('Last checked:', 'spg-crypto-manual') . ' ' . esc_html(wp_date('Y-m-d H:i:s', $ts)) . '</p>';
  } elseif (spg_is_evm_net($net) && $last_checked_evm !== '') {
    $ts = (int)$last_checked_evm;
    if ($ts > 0) echo '<p style="margin:0;color:#666;">' . esc_html__('Last checked:', 'spg-crypto-manual') . ' ' . esc_html(wp_date('Y-m-d H:i:s', $ts)) . '</p>';
  } elseif (spg_coin_is_utxo($coin) && $utxo_last_checked !== '') {
    $ts = (int)$utxo_last_checked;
    if ($ts > 0) echo '<p style="margin:0;color:#666;">' . esc_html__('Last checked:', 'spg-crypto-manual') . ' ' . esc_html(wp_date('Y-m-d H:i:s', $ts)) . '</p>';
  } elseif (spg_coin_is_sol($coin, $net_raw) && $sol_last_checked !== '') {
    $ts = (int)$sol_last_checked;
    if ($ts > 0) echo '<p style="margin:0;color:#666;">' . esc_html__('Last checked:', 'spg-crypto-manual') . ' ' . esc_html(wp_date('Y-m-d H:i:s', $ts)) . '</p>';
  }

  $paid_url = wp_nonce_url(
    admin_url('admin-post.php?action=spg_mark_paid&order_id=' . $order->get_id()),
    'spg_mark_paid_' . $order->get_id()
  );

  $cancel_url = wp_nonce_url(
    admin_url('admin-post.php?action=spg_cancel_order&order_id=' . $order->get_id()),
    'spg_cancel_' . $order->get_id()
  );

  echo '<p style="margin-top:10px;">';
  echo '<a class="button button-primary" href="' . esc_url($paid_url) . '">' . esc_html__('Mark paid', 'spg-crypto-manual') . '</a> ';
  echo '<a class="button" href="' . esc_url($cancel_url) . '">' . esc_html__('Cancel', 'spg-crypto-manual') . '</a>';
  echo '</p>';

  echo '</div>';
  echo '</div>';
}

/**
 * Admin action: Mark paid (manual verification)
 * ✅ respects paid_order_status gateway setting (processing/completed)
 */
add_action('admin_post_spg_mark_paid', function () {
  if (!current_user_can('manage_woocommerce')) {
    wp_die(esc_html__('Access denied.', 'spg-crypto-manual'));
  }

  $order_id = absint($_GET['order_id'] ?? 0);
  $nonce = isset($_GET['_wpnonce'])
    ? sanitize_text_field(wp_unslash($_GET['_wpnonce']))
    : '';

  if (!$order_id || !wp_verify_nonce($nonce, 'spg_mark_paid_' . $order_id)) {
    wp_die(esc_html__('Invalid request.', 'spg-crypto-manual'));
  }

  $order = wc_get_order($order_id);
  if ($order) {
    // mark as paid
    $order->payment_complete();
    $order->update_meta_data('_spg_payment_status', 'paid');
    $order->save();

    // apply chosen status AFTER payment_complete
    $status = spg_get_paid_status_from_gateway();
    if ($order->get_status() !== $status) {
      $order->update_status(
        $status,
        __('Manually marked paid after crypto verification.', 'spg-crypto-manual')
      );
    } else {
      $order->add_order_note(__('Manually marked paid after crypto verification.', 'spg-crypto-manual'));
    }
  }

  wp_safe_redirect(wp_get_referer() ?: admin_url('admin.php?page=wc-orders'));
  exit;
});

/**
 * Admin action: Cancel order (manual)
 */
add_action('admin_post_spg_cancel_order', function () {
  if (!current_user_can('manage_woocommerce')) {
    wp_die(esc_html__('Access denied.', 'spg-crypto-manual'));
  }

  $order_id = absint($_GET['order_id'] ?? 0);
  $nonce = isset($_GET['_wpnonce'])
    ? sanitize_text_field(wp_unslash($_GET['_wpnonce']))
    : '';

  if (!$order_id || !wp_verify_nonce($nonce, 'spg_cancel_' . $order_id)) {
    wp_die(esc_html__('Invalid request.', 'spg-crypto-manual'));
  }

  $order = wc_get_order($order_id);
  if ($order) {
    $order->update_status('cancelled', __('Manually cancelled (crypto not received).', 'spg-crypto-manual'));
  }

  wp_safe_redirect(wp_get_referer() ?: admin_url('admin.php?page=wc-orders'));
  exit;
});