<?php
defined( 'ABSPATH' ) || exit;

$tab     = isset( $_GET['tab'] ) ? sanitize_key( $_GET['tab'] ) : 'general';
$lic     = ChainPay_License::summary();
$all_c   = ChainPay_Coin_Registry::all();
$enabled = (array) get_option( 'chainpay_enabled_coins', array( 'BTC', 'LTC' ) );
$stats   = ChainPay_Invoice::stats();

$used     = (int) $lic['monthly_count'];
$limit    = $lic['is_pro'] ? PHP_INT_MAX : CHAINPAY_FREE_LIMIT;
$pct      = $lic['is_pro'] ? 0 : min( 100, round( $used / CHAINPAY_FREE_LIMIT * 100 ) );
$over     = ! $lic['is_pro'] && $used >= CHAINPAY_FREE_LIMIT;
?>
<div class="cp-wrap">

  <!-- Header -->
  <div class="cp-header">
    <div class="cp-logo">&#9889;</div>
    <div>
      <div class="cp-header-title">ChainPay &nbsp;<span style="font-weight:400;color:#9ca3af;font-size:14px;">v<?php echo esc_html( CHAINPAY_VERSION ); ?></span></div>
      <div class="cp-header-sub"><a href="https://chainpay.store" target="_blank" style="color:#9ca3af;">chainpay.store</a> &nbsp;&middot;&nbsp; <a href="https://chainpay.store/docs" target="_blank" style="color:#9ca3af;">Docs</a> &nbsp;&middot;&nbsp; <a href="https://chainpay.store/contact" target="_blank" style="color:#9ca3af;">Support</a></div>
    </div>

    <!-- Usage meter -->
    <div style="flex:1;max-width:280px;">
      <?php if ( $lic['is_pro'] ) : ?>
        <div style="display:flex;align-items:center;gap:8px;">
          <span style="background:#059669;color:#fff;border-radius:6px;padding:3px 10px;font-size:11px;font-weight:800;">&#9889; PRO — Unlimited</span>
          <span style="font-size:11px;color:#9ca3af;"><?php echo esc_html( number_format( $used ) ); ?> payments this month</span>
        </div>
      <?php else : ?>
        <div style="font-size:11px;font-weight:700;color:<?php echo $over ? '#dc2626' : '#374151'; ?>;margin-bottom:5px;">
          <?php echo esc_html( $used ); ?> / <?php echo esc_html( CHAINPAY_FREE_LIMIT ); ?> free payments used this month
          <?php if ( $over ) : ?><span style="color:#dc2626;"> — LIMIT REACHED</span><?php endif; ?>
        </div>
        <div style="background:#e5e7eb;border-radius:20px;height:8px;overflow:hidden;">
          <div style="height:100%;border-radius:20px;width:<?php echo esc_attr( $pct ); ?>%;background:<?php echo $over ? '#dc2626' : ( $pct > 80 ? '#f59e0b' : '#ff6b2b' ); ?>;transition:width .5s;"></div>
        </div>
        <div style="margin-top:4px;font-size:10px;color:#9ca3af;"><?php echo esc_html( max( 0, CHAINPAY_FREE_LIMIT - $used ) ); ?> remaining &nbsp;&middot;&nbsp; <a href="<?php echo esc_url( admin_url( 'admin.php?page=chainpay&tab=license' ) ); ?>" style="color:#ff6b2b;font-weight:700;">Upgrade to Pro →</a></div>
      <?php endif; ?>
    </div>

    <span class="cp-header-badge <?php echo $lic['is_pro'] ? 'pro' : ''; ?>">
      <?php echo $lic['is_pro'] ? '&#128274; Pro Active' : '&#128513; Free Plan'; ?>
    </span>
  </div>

  <!-- Over-limit warning banner -->
  <?php if ( $over ) : ?>
  <div style="background:#fef2f2;border:1.5px solid #fecaca;border-radius:10px;padding:13px 16px;margin-bottom:16px;display:flex;align-items:center;gap:10px;">
    <span style="font-size:18px;">&#9888;&#65039;</span>
    <div style="flex:1;">
      <strong style="color:#dc2626;">Payment limit reached!</strong>
      <span style="font-size:13px;color:#991b1b;"> Customers cannot complete crypto payments until you upgrade or wait for next month's reset.</span>
    </div>
    <a href="<?php echo esc_url( admin_url( 'admin.php?page=chainpay&tab=license' ) ); ?>" style="background:#dc2626;color:#fff;border-radius:8px;padding:8px 16px;font-size:12px;font-weight:800;text-decoration:none;">Upgrade Now →</a>
  </div>
  <?php endif; ?>

  <!-- Tabs -->
  <div class="cp-tabs-nav">
    <?php
    $tabs = array(
      'general'  => '&#9881; General',
      'license'  => '&#128274; License',
      'coins'    => '&#129689; Coins',
      'wallets'  => '&#128188; Wallets / xPub',
      'invoices' => '&#128203; Invoices',
      'logs'     => '&#128202; Stats',
    );
    foreach ( $tabs as $t_key => $t_label ) :
      $url = admin_url( 'admin.php?page=chainpay&tab=' . $t_key );
    ?>
    <a href="<?php echo esc_url( $url ); ?>" class="cp-tab-link<?php echo $tab === $t_key ? ' active' : ''; ?>">
      <?php echo $t_label; ?>
    </a>
    <?php endforeach; ?>
  </div>

  <div class="cp-notice" id="cp-save-msg" style="display:none;"></div>

  <!-- ═══ GENERAL ══════════════════════════════════════════════ -->
  <?php if ( 'general' === $tab ) : ?>

  <div class="cp-section">
    <div class="cp-section-title">API Connection</div>
    <div class="cp-section-sub">Connect to your <a href="https://chainpay.store/dashboard" target="_blank">chainpay.store</a> account for address derivation and price feeds.</div>
    <div class="cp-grid">
      <div class="cp-field">
        <label class="cp-label">API Key</label>
        <input class="cp-input cp-mono" type="password" name="chainpay_api_key" value="<?php echo esc_attr( (string) get_option( 'chainpay_api_key', '' ) ); ?>" placeholder="cp_live_…" autocomplete="off">
        <div class="cp-help">Get from <a href="https://chainpay.store/dashboard" target="_blank">chainpay.store → Dashboard → API Keys</a></div>
      </div>
      <div class="cp-field">
        <label class="cp-label">Mode</label>
        <select class="cp-select" name="chainpay_api_mode">
          <option value="live"<?php selected( get_option( 'chainpay_api_mode', 'live' ), 'live' ); ?>>&#128994; Live</option>
          <option value="test"<?php selected( get_option( 'chainpay_api_mode' ), 'test' ); ?>>&#128993; Test / Sandbox</option>
        </select>
      </div>
    </div>
    <button type="button" id="cp-refresh-prices" class="cp-btn cp-btn-secondary cp-btn-sm">&#8635; Refresh Prices</button>
    <span class="cp-notice" id="cp-prices-msg" style="display:none;margin-left:8px;"></span>
  </div>

  <div class="cp-section">
    <div class="cp-section-title">Invoice Settings</div>
    <div class="cp-grid">
      <div class="cp-field">
        <label class="cp-label">Invoice Timeout (minutes)</label>
        <input class="cp-input" type="number" name="chainpay_invoice_timeout" value="<?php echo esc_attr( (string) get_option( 'chainpay_invoice_timeout', 15 ) ); ?>" min="5" max="120">
        <div class="cp-help">How long customers have to pay. 15 minutes recommended.</div>
      </div>
      <div class="cp-field">
        <label class="cp-label">Underpayment Tolerance (%)</label>
        <input class="cp-input" type="number" name="chainpay_underpayment_pct" value="<?php echo esc_attr( (string) get_option( 'chainpay_underpayment_pct', 1 ) ); ?>" min="0" max="10" step="0.1">
        <div class="cp-help">Accept payments within this % of expected. 1% covers small fee fluctuations.</div>
      </div>
    </div>
    <div class="cp-grid-3">
      <div class="cp-field">
        <label class="cp-label">Status: Confirmed</label>
        <select class="cp-select" name="chainpay_confirmed_status">
          <?php foreach ( array( 'processing', 'completed', 'on-hold' ) as $s ) : ?>
          <option value="<?php echo esc_attr( $s ); ?>"<?php selected( get_option( 'chainpay_confirmed_status', 'processing' ), $s ); ?>><?php echo ucfirst( $s ); ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="cp-field">
        <label class="cp-label">Status: Pending / Detected</label>
        <select class="cp-select" name="chainpay_pending_status">
          <?php foreach ( array( 'on-hold', 'pending', 'processing' ) as $s ) : ?>
          <option value="<?php echo esc_attr( $s ); ?>"<?php selected( get_option( 'chainpay_pending_status', 'on-hold' ), $s ); ?>><?php echo ucfirst( $s ); ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="cp-field">
        <label class="cp-label">Status: Expired</label>
        <select class="cp-select" name="chainpay_expired_status">
          <?php foreach ( array( 'cancelled', 'failed', 'on-hold' ) as $s ) : ?>
          <option value="<?php echo esc_attr( $s ); ?>"<?php selected( get_option( 'chainpay_expired_status', 'cancelled' ), $s ); ?>><?php echo ucfirst( $s ); ?></option>
          <?php endforeach; ?>
        </select>
      </div>
    </div>
  </div>

  <div class="cp-section">
    <div class="cp-section-title">Checkout Display</div>
    <div class="cp-toggle-row"><div><div class="cp-toggle-label">Show QR Code</div><div class="cp-toggle-desc">Display scannable QR at checkout</div></div><label class="cp-switch"><input type="checkbox" name="chainpay_show_qr"<?php checked( get_option( 'chainpay_show_qr', 'yes' ), 'yes' ); ?>><span class="cp-slider"></span></label></div>
    <div class="cp-toggle-row"><div><div class="cp-toggle-label">Show Countdown Timer</div><div class="cp-toggle-desc">Invoice expiry countdown</div></div><label class="cp-switch"><input type="checkbox" name="chainpay_show_timer"<?php checked( get_option( 'chainpay_show_timer', 'yes' ), 'yes' ); ?>><span class="cp-slider"></span></label></div>
    <div class="cp-toggle-row"><div><div class="cp-toggle-label">Show Exchange Rate</div><div class="cp-toggle-desc">Show 1 BTC = $XX,XXX</div></div><label class="cp-switch"><input type="checkbox" name="chainpay_show_rate"<?php checked( get_option( 'chainpay_show_rate', 'yes' ), 'yes' ); ?>><span class="cp-slider"></span></label></div>
    <div class="cp-toggle-row"><div><div class="cp-toggle-label">Show Recommended Fee</div><div class="cp-toggle-desc">Network fee recommendation</div></div><label class="cp-switch"><input type="checkbox" name="chainpay_show_fee"<?php checked( get_option( 'chainpay_show_fee', 'yes' ), 'yes' ); ?>><span class="cp-slider"></span></label></div>
  </div>

  <div class="cp-section">
    <div class="cp-section-title">Email Notifications</div>
    <div class="cp-toggle-row"><div><div class="cp-toggle-label">Payment Confirmed (customer)</div><div class="cp-toggle-desc">Email customer when payment confirmed on-chain</div></div><label class="cp-switch"><input type="checkbox" name="chainpay_email_on_confirmed"<?php checked( get_option( 'chainpay_email_on_confirmed', 'yes' ), 'yes' ); ?>><span class="cp-slider"></span></label></div>
    <div class="cp-toggle-row"><div><div class="cp-toggle-label">Payment Detected (customer)</div><div class="cp-toggle-desc">Email when payment seen on-chain (unconfirmed)</div></div><label class="cp-switch"><input type="checkbox" name="chainpay_email_on_detected"<?php checked( get_option( 'chainpay_email_on_detected', 'yes' ), 'yes' ); ?>><span class="cp-slider"></span></label></div>
    <div class="cp-toggle-row"><div><div class="cp-toggle-label">Underpayment Notice</div><div class="cp-toggle-desc">Email customer when they underpay</div></div><label class="cp-switch"><input type="checkbox" name="chainpay_underpayment_email"<?php checked( get_option( 'chainpay_underpayment_email', 'yes' ), 'yes' ); ?>><span class="cp-slider"></span></label></div>
    <div class="cp-toggle-row"><div><div class="cp-toggle-label">Admin Copy on Confirmation</div><div class="cp-toggle-desc">Send confirmation to admin email</div></div><label class="cp-switch"><input type="checkbox" name="chainpay_admin_email_on_confirmed"<?php checked( get_option( 'chainpay_admin_email_on_confirmed', 'yes' ), 'yes' ); ?>><span class="cp-slider"></span></label></div>
  </div>

  <div class="cp-section">
    <div class="cp-section-title">Smart Routing <span class="cp-badge cp-badge-orange" style="font-size:10px;margin-left:6px;">Pro</span></div>
    <div class="cp-section-sub">Automatically hide high-fee coins (ETH/ERC-20) when network fees are high. Requires Pro license.</div>
    <div class="cp-toggle-row"><div><div class="cp-toggle-label">Enable Smart Routing</div><div class="cp-toggle-desc">Hide ERC-20 coins when gas > threshold</div></div><label class="cp-switch" style="<?php echo ! $lic['is_pro'] ? 'opacity:.5;pointer-events:none;' : ''; ?>"><input type="checkbox" name="chainpay_smart_routing"<?php checked( get_option( 'chainpay_smart_routing', 'yes' ), 'yes' ); ?><?php echo ! $lic['is_pro'] ? ' disabled' : ''; ?>><span class="cp-slider"></span></label></div>
    <div class="cp-field" style="margin-top:10px;max-width:240px;">
      <label class="cp-label">ETH Gas Threshold (USD)</label>
      <input class="cp-input" type="number" name="chainpay_eth_fee_threshold" value="<?php echo esc_attr( (string) get_option( 'chainpay_eth_fee_threshold', 30 ) ); ?>" min="0" max="200">
    </div>
  </div>

  <div class="cp-section">
    <div class="cp-section-title">Webhook / IPN</div>
    <div class="cp-field">
      <label class="cp-label">Your IPN Endpoint (add to chainpay.store)</label>
      <div class="cp-copy-row"><div class="cp-copy-val"><?php echo esc_html( home_url( '/chainpay-ipn/' ) ); ?></div><button type="button" class="cp-copy-btn">Copy</button></div>
    </div>
    <div class="cp-field">
      <label class="cp-label">Webhook Secret (HMAC verification)</label>
      <input class="cp-input cp-mono" type="password" name="chainpay_webhook_secret" value="<?php echo esc_attr( (string) get_option( 'chainpay_webhook_secret', '' ) ); ?>" placeholder="wsk_…">
    </div>
  </div>

  <button type="button" class="cp-btn cp-btn-primary cp-save-btn" data-tab="general">&#10003; Save Settings</button>

  <!-- ═══ LICENSE ═══════════════════════════════════════════════ -->
  <?php elseif ( 'license' === $tab ) : ?>

  <!-- Current status card -->
  <div class="cp-section">
    <div class="cp-lic-card">
      <div class="cp-lic-icon" style="background:<?php echo $lic['is_pro'] ? 'rgba(5,150,105,.1)' : 'rgba(107,114,128,.08)'; ?>;">
        <?php echo $lic['is_pro'] ? '&#128274;' : '&#128513;'; ?>
      </div>
      <div class="cp-lic-info">
        <div class="cp-lic-status" style="color:<?php echo $lic['is_pro'] ? '#059669' : '#374151'; ?>;">
          <?php echo $lic['is_pro'] ? 'Pro License &#10003; Active' : 'Free Plan'; ?>
        </div>
        <div class="cp-lic-detail">
          <?php if ( $lic['is_pro'] ) : ?>
            Plan: <?php echo esc_html( ucfirst( $lic['plan'] ) ); ?> &nbsp;&middot;&nbsp;
            Domain: <code style="font-size:11px;"><?php echo esc_html( $lic['domain'] ?: home_url() ); ?></code> &nbsp;&middot;&nbsp;
            Expires: <?php echo esc_html( $lic['expires'] ?: 'Never' ); ?>
            <br>Key: <code style="font-size:10px;"><?php echo esc_html( $lic['key'] ); ?></code>
          <?php else : ?>
            BTC + LTC only &nbsp;&middot;&nbsp; <?php echo esc_html( $used ); ?>/<?php echo esc_html( CHAINPAY_FREE_LIMIT ); ?> payments used this month
          <?php endif; ?>
        </div>
      </div>
      <?php if ( $lic['is_pro'] ) : ?>
        <button id="cp-license-revoke" class="cp-btn cp-btn-danger cp-btn-sm">Deactivate License</button>
      <?php endif; ?>
    </div>
  </div>

  <!-- Usage meter (for both plans) -->
  <div class="cp-section">
    <div class="cp-section-title">Monthly Usage</div>
    <?php if ( $lic['is_pro'] ) : ?>
      <div style="display:flex;align-items:center;gap:12px;padding:10px 0;">
        <div style="font-size:28px;font-weight:900;color:#059669;font-family:var(--cp-mono, monospace);"><?php echo esc_html( number_format( $used ) ); ?></div>
        <div style="color:#9ca3af;font-size:13px;">payments this month &nbsp;·&nbsp; <strong style="color:#059669;">Unlimited &#9889;</strong></div>
      </div>
    <?php else : ?>
      <div style="display:flex;justify-content:space-between;margin-bottom:6px;font-size:13px;">
        <span style="font-weight:700;color:<?php echo $over ? '#dc2626' : 'var(--cp-ink,#111)'; ?>;">
          <?php echo esc_html( $used ); ?> / <?php echo esc_html( CHAINPAY_FREE_LIMIT ); ?> payments used
        </span>
        <span style="color:#9ca3af;"><?php echo esc_html( max( 0, CHAINPAY_FREE_LIMIT - $used ) ); ?> remaining</span>
      </div>
      <div style="background:#e5e7eb;border-radius:20px;height:12px;overflow:hidden;margin-bottom:8px;">
        <div style="height:100%;border-radius:20px;width:<?php echo esc_attr( $pct ); ?>%;background:<?php echo $over ? '#dc2626' : ( $pct > 80 ? '#f59e0b' : '#ff6b2b' ); ?>;transition:width .5s;"></div>
      </div>
      <div style="font-size:12px;color:#9ca3af;">Resets on <?php echo esc_html( gmdate( 'M 1', mktime( 0, 0, 0, (int) gmdate('m') + 1, 1 ) ) ); ?></div>
    <?php endif; ?>
  </div>

  <!-- Activate form (only for free plan) -->
  <div class="cp-notice" id="cp-license-msg" style="display:none;"></div>

  <?php if ( ! $lic['is_pro'] ) : ?>
  <div class="cp-section">
    <div class="cp-section-title">Activate Pro License</div>
    <div class="cp-section-sub">
      Enter your license key from <a href="https://chainpay.store/pricing" target="_blank">chainpay.store/pricing</a>.
      Each key is <strong>domain-locked</strong> — it will be bound to <code style="font-size:11px;"><?php echo esc_html( home_url() ); ?></code> on activation.
    </div>
    <div style="display:flex;gap:10px;align-items:flex-end;">
      <div class="cp-field" style="flex:1;margin-bottom:0;">
        <label class="cp-label">License Key</label>
        <input class="cp-input cp-mono" type="text" id="cp-license-key-input" placeholder="cp_lic_xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" autocomplete="off">
      </div>
      <button id="cp-license-verify" class="cp-btn cp-btn-primary" style="white-space:nowrap;">&#10003; Activate</button>
    </div>
    <div style="margin-top:10px;display:flex;gap:10px;align-items:center;">
      <a href="https://chainpay.store/pricing" target="_blank" class="cp-btn cp-btn-secondary" style="text-decoration:none;">Buy Pro &mdash; $49/yr &rarr;</a>
      <span style="font-size:12px;color:#9ca3af;">&#128274; Domain-locked to this site &nbsp;&middot;&nbsp; &#128257; 30-day money back</span>
    </div>
  </div>
  <?php endif; ?>

  <!-- Plan comparison -->
  <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:14px;margin-top:4px;">
    <?php
    $plans = array(
      array( 'name' => 'Free', 'price' => '$0', 'sub' => 'forever', 'color' => '#374151', 'badge_class' => 'cp-badge-gray', 'feats' => array(
        array( true,  'Bitcoin (BTC)' ),
        array( true,  'Litecoin (LTC)' ),
        array( true,  'xPub HD wallet derivation' ),
        array( true,  '50 payments / month' ),
        array( false, 'Unlimited payments' ),
        array( false, '12 extra coins' ),
        array( false, 'Smart routing' ),
        array( false, 'Webhooks' ),
        array( false, 'Domain-locked license' ),
      ) ),
      array( 'name' => 'Pro', 'price' => '$49', 'sub' => '/year', 'color' => '#ff6b2b', 'badge_class' => 'cp-badge-orange', 'highlight' => true, 'feats' => array(
        array( true, 'All 14 cryptocurrencies' ),
        array( true, 'Unlimited payments' ),
        array( true, '0.25% platform fee' ),
        array( true, 'Domain-locked license' ),
        array( true, 'Smart coin routing' ),
        array( true, 'Webhook IPN' ),
        array( true, 'Full API access' ),
        array( true, 'Priority support' ),
        array( true, '30-day money-back' ),
      ) ),
      array( 'name' => 'Enterprise', 'price' => 'Custom', 'sub' => 'talk to us', 'color' => '#f59e0b', 'badge_class' => 'cp-badge-gold', 'feats' => array(
        array( true, 'Everything in Pro' ),
        array( true, 'White-label checkout' ),
        array( true, 'Multi-store management' ),
        array( true, 'SLA guarantee' ),
        array( true, 'Dedicated account manager' ),
        array( true, 'Volume fee discounts' ),
      ) ),
    );
    foreach ( $plans as $p ) :
      $border = ! empty( $p['highlight'] ) ? '2px solid #ff6b2b' : '1.5px solid #e5e7eb';
    ?>
    <div class="cp-section" style="border:<?php echo esc_attr( $border ); ?>;position:relative;">
      <?php if ( ! empty( $p['highlight'] ) ) : ?>
      <div style="position:absolute;top:-12px;left:50%;transform:translateX(-50%);background:#ff6b2b;color:#fff;border-radius:20px;padding:3px 14px;font-size:10px;font-weight:800;white-space:nowrap;">Most Popular</div>
      <?php endif; ?>
      <div style="margin-bottom:10px;"><span class="cp-badge <?php echo esc_attr( $p['badge_class'] ); ?>"><?php echo esc_html( $p['name'] ); ?></span></div>
      <div style="font-size:24px;font-weight:900;color:<?php echo esc_attr( $p['color'] ); ?>;margin-bottom:2px;"><?php echo esc_html( $p['price'] ); ?><span style="font-size:13px;color:#9ca3af;font-weight:400;"><?php echo esc_html( $p['sub'] ); ?></span></div>
      <div style="margin-top:12px;display:flex;flex-direction:column;gap:6px;font-size:12px;">
        <?php foreach ( $p['feats'] as $f ) : ?>
        <div style="display:flex;align-items:center;gap:6px;color:<?php echo $f[0] ? '#374151' : '#d1d5db'; ?>;">
          <span style="flex-shrink:0;"><?php echo $f[0] ? '&#10003;' : '&#10007;'; ?></span>
          <?php echo esc_html( $f[1] ); ?>
        </div>
        <?php endforeach; ?>
      </div>
      <?php if ( 'Pro' === $p['name'] && ! $lic['is_pro'] ) : ?>
        <a href="https://chainpay.store/pricing" target="_blank" class="cp-btn cp-btn-primary" style="display:block;text-align:center;margin-top:14px;text-decoration:none;">Get Pro &rarr;</a>
      <?php elseif ( 'Enterprise' === $p['name'] ) : ?>
        <a href="https://chainpay.store/contact" target="_blank" class="cp-btn cp-btn-secondary" style="display:block;text-align:center;margin-top:14px;text-decoration:none;">Contact Sales &rarr;</a>
      <?php endif; ?>
    </div>
    <?php endforeach; ?>
  </div>

  <!-- ═══ COINS ═══════════════════════════════════════════════ -->
  <?php elseif ( 'coins' === $tab ) : ?>

  <?php if ( ! $lic['is_pro'] ) : ?>
  <div class="cp-notice cp-notice-info">
    <span>&#128274;</span>
    <div><strong>Free plan:</strong> Only Bitcoin and Litecoin are available. <a href="<?php echo esc_url( admin_url( 'admin.php?page=chainpay&tab=license' ) ); ?>">Upgrade to Pro ($49/yr)</a> to unlock all 14 coins.</div>
  </div>
  <?php endif; ?>

  <div class="cp-section">
    <div class="cp-section-title">Enable Cryptocurrencies</div>
    <div class="cp-section-sub">Select which coins to show at checkout. Each coin requires an xPub key configured below.</div>
    <div class="cp-coin-grid">
      <?php foreach ( $all_c as $key => $coin ) :
        $checked = in_array( $key, $enabled, true );
        $locked  = ! $lic['is_pro'] && ! $coin['free'];
      ?>
      <div class="cp-coin-item<?php echo $locked ? ' cp-coin-item-locked' : ''; ?>">
        <div class="cp-coin-ico" style="background:<?php echo esc_attr( $coin['color'] ); ?>;"><?php echo esc_html( $coin['icon'] ); ?></div>
        <div style="flex:1;min-width:0;">
          <div class="cp-coin-name"><?php echo esc_html( $coin['name'] ); ?></div>
          <div class="cp-coin-sym"><?php echo esc_html( $coin['symbol'] ); ?> &middot; <?php echo esc_html( $coin['network'] ); ?></div>
          <?php if ( $coin['free'] ) : ?>
            <span class="cp-badge cp-badge-green" style="font-size:9px;margin-top:2px;">Always Free</span>
          <?php elseif ( $locked ) : ?>
            <span class="cp-badge cp-badge-gray" style="font-size:9px;margin-top:2px;">&#128274; Pro Only</span>
          <?php endif; ?>
        </div>
        <label class="cp-switch" style="<?php echo $locked ? 'opacity:.4;pointer-events:none;' : ''; ?>">
          <input type="checkbox" name="chainpay_enabled_coins[]" value="<?php echo esc_attr( $key ); ?>"<?php checked( $checked || $coin['free'] ); ?><?php echo $locked ? ' disabled' : ''; ?>>
          <span class="cp-slider"></span>
        </label>
      </div>
      <?php endforeach; ?>
    </div>
    <div style="margin-top:16px;">
      <button type="button" class="cp-btn cp-btn-primary cp-save-btn" data-tab="coins">&#10003; Save Coin Settings</button>
    </div>
  </div>

  <!-- ═══ WALLETS ══════════════════════════════════════════════ -->
  <?php elseif ( 'wallets' === $tab ) : ?>

  <div class="cp-notice cp-notice-warn">
    <span>&#9888;&#65039;</span>
    <div><strong>Security:</strong> Enter ONLY your <strong>xPub / zPub / ypub</strong> (extended PUBLIC key). <strong>Never enter a private key or seed phrase.</strong> ChainPay cannot spend your funds.</div>
  </div>

  <?php foreach ( $all_c as $key => $coin ) :
    if ( ! $lic['is_pro'] && ! $coin['free'] ) continue;
    $saved = (string) get_option( 'chainpay_xpub_' . $key, '' );
    $idx   = (int) get_option( 'chainpay_xpub_idx_' . $key, 0 );
  ?>
  <div class="cp-section" style="margin-bottom:12px;">
    <div style="display:flex;align-items:center;gap:10px;margin-bottom:12px;">
      <div class="cp-coin-ico" style="background:<?php echo esc_attr( $coin['color'] ); ?>;width:30px;height:30px;font-size:13px;"><?php echo esc_html( $coin['icon'] ); ?></div>
      <div>
        <div style="font-weight:800;font-size:14px;color:var(--cp-ink,#111);"><?php echo esc_html( $coin['name'] ); ?></div>
        <div style="font-size:10px;color:#9ca3af;"><?php echo esc_html( $coin['network'] ); ?> &nbsp;&middot;&nbsp; Next index: <?php echo esc_html( (string) $idx ); ?></div>
      </div>
      <?php if ( $coin['free'] ) : ?><span class="cp-badge cp-badge-green" style="margin-left:auto;font-size:9px;">Always Free</span><?php endif; ?>
    </div>
    <div class="cp-field" style="margin-bottom:8px;">
      <label class="cp-label">xPub / zPub Key</label>
      <input class="cp-input cp-mono" type="text" data-xpub-coin="<?php echo esc_attr( $key ); ?>"
             value="<?php echo esc_attr( $saved ); ?>"
             placeholder="xpub6… or zpub1… or ypub6…">
    </div>
    <div style="display:flex;gap:8px;align-items:center;">
      <button type="button" class="cp-btn cp-btn-primary cp-save-btn cp-btn-sm" data-tab="wallets">Save</button>
      <button type="button" class="cp-btn cp-btn-secondary cp-btn-sm cp-test-xpub" data-coin="<?php echo esc_attr( $key ); ?>">Test Derivation</button>
      <?php if ( $idx > 0 ) : ?>
        <span style="font-size:11px;color:#9ca3af;"><?php echo esc_html( (string) $idx ); ?> addresses derived</span>
      <?php endif; ?>
    </div>
    <div class="cp-notice" id="cp-xpub-result-<?php echo esc_attr( $key ); ?>" style="display:none;margin-top:8px;"></div>
  </div>
  <?php endforeach; ?>

  <?php if ( ! $lic['is_pro'] ) : ?>
  <div class="cp-notice cp-notice-info">
    <span>&#128274;</span>
    <div><a href="<?php echo esc_url( admin_url( 'admin.php?page=chainpay&tab=license' ) ); ?>">Upgrade to Pro</a> to configure wallets for all 14 coins.</div>
  </div>
  <?php endif; ?>

  <!-- ═══ INVOICES ══════════════════════════════════════════════ -->
  <?php elseif ( 'invoices' === $tab ) : ?>
  <?php
  global $wpdb;
  $t    = $wpdb->prefix . 'chainpay_invoices';
  $page = max( 1, isset( $_GET['paged'] ) ? absint( $_GET['paged'] ) : 1 );
  $per  = 25;
  $rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $t ORDER BY created_at DESC LIMIT %d OFFSET %d", $per, ( $page - 1 ) * $per ), ARRAY_A );
  $status_class = array( 'confirmed' => 'cp-badge-green', 'pending' => 'cp-badge-gold', 'detected' => 'cp-badge-blue', 'expired' => 'cp-badge-gray', 'underpaid' => 'cp-badge-orange' );
  ?>
  <div class="cp-stats">
    <div class="cp-stat"><div class="cp-stat-val"><?php echo esc_html( number_format( $stats['total'] ) ); ?></div><div class="cp-stat-lbl">Total Invoices</div></div>
    <div class="cp-stat"><div class="cp-stat-val" style="color:#059669;"><?php echo esc_html( number_format( $stats['confirmed'] ) ); ?></div><div class="cp-stat-lbl">Confirmed</div></div>
    <div class="cp-stat"><div class="cp-stat-val" style="color:#f59e0b;"><?php echo esc_html( number_format( $stats['pending'] ) ); ?></div><div class="cp-stat-lbl">Pending</div></div>
    <div class="cp-stat"><div class="cp-stat-val" style="color:#2563eb;"><?php echo '$' . esc_html( number_format( $stats['revenue'], 2 ) ); ?></div><div class="cp-stat-lbl">Revenue</div></div>
  </div>
  <div class="cp-section" style="padding:0;">
    <div class="cp-table-wrap">
      <table class="cp-table">
        <thead><tr><th>Invoice ID</th><th>Order</th><th>Coin</th><th>Amount</th><th>Fiat</th><th>Status</th><th>TX Hash</th><th>Date</th></tr></thead>
        <tbody>
        <?php foreach ( $rows as $r ) :
          $c = ChainPay_Coin_Registry::get( $r['coin'] );
          $bc = isset( $status_class[ $r['status'] ] ) ? $status_class[ $r['status'] ] : 'cp-badge-gray';
          $olink = wc_get_order( $r['order_id'] ) ? '<a href="' . esc_url( get_edit_post_link( $r['order_id'] ) ) . '">#' . esc_html( $r['order_id'] ) . '</a>' : '#' . esc_html( $r['order_id'] );
        ?>
          <tr>
            <td class="cp-mono"><?php echo esc_html( $r['invoice_id'] ); ?></td>
            <td><?php echo $olink; ?></td>
            <td>
              <span style="display:inline-flex;align-items:center;gap:5px;">
                <span style="width:16px;height:16px;border-radius:50%;background:<?php echo esc_attr( $c ? $c['color'] : '#aaa' ); ?>;color:#fff;display:inline-flex;align-items:center;justify-content:center;font-size:8px;font-weight:900;"><?php echo esc_html( $c ? $c['icon'] : $r['coin'][0] ); ?></span>
                <?php echo esc_html( $r['coin'] ); ?>
              </span>
            </td>
            <td class="cp-mono"><?php echo esc_html( $r['amount_crypto'] ); ?></td>
            <td><?php echo esc_html( $r['fiat_currency'] . ' ' . number_format( (float) $r['amount_fiat'], 2 ) ); ?></td>
            <td><span class="cp-badge <?php echo esc_attr( $bc ); ?>"><?php echo esc_html( $r['status'] ); ?></span></td>
            <td class="cp-mono" style="max-width:120px;overflow:hidden;text-overflow:ellipsis;"><?php echo $r['tx_hash'] ? esc_html( substr( $r['tx_hash'], 0, 14 ) . '…' ) : '<span style="color:#ddd;">—</span>'; ?></td>
            <td style="color:#9ca3af;font-size:11px;"><?php echo esc_html( wp_date( 'M j, g:i a', strtotime( $r['created_at'] ) ) ); ?></td>
          </tr>
        <?php endforeach; ?>
        <?php if ( empty( $rows ) ) : ?>
          <tr><td colspan="8" style="text-align:center;padding:28px;color:#9ca3af;">No invoices yet. Once customers pay via ChainPay they will appear here.</td></tr>
        <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>

  <!-- ═══ STATS ═════════════════════════════════════════════════ -->
  <?php elseif ( 'logs' === $tab ) : ?>

  <div class="cp-stats">
    <div class="cp-stat"><div class="cp-stat-val"><?php echo esc_html( $stats['this_month'] ); ?></div><div class="cp-stat-lbl">This Month</div></div>
    <div class="cp-stat"><div class="cp-stat-val" style="color:#059669;"><?php echo esc_html( $stats['confirmed'] ); ?></div><div class="cp-stat-lbl">Confirmed</div></div>
    <div class="cp-stat"><div class="cp-stat-val" style="color:#6b7280;"><?php echo esc_html( $stats['expired'] ); ?></div><div class="cp-stat-lbl">Expired</div></div>
    <div class="cp-stat"><div class="cp-stat-val">'$<?php echo esc_html( number_format( $stats['revenue'], 2 ) ); ?></div><div class="cp-stat-lbl">Revenue</div></div>
  </div>

  <div class="cp-section">
    <div class="cp-section-title">Plugin & System Info</div>
    <?php
    $info = array(
      'Plugin Version'        => CHAINPAY_VERSION,
      'Plan'                  => $lic['is_pro'] ? 'Pro (Licensed)' : 'Free',
      'Monthly Payments Used' => $lic['is_pro'] ? $used . ' (unlimited)' : $used . ' / ' . CHAINPAY_FREE_LIMIT,
      'Domain'                => home_url(),
      'License Domain Bound'  => $lic['is_pro'] ? $lic['domain'] : 'N/A (free plan)',
      'API Endpoint'          => CHAINPAY_API_BASE,
      'Webhook IPN URL'       => home_url( '/chainpay-ipn/' ),
      'PHP Version'           => PHP_VERSION,
      'WC Version'            => defined( 'WC_VERSION' ) ? WC_VERSION : 'N/A',
      'WP Version'            => get_bloginfo( 'version' ),
      'Cron: Invoices'        => wp_next_scheduled( 'chainpay_cron_invoices' ) ? wp_date( 'H:i:s', wp_next_scheduled( 'chainpay_cron_invoices' ) ) : '⚠ Not scheduled!',
      'Cron: Prices'          => wp_next_scheduled( 'chainpay_cron_prices' )   ? wp_date( 'H:i:s', wp_next_scheduled( 'chainpay_cron_prices' ) )   : '⚠ Not scheduled!',
    );
    ?>
    <table style="width:100%;border-collapse:collapse;font-size:12px;">
      <?php foreach ( $info as $k => $v ) : ?>
      <tr>
        <td style="color:#9ca3af;width:180px;padding:7px 0;border-bottom:1px solid #f0f0f0;font-size:10px;text-transform:uppercase;letter-spacing:.4px;font-weight:700;"><?php echo esc_html( $k ); ?></td>
        <td style="padding:7px 0;border-bottom:1px solid #f0f0f0;font-family:monospace;font-size:11px;"><?php echo esc_html( (string) $v ); ?></td>
      </tr>
      <?php endforeach; ?>
    </table>
  </div>

  <?php endif; ?>
</div><!-- /cp-wrap -->
