<?php
/**
 * Theme functions and definitions – xeco (support form + icons + quotes + wallet USD + withdraw + manual payments)
 * FIXED VERSION — includes:
 *  - Bank & Crypto manual gateways (visible)
 *  - Wallet system (ledger, admin, top-up)
 *  - "Para Çek" modal updated: choose Bank (IBAN) or Crypto (Coin + Address)
 *  - New handler for crypto withdraws (admin_post_xeco_withdraw)
 *  - Small patch to ensure our manual gateways are always present in available gateways
 *
 * PHP 7.4 compatible
 */
if (!defined('ABSPATH')) { exit; }

/* ===========================
   Tema kurulumu
   =========================== */
if (!function_exists('xeco_setup')) :
function xeco_setup(){
  load_theme_textdomain('xeco', get_template_directory().'/languages');
  add_theme_support('automatic-feed-links');
  add_theme_support('title-tag');
  add_theme_support('post-thumbnails');
  register_nav_menus([
    'main-menu'   => esc_html__('Main Menu','xeco'),
    'footer-menu' => esc_html__('Footer Menu','xeco'),
  ]);
  add_theme_support('html5', ['search-form','comment-form','comment-list','gallery','caption']);
  add_theme_support('custom-background', ['default-color'=>'ffffff','default-image'=>'']);
  add_theme_support('customize-selective-refresh-widgets');
  add_theme_support('custom-header');
  add_theme_support('custom-logo', ['height'=>250,'width'=>250,'flex-width'=>true,'flex-height'=>true]);
  add_theme_support('post-formats', ['image','audio','video','gallery','quote']);
  add_theme_support('wp-block-styles');
  add_theme_support('align-wide');
  add_theme_support('editor-styles');
  add_theme_support('responsive-embeds');
  remove_theme_support('widgets-block-editor');
  add_theme_support('woocommerce', [
    'thumbnail_image_width'=>350,'gallery_thumbnail_image_width'=>350,'single_image_width'=>650,
  ]);
  add_theme_support('wc-product-gallery-lightbox');
  add_theme_support('wc-product-gallery-slider');
  add_image_size('xeco-case-details', 1170, 600, ['center','center']);
}
endif;
add_action('after_setup_theme','xeco_setup');

function xeco_content_width(){ $GLOBALS['content_width']=apply_filters('xeco_content_width',640); }
add_action('after_setup_theme','xeco_content_width',0);

/* ===========================
   Include’lar (inc klasörü kullanımı)
   =========================== */
define('XECO_THEME_DIR', get_template_directory());
define('XECO_THEME_URI', get_template_directory_uri());
define('XECO_THEME_INC', XECO_THEME_DIR.'/inc/');
define('XECO_THEME_CSS_DIR', XECO_THEME_URI . '/assets/css/');
define('XECO_THEME_JS_DIR',  XECO_THEME_URI . '/assets/js/');

if(!function_exists('wp_body_open')){ function wp_body_open(){ do_action('wp_body_open'); } }
// yüklemeler (varsa)
if (file_exists(XECO_THEME_INC.'custom-header.php')) require XECO_THEME_INC.'custom-header.php';
if (file_exists(XECO_THEME_INC.'template-functions.php')) require XECO_THEME_INC.'template-functions.php';
if (file_exists(XECO_THEME_INC.'template-helper.php')) require XECO_THEME_INC.'template-helper.php';
if (file_exists(XECO_THEME_INC.'kirki-customizer.php')) include_once XECO_THEME_INC.'kirki-customizer.php';
if (file_exists(XECO_THEME_INC.'class-xeco-kirki.php')) include_once XECO_THEME_INC.'class-xeco-kirki.php';
if (defined('JETPACK__VERSION') && file_exists(XECO_THEME_INC.'jetpack.php')) require XECO_THEME_INC.'jetpack.php';
if (file_exists(XECO_THEME_INC.'class-navwalker.php')) require_once XECO_THEME_INC.'class-navwalker.php';
if (file_exists(XECO_THEME_INC.'class-tgm-plugin-activation.php')) require_once XECO_THEME_INC.'class-tgm-plugin-activation.php';
if (file_exists(XECO_THEME_INC.'add_plugin.php')) require_once XECO_THEME_INC.'add_plugin.php';
if (file_exists(XECO_THEME_INC.'/common/xeco-breadcrumb.php')) require_once XECO_THEME_INC.'/common/xeco-breadcrumb.php';
if (file_exists(XECO_THEME_INC.'/common/xeco-scripts.php')) require_once XECO_THEME_INC.'/common/xeco-scripts.php';
if (file_exists(XECO_THEME_INC.'/common/xeco-widgets.php')) require_once XECO_THEME_INC.'/common/xeco-widgets.php';
if (class_exists('WooCommerce') && file_exists(XECO_THEME_INC.'/woocommerce/xeco-woocommerce.php')) require_once XECO_THEME_INC.'/woocommerce/xeco-woocommerce.php';

/* ===========================
   Ufak yardımcılar
   =========================== */
add_action('wp_head', function(){
  if (is_singular() && pings_open()){
    printf('<link rel="pingback" href="%s">', esc_url(get_bloginfo('pingback_url')));
  }
});
add_filter('comment_form_fields', function($fields){
  if (isset($fields['comment'])) {
    $c = $fields['comment'];
    unset($fields['comment']);
    $fields['comment'] = $c;
  }
  return $fields;
});
add_filter('get_archives_link', function($l){ $l=str_replace('</a>&nbsp;(','</a> <span class="float-right">(',$l); return str_replace(')',')</span>',$l); });
add_filter('wp_list_categories', function($l){
  $l=str_replace('<span class="count">(','</a> <span class="float-right">',$l);
  $l=str_replace('</a> (','</a> <span class="float-right">(',$l);
  return str_replace(')',')</span>',$l);
},10,2);

/* ===========================
   “Hesabım” sekmeleri
   =========================== */
add_action('init', function(){
  add_rewrite_endpoint('cuzdanim',EP_ROOT|EP_PAGES);
  add_rewrite_endpoint('borsa-alim-satim',EP_ROOT|EP_PAGES);
  add_rewrite_endpoint('emtia-alim-satim',EP_ROOT|EP_PAGES);
  add_rewrite_endpoint('kripto-alim-satim',EP_ROOT|EP_PAGES);
  add_rewrite_endpoint('musteri-hizmetleri',EP_ROOT|EP_PAGES); // özel form
});
add_filter('woocommerce_account_menu_items', function(){
  return [
    'dashboard'         => 'HESABIM',
    'cuzdanim'          => 'Cüzdanım',
    'borsa-alim-satim'  => 'Borsa Alım / Satım',
    'emtia-alim-satim'  => 'Emtia Alım / Satım',
    'kripto-alim-satim' => 'Kripto Alım / Satım',
    'edit-account'      => 'Hesap Bilgileri',
    'musteri-hizmetleri'=> 'Müşteri Hizmetleri',
    'customer-logout'   => 'Çıkış',
  ];
}, PHP_INT_MAX);

/* ===========================
   Müşteri Hizmetleri – Form (işleme + çizim)
   =========================== */
add_action('woocommerce_account_musteri-hizmetleri_endpoint', function () {
  if (isset($_POST['xh_support_nonce']) && wp_verify_nonce($_POST['xh_support_nonce'], 'xh_support_form')) {
    $errs = [];

    $name   = sanitize_text_field($_POST['xh_name']   ?? '');
    $phone  = preg_replace('/[^0-9+\s()\-]/', '', $_POST['xh_phone'] ?? '');
    $email  = sanitize_email($_POST['xh_email'] ?? '');
    $topic  = sanitize_text_field($_POST['xh_topic']  ?? '');
    $time   = sanitize_text_field($_POST['xh_time']   ?? '');
    $msg    = wp_kses_post($_POST['xh_msg'] ?? '');

    if ($name === '')  { $errs[] = 'Lütfen ad soyad giriniz.'; }
    if ($phone === '') { $errs[] = 'Lütfen telefon numarası giriniz.'; }
    if ($topic === '') { $errs[] = 'Lütfen bir konu seçiniz.'; }
    if ($msg === '')   { $errs[] = 'Lütfen mesajınızı yazınız.'; }
    if ($email && !is_email($email)) { $errs[] = 'Lütfen geçerli bir e-posta giriniz.'; }

    if ($errs) {
      foreach($errs as $e){ wc_add_notice($e, 'error'); }
    } else {
      $admin   = get_option('admin_email');
      $user_id = get_current_user_id();

      $subject = 'Müşteri Hizmetleri – ' . $topic;
      $body    = "Kullanıcı: {$name}" . ($user_id ? " (ID: {$user_id})" : '') . "\n"
               . "Telefon: {$phone}\n"
               . "E-posta: " . ($email ?: '-') . "\n"
               . "Konu: {$topic}\n"
               . "Uygun Saat: " . ($time ?: '-') . "\n\n"
               . "Mesaj:\n{$msg}\n";

      $headers = ['Content-Type: text/plain; charset=UTF-8'];
      if ($email) { $headers[] = 'Reply-To: '.$email; }

      wp_mail($admin, $subject, $body, $headers);

      if ($email) {
        wp_mail($email, 'Talebiniz alındı', "Merhaba {$name},\n\nTalebiniz bize ulaştı. En kısa sürede dönüş yapacağız.\n\nÖzet:\n{$subject}\n\n{$msg}\n", ['Content-Type: text/plain; charset=UTF-8']);
      }

      wc_add_notice('Talebiniz alındı. En kısa sürede sizinle iletişime geçeceğiz.', 'success');
      $_POST = [];
    }
  }

  wc_print_notices();
  ?>
  <style>
    .xh-card{background:#0f1319;border:1px solid #202733;border-radius:14px;padding:18px;margin:6px 0 18px}
    .xh-title{margin:0 0 14px;font-weight:600}
    .xh-grid{display:grid;grid-template-columns:1fr 1fr;gap:14px}
    .xh-grid + .xh-grid{margin-top:14px}
    .xh-full{grid-column:1/-1}
    .xh-label{display:block;margin:0 0 6px;color:#9aa4b2;font-size:13px}
    .xh-input,.xh-select,.xh-textarea,.xh-time{
      width:100%;background:#0b0f14;border:1px solid #2a3340;color:#e8f0fb;border-radius:10px;
      padding:10px 12px;outline:none
    }
    .xh-textarea{min-height:140px;resize:vertical}
    .xh-btn{margin-top:16px;background:#16a34a;color:#fff;border:0;border-radius:999px;padding:11px 18px;cursor:pointer}
    .xh-btn:hover{filter:brightness(1.08)}
  </style>

  <div class="xh-card">
    <h3 class="xh-title">Müşteri Hizmetleri</h3>
    <form method="post">
      <?php wp_nonce_field('xh_support_form', 'xh_support_nonce'); ?>

      <div class="xh-grid">
        <div>
          <label class="xh-label">Ad Soyad *</label>
          <input class="xh-input" type="text" name="xh_name" value="<?php echo esc_attr($_POST['xh_name'] ?? ''); ?>">
        </div>
        <div>
          <label class="xh-label">Telefon *</label>
          <input class="xh-input" type="tel" name="xh_phone" inputmode="tel" placeholder="+90 5xx xxx xx xx" value="<?php echo esc_attr($_POST['xh_phone'] ?? ''); ?>">
        </div>
      </div>

      <div class="xh-grid">
        <div>
          <label class="xh-label">E-posta</label>
          <input class="xh-input" type="email" name="xh_email" value="<?php echo esc_attr($_POST['xh_email'] ?? ''); ?>">
        </div>
        <div>
          <label class="xh-label">Konu *</label>
          <select class="xh-select" name="xh_topic">
            <option value="">Seçiniz…</option>
            <?php
              $opts=['Destek','Talep','İstek','Şikayet','Hesap İşlemleri','Ödeme'];
              $cur=$_POST['xh_topic'] ?? '';
              foreach($opts as $o){ printf('<option value="%1$s"%2$s>%1$s</option>', esc_attr($o), selected($cur,$o,false)); }
            ?>
          </select>
        </div>
      </div>

      <div class="xh-grid">
        <div>
          <label class="xh-label">Uygun Olduğunuz Saat(Müşteri Temsilcimiz Size Ulaşacak)</label>
          <input class="xh-time" type="time" name="xh_time" value="<?php echo esc_attr($_POST['xh_time'] ?? ''); ?>">
        </div>
        <div class="xh-full">
          <label class="xh-label">Mesajınız *</label>
          <textarea class="xh-textarea" name="xh_msg"><?php echo esc_textarea($_POST['xh_msg'] ?? ''); ?></textarea>
        </div>
      </div>

      <button class="xh-btn" type="submit">Gönder</button>
    </form>
  </div>
  <?php
});

/* ===========================
   Sanal ürün + Sepet’e ekle (checkout’a yönlendir)
   =========================== */
function tw_ensure_virtual_product(){
  $sku='trade-order-virtual-no-plugin';
  if(function_exists('wc_get_product_id_by_sku')){
    $pid=wc_get_product_id_by_sku($sku);
    if($pid) return $pid;
  }
  $pid=wp_insert_post(['post_title'=>'Trade Order','post_type'=>'product','post_status'=>'publish']);
  update_post_meta($pid,'_sku',$sku);
  update_post_meta($pid,'_virtual','yes');
  update_post_meta($pid,'_price','1');
  update_post_meta($pid,'_regular_price','1');
  wp_set_object_terms($pid,'simple','product_type',false);
  return $pid;
}
add_action('wp_ajax_tw_add_to_cart','tw_add_to_cart');
add_action('wp_ajax_nopriv_tw_add_to_cart','tw_add_to_cart');
function tw_add_to_cart(){
  $symbol=sanitize_text_field($_POST['symbol']??'');
  $amount=floatval($_POST['amount']??0);
  $price=floatval($_POST['price']??0);
  $side=sanitize_text_field($_POST['side']??'buy');
  $type=sanitize_text_field($_POST['type']??'borsa');
  if(!$symbol||$amount<=0||$price<=0) wp_send_json_error('Geçersiz veri');

  $pid=tw_ensure_virtual_product();
  $total=round($amount*$price,2);
  $data=['_tw_symbol'=>$symbol,'_tw_amount'=>$amount,'_tw_price'=>$price,'_tw_side'=>$side,'_tw_type'=>$type,'_custom_price'=>$total];
  if (WC()->cart) WC()->cart->empty_cart();
  $added=WC()->cart->add_to_cart($pid,1,0,[],$data);
  if(!$added) wp_send_json_error('Sepete eklenemedi');
  wp_send_json_success(['checkout'=>wc_get_checkout_url()]);
}

add_action('woocommerce_before_calculate_totals', function($cart){
  if (empty($cart->cart_contents)) return;
  foreach ($cart->cart_contents as $item){
    if (isset($item['_custom_price'])) {
      // Fiyatı sabitle
      $item['data']->set_price($item['_custom_price']);

      // Eğer top-up ise uygun isim ver
      if (!empty($item['_is_topup'])) {
        $item['data']->set_name('Cüzdan Bakiye Yükleme (USD)');
        continue;
      }

      // Değilse trade kalemi formatı
      if (isset($item['_tw_symbol'], $item['_tw_side'], $item['_tw_type'])) {
        $item['data']->set_name(
          'İşlem: ' .
          strtoupper($item['_tw_symbol']) . ' ' .
          strtoupper($item['_tw_side']) .
          ' (' . $item['_tw_type'] . ')'
        );
      }
    }
  }
}, 10);


add_action('woocommerce_checkout_create_order_line_item', function($item,$key,$vals){
  foreach(['_tw_symbol','_tw_amount','_tw_price','_tw_side','_tw_type'] as $k){
    if(isset($vals[$k])) $item->add_meta_data(substr($k,1),$vals[$k],true);
  }
},10,3);

/* ===========================
   ÖDEME YÖNTEMLERİ – İki manuel yöntem (Bank & Kripto)
   =========================== */

/* Klasik checkout zorunlu: Blocks kapat */
add_filter('woocommerce_should_load_cart_checkout_blocks', '__return_false', 999);

/* Manuel gateway’leri ekle */
add_filter('woocommerce_payment_gateways', function($methods){
  $methods[] = 'UV_Gateway_Bank_Manual';
  $methods[] = 'UV_Gateway_Crypto_Manual';
  return $methods;
});

/* WooCommerce’in kendi BACS’ını gizle – bizim bankayı kullanalım (isteğe bağlı) */
add_filter('woocommerce_available_payment_gateways', function($gws){
  // Ensure our gateways are present when enabled in admin
  if (isset($gws['uv_bank_manual']) === false) {
      // create temporary instance to check admin settings
      if (class_exists('UV_Gateway_Bank_Manual')) {
          $gw = new UV_Gateway_Bank_Manual();
          if ($gw->is_available()) $gws['uv_bank_manual'] = $gw;
      }
  }
  if (isset($gws['uv_crypto_manual']) === false) {
      if (class_exists('UV_Gateway_Crypto_Manual')) {
          $gw2 = new UV_Gateway_Crypto_Manual();
          if ($gw2->is_available()) $gws['uv_crypto_manual'] = $gw2;
      }
  }
  // remove core bacs only if present (we still leave it by default, but can be removed)
  if(isset($gws['bacs'])) unset($gws['bacs']);
  return $gws;
}, 9);

/* Varsayılan gateway bankamız olsun */
add_filter('woocommerce_default_gateway', function(){ return 'uv_bank_manual'; });

if (!class_exists('UV_Gateway_Bank_Manual')) {
class UV_Gateway_Bank_Manual extends WC_Payment_Gateway {
  public function __construct(){
    $this->id                 = 'uv_bank_manual';
    $this->method_title       = 'Banka Havalesi / EFT (Manuel)';
    $this->method_description = 'Müşteri IBAN’a havale/EFT yapar, onay sonrası sipariş işleme alınır.';
    $this->title              = '🏦 Banka Havalesi / EFT';
    $this->has_fields         = false;
    $this->supports           = ['products'];

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

    $this->iban     = $this->get_option('iban');
    $this->bank     = $this->get_option('bank');
    $this->acc_name = $this->get_option('acc_name');
    $this->note     = $this->get_option('note');

    add_action('woocommerce_update_options_payment_gateways_'.$this->id, [$this,'process_admin_options']);
  }
  public function init_form_fields(){
    $this->form_fields = [
      'enabled'  => ['title'=>'Aktif','type'=>'checkbox','label'=>'Bu yöntemi etkinleştir','default'=>'yes'],
      'bank'     => ['title'=>'Banka Adı','type'=>'text','default'=>''],
      'acc_name' => ['title'=>'Hesap Adı','type'=>'text','default'=>''],
      'iban'     => ['title'=>'IBAN','type'=>'text','default'=>''],
      'note'     => ['title'=>'Talimat','type'=>'textarea','default'=>'Ödeme açıklamasına sipariş numaranızı yazınız.'],
    ];
  }
  public function is_available(){ return ('yes'===$this->get_option('enabled')); }
  public function payment_fields(){
    echo '<p>Lütfen aşağıdaki hesap bilgilerine ödeme yapın, onay sonrası siparişiniz işleme alınacaktır.</p>';
    echo '<ul style="line-height:1.6em">';
    if($this->bank)     echo '<li><strong>Banka:</strong> '.esc_html($this->bank).'</li>';
    if($this->acc_name) echo '<li><strong>Hesap Adı:</strong> '.esc_html($this->acc_name).'</li>';
    if($this->iban)     echo '<li><strong>IBAN:</strong> '.esc_html($this->iban).'</li>';
    echo '</ul>';
    if($this->note) echo '<p><em>'.wp_kses_post($this->note).'</em></p>';
  }
  public function process_payment($order_id){
    $order = wc_get_order($order_id);
    $order->update_status('on-hold','Banka havalesi bekleniyor.');
    /* Referans kodu üret */
    if (!$order->get_meta('_uv_bank_ref')) {
      $order->update_meta_data('_uv_bank_ref', 'HF-' . $order->get_id() . '-' . wp_generate_password(6, false, false));
      $order->save();
    }
    if (WC() && WC()->cart) WC()->cart->empty_cart();
    return ['result'=>'success','redirect'=>$this->get_return_url($order)];
  }
}}
if (!class_exists('UV_Gateway_Crypto_Manual')) {
class UV_Gateway_Crypto_Manual extends WC_Payment_Gateway {
  public function __construct(){
    $this->id                 = 'uv_crypto_manual';
    $this->method_title       = 'Kripto Transferi (Manuel)';
    $this->method_description = 'USDT/BTC/ETH adreslerine manuel transfer.';
    $this->title              = '💎 Kripto Transferi (USDT/BTC/ETH)';
    $this->has_fields         = true; // show fields so user can paste TXID, coin type or choose after checkout
    $this->supports           = ['products'];

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

    $this->addr_usdt = $this->get_option('addr_usdt');
    $this->addr_btc  = $this->get_option('addr_btc');
    $this->addr_eth  = $this->get_option('addr_eth');
    $this->note      = $this->get_option('note');

    add_action('woocommerce_update_options_payment_gateways_'.$this->id, [$this,'process_admin_options']);
  }
  public function init_form_fields(){
    $this->form_fields = [
      'enabled'   => ['title'=>'Aktif','type'=>'checkbox','label'=>'Bu yöntemi etkinleştir','default'=>'yes'],
      'addr_usdt' => ['title'=>'USDT (TRC20) Adresi','type'=>'text','default'=>''],
      'addr_btc'  => ['title'=>'BTC Adresi','type'=>'text','default'=>''],
      'addr_eth'  => ['title'=>'ETH Adresi','type'=>'text','default'=>''],
      'note'      => ['title'=>'Talimat','type'=>'textarea','default'=>'Transfer tamamlandıktan sonra TXID ile bildiriniz.'],
    ];
  }
  public function is_available(){ return ('yes'===$this->get_option('enabled')); }
  public function payment_fields(){
    echo '<p>Aşağıdaki adreslerden uygun olana transfer yapın. Onay sonrası siparişiniz işleme alınır.</p><ul style="line-height:1.6em">';
    if($this->addr_usdt) echo '<li><strong>USDT (TRC20):</strong> '.esc_html($this->addr_usdt).'</li>';
    if($this->addr_btc)  echo '<li><strong>BTC:</strong> '.esc_html($this->addr_btc).'</li>';
    if($this->addr_eth)  echo '<li><strong>ETH:</strong> '.esc_html($this->addr_eth).'</li>';
    echo '</ul>';
    // also allow customer to paste their TXID or select coin after placing order
    echo '<p><label>TXID / Transfer ID (varsa): <input type="text" name="uv_crypto_txid" style="width:100%;max-width:420px"></label></p>';
    if($this->note) echo '<p><em>'.wp_kses_post($this->note).'</em></p>';
  }
  public function process_payment($order_id){
    $order = wc_get_order($order_id);
    $order->update_status('on-hold','Kripto transferi bekleniyor.');
    if (WC() && WC()->cart) WC()->cart->empty_cart();
    return ['result'=>'success','redirect'=>$this->get_return_url($order)];
  }
}}

/* Teşekkür sayfasında talimat kutuları */
add_action('woocommerce_thankyou', function($order_id){
  $order = wc_get_order($order_id);
  if (!$order) return;

  echo '<div style="border:1px solid #2b2f3a;padding:14px 16px;border-radius:12px;margin:18px 0;background:#0d1117;color:#e5e7eb">';
  if ($order->get_payment_method()==='uv_bank_manual'){
    $ref = $order->get_meta('_uv_bank_ref');
    if (empty($ref)) {
      $ref = 'HF-' . $order->get_id() . '-' . wp_generate_password(6, false, false);
      $order->update_meta_data('_uv_bank_ref', $ref);
      $order->save();
    }
    $ref = esc_html($ref);

    // Gateway ayarlarından çek
    $gw = new UV_Gateway_Bank_Manual();
    $bank = esc_html($gw->bank ?? '');
    $acc  = esc_html($gw->acc_name ?? '');
    $iban = esc_html($gw->iban ?? '');

    echo '<h3 style="margin:0 0 10px;font-size:18px">Havale / EFT Bilgileri</h3>';
    if ($bank) echo '<p style="margin:6px 0">Banka: <strong>'.$bank.'</strong></p>';
    if ($acc)  echo '<p style="margin:6px 0">Hesap Adı: <strong>'.$acc.'</strong></p>';
    if ($iban) echo '<p style="margin:6px 0">IBAN: <strong>'.$iban.'</strong></p>';
    echo '<p style="margin:10px 0">Sipariş Referansı: <strong>'.$ref.'</strong></p>';
    echo '<p style="margin:10px 0">Ödenecek Tutar: <strong>'.wc_price($order->get_total(), ['currency' => $order->get_currency()]).'</strong></p>';
    echo '<p style="margin:12px 0 0;color:#9aa4b2;font-size:13px">Lütfen havale açıklamasına <b>'.$ref.'</b> kodunu yazınız. Ödemeniz onaylandığında siparişiniz işleme alınacaktır.</p>';
  } elseif ($order->get_payment_method()==='uv_crypto_manual'){
    $gw = new UV_Gateway_Crypto_Manual();
    echo '<h3 style="margin:0 0 10px;font-size:18px">Kripto Transfer Bilgileri</h3><ul>';
    if(!empty($gw->addr_usdt)) echo '<li>USDT (TRC20): <strong>'.esc_html($gw->addr_usdt).'</strong></li>';
    if(!empty($gw->addr_btc))  echo '<li>BTC: <strong>'.esc_html($gw->addr_btc).'</strong></li>';
    if(!empty($gw->addr_eth))  echo '<li>ETH: <strong>'.esc_html($gw->addr_eth).'</strong></li>';
    echo '</ul>';
    echo '<p style="margin:10px 0">Gönderilecek Tutar: <strong>'.wc_price($order->get_total(), ['currency' => $order->get_currency()]).'</strong></p>';
    echo '<p style="margin:12px 0 0;color:#9aa4b2;font-size:13px">Transfer sonrası TXID ile bildiriniz. Onaylandığında siparişiniz işleme alınır.</p>';
  }
  echo '</div>';
}, 20);

/* ===========================
   Fiyat / Grafik – Yahoo & Binance
   (kısaltıldı — orijinal fonksiyonel yapıyı koruyun, gerektiğinde geri ekleyin)
   =========================== */
function tw_map_symbol($type,$symbol){
  $s=strtoupper(trim($symbol));
  // basit map (orijinal kodun eşdeğeri)
  if($type==='emtia'){ $map = ['XAUUSD'=>'XAUUSD=X','XAGUSD'=>'XAGUSD=X','GOLD'=>'XAUUSD=X','SILVER'=>'XAGUSD=X']; return $map[$s] ?? $s; }
  if($type==='borsa'){ $map=['GSPC'=>'^GSPC','DJI'=>'^DJI']; return $map[$s] ?? $s; }
  return $s;
}

/* anlık fiyat */
add_action('wp_ajax_nopriv_tw_get_price','tw_get_price');
add_action('wp_ajax_tw_get_price','tw_get_price');
function tw_get_price(){
  $type=sanitize_text_field($_GET['type']??'');
  $symbol=strtoupper(sanitize_text_field($_GET['symbol']??''));
  if(!$type||!$symbol) wp_send_json_error('bad_params');
  if(!preg_match('/^[A-Z0-9\^\.\=\-\_]+$/',$symbol)) wp_send_json_error('bad_symbol');

  if($type==='kripto'){
    $r=wp_remote_get('https://api.binance.com/api/v3/ticker/price?symbol='.rawurlencode($symbol),['timeout'=>6,'headers'=>['User-Agent'=>'Mozilla/5.0']]);
    if(!is_wp_error($r) && 200===wp_remote_retrieve_response_code($r)){
      $b=json_decode(wp_remote_retrieve_body($r),true);
      if(isset($b['price'])) wp_send_json_success(['price'=>(float)$b['price']]);
    }
    wp_send_json_error('no_price');
  }

  $y=tw_map_symbol($type,$symbol);
  $ua=['headers'=>['User-Agent'=>'Mozilla/5.0'],'timeout'=>6];
  $r=wp_remote_get('https://query1.finance.yahoo.com/v7/finance/quote?symbols='.rawurlencode($y),$ua);
  $p=0.0;
  if(!is_wp_error($r) && 200===wp_remote_retrieve_response_code($r)){
    $j=json_decode(wp_remote_retrieve_body($r),true);
    $p=(float)($j['quoteResponse']['result'][0]['regularMarketPrice']??0);
  }
  if(!$p){
    $r2=wp_remote_get('https://query2.finance.yahoo.com/v10/finance/quoteSummary/'.rawurlencode($y).'?modules=price',$ua);
    if(!is_wp_error($r2) && 200===wp_remote_retrieve_response_code($r2)){
      $k=json_decode(wp_remote_retrieve_body($r2),true);
      $p=(float)($k['quoteSummary']['result'][0]['price']['regularMarketPrice']['raw']??0);
    }
  }
  $p>0 ? wp_send_json_success(['price'=>$p]) : wp_send_json_error('no_price');
}

/* tarihsel (kısaltıldı) */
add_action('wp_ajax_nopriv_tw_get_history','tw_get_history');
add_action('wp_ajax_tw_get_history','tw_get_history');
function tw_get_history(){
  wp_send_json_error('not_implemented');
}

/* ===========================
   Ortak Trade kutusu + Modal
   (korundu — bu bölüm orijinal kodu kullanır)
   =========================== */
function tw_render_trade_box($type,$title,$symbols){ ?>
  <div class="tw-box" data-type="<?php echo esc_attr($type); ?>">
    <h3 class="tw-title"><?php echo esc_html($title); ?></h3>
    <div class="tw-iframe-wrap" style="height:360px"><div id="chartx"></div></div>
    <div class="tw-form">
      <div class="tw-row two">
        <div>
          <label><?php echo $type==='borsa'?'Endeks/Sembol':'Sembol'; ?></label>
          <div style="display:flex;gap:8px;">
            <input class="tw-symbol" type="text" placeholder="<?php echo $type==='borsa'?'ör: GSPC / FTSE / GDAXI':'ör: BTCUSDT / XAUUSD'; ?>" readonly>
            <button class="tw-select-btn" type="button">SEÇ</button>
          </div>
        </div>
        <div><label>Miktar</label><input class="tw-amount" type="number" step="any" min="0" placeholder="ör: 1.5"></div>
      </div>
      <div class="tw-row two">
        <div><label>Fiyat (Anlık)</label><input class="tw-price" type="number" step="any" min="0" readonly></div>
        <div><label>Toplam Tutar</label><input class="tw-total" type="number" step="any" min="0" readonly></div>
      </div>
      <div class="tw-actions"><button class="tw-buy" type="button">AL</button><button class="tw-sell tw-ghost" type="button">SAT</button></div>
      <p class="tw-note">Ödemeler <b>🏦 Havale/EFT</b> veya <b>💎 Kripto</b> iledir. Sipariş sonrası talimatlar gösterilir.</p>
    </div>

    <div class="tw-modal" hidden>
      <div class="tw-modal-content">
        <div class="tw-modal-head"><strong>Sembol Seç</strong><button class="tw-close" type="button">×</button></div>
        <input class="tw-search" type="text" placeholder="Sembol ara...">
        <div class="tw-list">
          <?php foreach($symbols as $s): ?>
            <button type="button" class="tw-item" data-s="<?php echo esc_attr($s); ?>"><?php echo esc_html($s); ?></button>
          <?php endforeach; ?>
        </div>
      </div>
    </div>
  </div>
<?php }

/* ===========================
   Sekme içerikleri
   =========================== */
add_action('woocommerce_account_borsa-alim-satim_endpoint', function(){
  $symbols=[
    'DJI','IXIC','RUT','FTSE','GDAXI','FCHI','IBEX','AEX','OMXS30','SSMI','ATX','OMXC25','OMXH25','BFX','HSI','STI','AXJO',
    'AAPL','MSFT','GOOGL','AMZN','TSLA','NVDA','META','NFLX',
  ];
  tw_render_trade_box('borsa','CANLI BORSALAR (Dünya & Avrupa)',$symbols);
});
add_action('woocommerce_account_emtia-alim-satim_endpoint', function(){
  $symbols = ['XAUUSD','XAGUSD','XPTUSD','XPDUSD','USOIL','UKOIL','NATGAS'];
  tw_render_trade_box('emtia','CANLI EMTİA',$symbols);
});
add_action('woocommerce_account_kripto-alim-satim_endpoint', function(){
  $symbols = ['BTCUSDT','ETHUSDT','BNBUSDT','SOLUSDT','XRPUSDT'];
  tw_render_trade_box('kripto','CANLI KRİPTO PARALAR',$symbols);
});

/* ===========================
   Cüzdan: ikonlar
   =========================== */
if (!function_exists('xeco_svg_green_uri')) {
  function xeco_svg_green_uri($d){
    $svg = "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%2316a34a' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'><path d=\"{$d}\"/></svg>";
    return "data:image/svg+xml;utf8,".rawurlencode($svg);
  }
}
add_action('wp_head', function () {
  $icons = [
    'dashboard'          => xeco_svg_green_uri('M3 10l9-7 9 7M5 10v10h5v-6h4v6h5V10'),
    'cuzdanim'           => xeco_svg_green_uri('M3 7h14a3 3 0 0 1 3 3v4a3 3 0 0 1-3 3H3a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2zm13 5h4'),
    'borsa-alim-satim'   => xeco_svg_green_uri('M3 17l6-6 4 4 8-10'),
    'emtia-alim-satim'   => xeco_svg_green_uri('M12 3l9 5-9 5-9-5 9-5zM3 8v8l9 5 9-5V8'),
    'kripto-alim-satim'  => xeco_svg_green_uri('M7 3h10l5 9-5 9H7L2 12 7 3z'),
    'edit-account'       => xeco_svg_green_uri('M12 12a4 4 0 1 0-4-4 4 4 0 0 0 4 4zm-8 9a8 8 0 0 1 16 0'),
    'musteri-hizmetleri' => xeco_svg_green_uri('M4 12a8 8 0 1 1 16 0v3a2 2 0 0 1-2 2h-2v-4h4v-1a7 7 0 1 0-14 0v1h4v4H6a2 2 0 0 1-2-2v-3'),
    'customer-logout'    => xeco_svg_green_uri('M10 21H6a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4M15 16l5-4-5-4M20 12H10'),
  ];
  ?>
  <style>
    .woocommerce-account .xeco-ico{
      display:inline-block; width:20px; height:20px; margin-right:10px;
      background-size:20px 20px; background-repeat:no-repeat; background-position:center;
      vertical-align:middle; filter: drop-shadow(0 2px 4px rgba(22,163,74,.25));
    }
    .woocommerce-account nav a, .woocommerce-MyAccount-navigation a{
      display:flex; align-items:center; gap:10px;
    }
  </style>
  <script>
    (function(){
      var roots = document.querySelectorAll(
        '.woocommerce-MyAccount-navigation, nav.woocommerce-MyAccount-navigation, .account-navigation, .my-account-navigation'
      );
      if(!roots.length) return;

      var ICONS = <?php echo json_encode($icons, JSON_UNESCAPESLASHES ?? $icons); ?>;
      // older PHP may not have JSON_UNESCAPESLASHES — but json_encode should work
      if (typeof ICONS === 'string') try { ICONS = JSON.parse(ICONS); } catch(e){}

      function pickKey(href){
        if(!href) return null;
        var keys = Object.keys(ICONS);
        for(var i=0;i<keys.length;i++){
          if(href.indexOf(keys[i]) !== -1) return keys[i];
        }
        if (/(my\-account|account|dashboard)\/?$/.test(href)) return 'dashboard';
        return null;
      }

      roots.forEach(function(root){
        root.querySelectorAll('a').forEach(function(a){
          if (a.querySelector('.xeco-ico')) return;
          var key = pickKey(a.getAttribute('href') || '');
          if(!key) return;
          var span = document.createElement('span');
          span.className = 'xeco-ico';
          span.style.backgroundImage = 'url("'+ICONS[key]+'")';
          a.insertBefore(span, a.firstChild);
        });
      });
    })();
  </script>
  <?php
}, 999);

/* ===========================
   💵 FULL WALLET SYSTEM (USD) — Ledger + Limits + Withdraw + Top-up + Cüzdandan Öde + Admin Panel
   =========================== */

/* 1) Ledger tablo */
function uv_wallet_install_table() {
  global $wpdb;
  $table   = $wpdb->prefix.'uv_wallet_ledger';
  $charset = $wpdb->get_charset_collate();
  $sql = "CREATE TABLE IF NOT EXISTS $table (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    user_id BIGINT UNSIGNED NOT NULL,
    actor_id BIGINT UNSIGNED NULL,
    delta DECIMAL(18,2) NOT NULL,
    balance_after DECIMAL(18,2) NOT NULL,
    reason VARCHAR(120) NOT NULL,
    ref VARCHAR(191) NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    KEY user_id (user_id),
    KEY created_at (created_at)
  ) $charset;";
  require_once ABSPATH.'wp-admin/includes/upgrade.php';
  dbDelta($sql);
}
add_action('after_switch_theme','uv_wallet_install_table');
add_action('init','uv_wallet_install_table'); // ekstra garanti

/* 2) Yardımcılar */
function uv_wallet_get($uid){ return (float) get_user_meta($uid,'uv_wallet_balance_USD',true); }
function uv_wallet_set($uid,$amount){ update_user_meta($uid,'uv_wallet_balance_USD', round((float)$amount,2)); }
function uv_wallet_add($uid,$delta,$reason,$ref='',$actor=0){
  global $wpdb;
  $actor = $actor ?: get_current_user_id();
  $old   = uv_wallet_get($uid);
  $new   = max(0, round($old + (float)$delta, 2));
  uv_wallet_set($uid,$new);
  $wpdb->insert($wpdb->prefix.'uv_wallet_ledger',[
    'user_id'       => $uid,
    'actor_id'      => $actor ?: null,
    'delta'         => round($delta,2),
    'balance_after' => $new,
    'reason'        => sanitize_text_field($reason),
    'ref'           => sanitize_text_field($ref),
    'created_at'    => current_time('mysql')
  ]);
  return $new;
}
function uv_wallet_logs($uid,$limit=20){
  global $wpdb;
  return $wpdb->get_results($wpdb->prepare(
    "SELECT * FROM {$wpdb->prefix}uv_wallet_ledger WHERE user_id=%d ORDER BY id DESC LIMIT %d",
    $uid, $limit
  ));
}

/* 3) Varsayılan meta */
add_action('user_register', function($uid){
  add_user_meta($uid,'uv_wallet_balance_USD',0,true);
  add_user_meta($uid,'uv_invest_limit_USD',100000,true);
  add_user_meta($uid,'uv_withdraw_limit_USD',10000,true);
});

/* 4) Admin kullanıcı alanları */
add_action('show_user_profile','uv_wallet_admin_fields');
add_action('edit_user_profile','uv_wallet_admin_fields');
function uv_wallet_admin_fields($user){
  $b = uv_wallet_get($user->ID);
  $i = (float) get_user_meta($user->ID,'uv_invest_limit_USD',true);
  $w = (float) get_user_meta($user->ID,'uv_withdraw_limit_USD',true);
  ?>
  <h2>💰 Wallet & Limit Yönetimi (USD)</h2>
  <table class="form-table">
    <tr><th><label>Bakiye (USD)</label></th>
      <td><input type="number" step="0.01" name="uv_wallet_balance_USD" value="<?php echo esc_attr($b); ?>"></td></tr>
    <tr><th><label>Yatırım Limiti (USD)</label></th>
      <td><input type="number" step="0.01" name="uv_invest_limit_USD" value="<?php echo esc_attr($i); ?>"></td></tr>
    <tr><th><label>Günlük Çekim Limiti (USD)</label></th>
      <td><input type="number" step="0.01" name="uv_withdraw_limit_USD" value="<?php echo esc_attr($w); ?>"></td></tr>
    <tr><th><label>🎁 Hediye Bakiye (anında ekle)</label></th>
      <td>
        <input type="number" step="0.01" name="uv_wallet_bonus" value="0">
        <p class="description">Pozitif rakam ekler, negatif rakam düşer.</p>
      </td></tr>
  </table>
  <?php
}
add_action('personal_options_update','uv_wallet_admin_save');
add_action('edit_user_profile_update','uv_wallet_admin_save');
function uv_wallet_admin_save($uid){
  if(!current_user_can('edit_users')) return;
  $old = uv_wallet_get($uid);
  if (isset($_POST['uv_wallet_balance_USD'])) {
    $new = round((float)$_POST['uv_wallet_balance_USD'],2);
    if ($new !== $old) uv_wallet_add($uid, $new - $old, 'admin_adjust', 'profile_set');
  }
  foreach(['uv_invest_limit_USD','uv_withdraw_limit_USD'] as $m){
    if(isset($_POST[$m])) update_user_meta($uid,$m, round((float)$_POST[$m],2));
  }
  if (!empty($_POST['uv_wallet_bonus']) && (float)$_POST['uv_wallet_bonus'] != 0) {
    uv_wallet_add($uid, round((float)$_POST['uv_wallet_bonus'],2), 'admin_bonus', 'profile_bonus');
  }
}

/* 5) Admin menüleri – Defter + Yöneticisi */
add_action('admin_menu', function(){
  add_menu_page('Cüzdan Yönetimi','Finans Yönetimi','manage_options','uv-wallet','uv_wallet_dashboard','dashicons-money-alt',56);
  add_submenu_page('uv-wallet','Cüzdan Defteri','Cüzdan Defteri','manage_options','uv-wallet-ledger','uv_wallet_ledger_page');
  add_submenu_page('uv-wallet','Cüzdan Yöneticisi','Cüzdan Yöneticisi','manage_options','uv-wallet-manager','uv_wallet_manager_page');
});
function uv_wallet_dashboard(){
  echo '<div class="wrap"><h1>Finans Yönetimi</h1><p>Sol menüden "Cüzdan Defteri" veya "Cüzdan Yöneticisi"ni kullanın.</p></div>';
}
function uv_wallet_ledger_page(){
  if(!current_user_can('manage_options')) return;
  global $wpdb;
  $table  = $wpdb->prefix.'uv_wallet_ledger';
  $search = isset($_GET['s']) ? sanitize_text_field($_GET['s']) : '';
  $where  = $search ? $wpdb->prepare("WHERE reason LIKE %s OR ref LIKE %s","%$search%","%$search%") : '';
  $rows   = $wpdb->get_results("SELECT * FROM $table $where ORDER BY id DESC LIMIT 500");

  echo '<div class="wrap"><h1>🧾 Cüzdan Defteri</h1>';
  echo '<form method="get"><input type="hidden" name="page" value="uv-wallet-ledger">';
  echo '<input type="search" name="s" placeholder="İşlem ara..." value="'.esc_attr($search).'" style="padding:6px 10px;width:260px"> ';
  echo '<button class="button">Ara</button></form><br>';
  if(!$rows){ echo '<p>Henüz kayıt yok.</p></div>'; return; }
  echo '<table class="widefat fixed striped"><thead><tr>
        <th>ID</th><th>Kullanıcı</th><th>Actor</th><th>Sebep</th><th>Tutar</th><th>Son Bakiye</th><th>Tarih</th><th>Ref</th></tr></thead><tbody>';
  foreach($rows as $r){
    $u = get_user_by('id',$r->user_id);
    $a = $r->actor_id ? get_user_by('id',$r->actor_id) : null;
    $clr = $r->delta<0? '#dc2626':'#16a34a';
    echo '<tr><td>'.$r->id.'</td><td>'.($u?'<a href="'.esc_url(get_edit_user_link($r->user_id)).'">'.$u->display_name.'</a>':'—').'</td>';
    echo '<td>'.($a?$a->display_name:'—').'</td><td>'.esc_html($r->reason).'</td>';
    echo '<td style="color:'.$clr.';">'.($r->delta>0?'+':'').'$'.number_format($r->delta,2).'</td>';
    echo '<td>$'.number_format($r->balance_after,2).'</td><td>'.esc_html($r->created_at).'</td><td>'.esc_html($r->ref).'</td></tr>';
  }
  echo '</tbody></table></div>';
}
function uv_wallet_manager_page(){
  if(!current_user_can('manage_options')) return;
  $uid = isset($_GET['user_id']) ? absint($_GET['user_id']) : 0;
  $user = $uid ? get_user_by('id',$uid) : null;

  echo '<div class="wrap"><h1>👤 Cüzdan Yöneticisi</h1>';
  echo '<form method="get" style="margin-bottom:10px;"><input type="hidden" name="page" value="uv-wallet-manager">
        <input type="number" name="user_id" placeholder="Kullanıcı ID" value="'.($uid?:'').'" style="padding:6px 10px;width:140px"> 
        <button class="button">Yükle</button></form>';

  if(!$user){ echo '<p>Kullanıcı ID girin.</p></div>'; return; }

  $bal     = uv_wallet_get($uid);
  $invest  = (float) get_user_meta($uid,'uv_invest_limit_USD',true);
  $withdr  = (float) get_user_meta($uid,'uv_withdraw_limit_USD',true);
  $logs    = uv_wallet_logs($uid,20);

  echo '<h2>'.$user->display_name.' (#'.$uid.')</h2>';
  echo '<p><strong>Bakiye:</strong> $'.number_format($bal,2).' | <strong>Yatırım Limiti:</strong> $'.number_format($invest,2).' | <strong>Günlük Çekim Limiti:</strong> $'.number_format($withdr,2).'</p>';

  // Hızlı işlemler
  echo '<h3>Hızlı İşlemler</h3>
  <form method="post" action="'.esc_url(admin_url('admin-post.php')).'" style="display:flex;gap:10px;align-items:center;flex-wrap:wrap">
    <input type="hidden" name="action" value="uv_wallet_manager_action">
    <input type="hidden" name="user_id" value="'.$uid.'">
    '.wp_nonce_field('uv_wallet_manager','uvm_nonce',true,false).'
    <select name="op">
      <option value="deposit">+ Bakiyeye Ekle</option>
      <option value="withdraw">- Bakiyeden Düş</option>
      <option value="set">Bakiyeyi Ayarla</option>
      <option value="bonus">🎁 Hediye Bakiye</option>
      <option value="set_limits">Limitleri Ayarla</option>
    </select>
    <input type="number" step="0.01" name="amount" placeholder="Tutar (USD)">
    <input type="number" step="0.01" name="invest_limit" placeholder="Yatırım Limiti (USD)">
    <input type="number" step="0.01" name="withdraw_limit" placeholder="Çekim Limiti (USD)">
    <input type="text" name="note" placeholder="Not/Referans">
    <button class="button button-primary">Uygula</button>
  </form><br>';

  echo '<h3>Son İşlemler</h3>';
  if(!$logs){ echo '<p>Kayıt yok.</p>'; }
  else{
    echo '<table class="widefat striped"><thead><tr><th>Tarih</th><th>Tür</th><th>Tutar</th><th>Son Bakiye</th><th>Ref</th></tr></thead><tbody>';
    foreach($logs as $r){
      $clr = $r->delta<0? 'style="color:#dc2626"':'style="color:#16a34a"';
      echo '<tr><td>'.esc_html($r->created_at).'</td><td>'.esc_html($r->reason).'</td><td '.$clr.'>'.($r->delta>0?'+':'').'$'.number_format($r->delta,2).'</td><td>$'.number_format($r->balance_after,2).'</td><td>'.esc_html($r->ref).'</td></tr>';
    }
    echo '</tbody></table>';
  }
  echo '</div>';
}
add_action('admin_post_uv_wallet_manager_action', function(){
  if(!current_user_can('manage_options')) wp_die('Nope');
  if(empty($_POST['uvm_nonce']) || !wp_verify_nonce($_POST['uvm_nonce'],'uv_wallet_manager')) wp_die('Bad nonce');
  $uid  = absint($_POST['user_id'] ?? 0);
  $op   = sanitize_text_field($_POST['op'] ?? '');
  $amt  = isset($_POST['amount']) ? round((float)$_POST['amount'],2) : 0;
  $note = sanitize_text_field($_POST['note'] ?? '');

  switch($op){
    case 'deposit':   uv_wallet_add($uid, +$amt, 'admin_deposit', $note); break;
    case 'withdraw':  uv_wallet_add($uid, -$amt, 'admin_withdraw', $note); break;
    case 'set':
      $old = uv_wallet_get($uid);
      uv_wallet_add($uid, round($amt - $old,2), 'admin_set', $note);
      break;
    case 'bonus':     uv_wallet_add($uid, +$amt, 'admin_bonus', $note); break;
    case 'set_limits':
      if(isset($_POST['invest_limit']))  update_user_meta($uid,'uv_invest_limit_USD',  round((float)$_POST['invest_limit'],2));
      if(isset($_POST['withdraw_limit']))update_user_meta($uid,'uv_withdraw_limit_USD',round((float)$_POST['withdraw_limit'],2));
      break;
  }
  wp_safe_redirect(admin_url('admin.php?page=uv-wallet-manager&user_id='.$uid));
  exit;
});

/* 6) “Bakiye Yükle” ürünü ve otomatik yatırma */
function uv_ensure_topup_product(){
  $sku='WALLET-TOPUP';
  if(function_exists('wc_get_product_id_by_sku')){
    $pid=wc_get_product_id_by_sku($sku);
    if($pid) return $pid;
  }
  $pid = wp_insert_post(['post_title'=>'Wallet Top-Up','post_type'=>'product','post_status'=>'publish','post_content'=>'Cüzdana USD yüklemek için. Adet = yüklenecek USD.']);
  if($pid && !is_wp_error($pid)){
    update_post_meta($pid,'_sku',$sku);
    update_post_meta($pid,'_price','1');
    update_post_meta($pid,'_regular_price','1');
    update_post_meta($pid,'_virtual','yes');
    update_post_meta($pid,'_sold_individually','no');
    wp_set_object_terms($pid,'simple','product_type',false);
  }
  return $pid;
}
add_action('init','uv_ensure_topup_product');

function uv_wallet_credit_on_paid($order_id){
  $order = wc_get_order($order_id);
  if(!$order) return;
  $uid = $order->get_user_id();
  if(!$uid) return;

  $sum = 0;
  foreach($order->get_items() as $item){
    $p = $item->get_product(); if(!$p) continue;
    if($p->get_sku()==='WALLET-TOPUP'){ $sum += (float)$item->get_total(); }
  }
  if($sum>0){ uv_wallet_add($uid, $sum, 'deposit', 'order#'.$order->get_id()); }
}
add_action('woocommerce_order_status_processing','uv_wallet_credit_on_paid');
add_action('woocommerce_order_status_completed', 'uv_wallet_credit_on_paid');


/* 7) Checkout – Cüzdandan Öde + yatırım limiti kontrolü */
add_action('woocommerce_review_order_before_payment', function(){
  if(!is_user_logged_in()) return;
  $bal = uv_wallet_get(get_current_user_id());
  if($bal>0){
    echo '<div style="border:1px solid #16a34a;border-radius:10px;padding:10px;margin-bottom:12px">
      <label><input type="checkbox" name="use_wallet_balance" value="1"> Cüzdanımdan öde (Bakiye: <strong>$'.number_format($bal,2).'</strong>)</label>
    </div>';
  }
});
add_action('woocommerce_checkout_create_order', function($order){
  if(!is_user_logged_in() || empty($_POST['use_wallet_balance'])) return;
  $uid   = get_current_user_id();
  $total = (float)$order->get_total();
  $bal   = uv_wallet_get($uid);
  $limit = (float)get_user_meta($uid,'uv_invest_limit_USD',true);

  if($total > $limit){ wc_add_notice('Yatırım limitiniz ($'.number_format($limit,2).') aşıldı.','error'); return; }
  if($bal   < $total){ wc_add_notice('Cüzdan bakiyeniz yetersiz.','error'); return; }

  uv_wallet_add($uid, -$total, 'order_payment', 'order#'.$order->get_id());
  $order->set_payment_method('wallet');
  $order->update_status('completed','Cüzdandan ödeme yapıldı.');
}, 20);

/* ===========================
   Cüzdan (özet + modal “Para Çek”)
   =========================== */
/* ============ Cüzdanım: Bakiye Yükle modal + buton (AJAX) ============ */
add_action('woocommerce_account_cuzdanim_endpoint', function () {
  if (!is_user_logged_in()) return;

  // Nonce & ajax url
  $nonce   = wp_create_nonce('uv_topup_nonce');
  $ajaxurl = admin_url('admin-ajax.php');

  ?>
  <style>
    .uvtopup-btn{background:#16a34a;color:#fff;border:0;border-radius:999px;padding:10px 18px;cursor:pointer}
    .uvtopup-btn:hover{filter:brightness(1.08)}
    .uvtopup-modal{position:fixed;inset:0;background:rgba(0,0,0,.55);display:none;align-items:center;justify-content:center;z-index:10000}
    .uvtopup-modal.show{display:flex}
    .uvtopup-card{width:min(520px,94vw);background:#0f1319;border:1px solid #202733;border-radius:14px;box-shadow:0 12px 50px rgba(0,0,0,.45);color:#e8f0fb}
    .uvtopup-head{display:flex;align-items:center;justify-content:space-between;padding:14px 16px;border-bottom:1px solid #243041}
    .uvtopup-body{padding:16px}
    .uvtopup-label{display:block;margin:0 0 6px;color:#9aa4b2;font-size:13px}
    .uvtopup-input{
      width:100%;background:#0b0f14;border:1px solid #2a3340;color:#e8f0fb;border-radius:10px;padding:10px 12px;outline:none
    }
    .uvtopup-foot{display:flex;gap:10px;justify-content:flex-end;padding:12px 16px;border-top:1px solid #243041}
    .uvtopup-cancel{background:#263245;color:#cbd5e1;border:0;border-radius:10px;padding:9px 14px;cursor:pointer}
    .uvtopup-submit{background:#16a34a;color:#fff;border:0;border-radius:10px;padding:10px 16px;cursor:pointer}
    .uvtopup-submit:hover{filter:brightness(1.08)}
    .uvtopup-error{color:#f87171;margin-top:8px;font-size:13px;display:none}
  </style>

  <div style="margin:18px 0">
    <button id="uvtopup-open" class="uvtopup-btn">Bakiye Yükle</button>
  </div>

  <div class="uvtopup-modal" id="uvtopup-modal">
    <div class="uvtopup-card">
      <div class="uvtopup-head">
        <strong>Bakiye Yükle (USD)</strong>
        <button type="button" id="uvtopup-close" class="uvtopup-cancel">Kapat</button>
      </div>
      <div class="uvtopup-body">
        <label class="uvtopup-label">Yükleme Tutarı (USD) *</label>
        <input id="uvtopup-amount" class="uvtopup-input" type="number" step="0.01" min="1" placeholder="ör: 250.00">
        <div id="uvtopup-err" class="uvtopup-error"></div>
      </div>
      <div class="uvtopup-foot">
        <button type="button" class="uvtopup-cancel" id="uvtopup-cancel-2">Vazgeç</button>
        <button type="button" class="uvtopup-submit" id="uvtopup-submit">Devam Et</button>
      </div>
    </div>
  </div>

  <script>
  (function(){
    var m   = document.getElementById('uvtopup-modal');
    var o   = document.getElementById('uvtopup-open');
    var c1  = document.getElementById('uvtopup-close');
    var c2  = document.getElementById('uvtopup-cancel-2');
    var amt = document.getElementById('uvtopup-amount');
    var err = document.getElementById('uvtopup-err');
    var go  = document.getElementById('uvtopup-submit');
    var ajax = "<?php echo esc_js($ajaxurl); ?>";
    var nonce = "<?php echo esc_js($nonce); ?>";

    function show(){ if(m) m.classList.add('show'); }
    function hide(){ if(m) m.classList.remove('show'); if(err){ err.style.display='none'; err.textContent=''; } }

    if(o)  o.addEventListener('click', show);
    if(c1) c1.addEventListener('click', hide);
    if(c2) c2.addEventListener('click', hide);
    if(m)  m.addEventListener('click', function(e){ if(e.target === m) hide(); });

    function post(data){
      return fetch(ajax, {
        method: 'POST',
        headers: { 'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8' },
        body: new URLSearchParams(data).toString()
      }).then(function(r){ return r.json(); });
    }

    if(go){
      go.addEventListener('click', function(){
        var v = parseFloat(amt && amt.value ? amt.value : '0');
        if(!v || v <= 0){
          if(err){ err.textContent = 'Lütfen geçerli bir tutar girin.'; err.style.display='block'; }
          return;
        }
        if(err){ err.style.display='none'; err.textContent=''; }
        go.disabled = true;

        post({ action:'uv_topup_add', amount: v.toFixed(2), nonce: nonce })
          .then(function(res){
            go.disabled = false;
            if(res && res.success && res.data && res.data.redirect){
              window.location.href = res.data.redirect;
            } else {
              if(err){ err.textContent = (res && res.data && res.data.msg) ? res.data.msg : 'İşlem başarısız.'; err.style.display='block'; }
            }
          })
          .catch(function(){
            go.disabled = false;
            if(err){ err.textContent = 'Ağ hatası. Lütfen tekrar deneyin.'; err.style.display='block'; }
          });
      });
    }
  })();
  </script>
  <?php
});

/* Cüzdan özet (koru) */
add_action('woocommerce_account_cuzdanim_endpoint', function(){
  if(!is_user_logged_in()) return;
  $uid=get_current_user_id();
  $bal=uv_wallet_get($uid);
  $orders=wc_get_orders(['customer'=>$uid,'status'=>['processing','completed','on-hold','pending'],'limit'=>20,'orderby'=>'date','order'=>'DESC','return'=>'objects']);
  $total=0; $rows=[];
  foreach($orders as $o){
    $t=(float)$o->get_total(); $total+=$t;
    $d=$o->get_date_created(); $ds=$d?$d->date_i18n('d.m.y / H:i'):'-';
    $desc=''; $items=$o->get_items();
    if(!empty($items)){
      $f=reset($items); $name=$f?$f->get_name():'';
      $sym=$f?$f->get_meta('tw_symbol'):''; $side=$f?$f->get_meta('tw_side'):''; $type=$f?$f->get_meta('tw_type'):'';
      $desc = ($sym||$side||$type) ? sprintf('%s %s (%s)',strtoupper($sym),strtoupper($side),$type?:'işlem') : $name;
    }
    if(!$desc) $desc='Sipariş #'.$o->get_order_number();
    $rows[]=['date'=>$ds,'desc'=>esc_html($desc),'amount'=>wc_price($t,['currency'=>$o->get_currency()]),'status'=>wc_get_order_status_name($o->get_status())];
  }

  echo '<div class="tw-wallet-wrap"><div class="tw-wallet-header"><div class="tw-wallet-title">CÜZDAN BAKİYESİ: <strong>$'.number_format($bal,2).'</strong></div><div class="tw-wallet-sub">Sipariş Toplamı: <strong>'.wc_price($total).'</strong></div></div><hr class="tw-sep"/><h3 class="tw-h3">İşlem Geçmişi</h3>';
  if(empty($rows)){ echo '<p>Henüz bir işlem yok.</p>'; }
  else{
    echo '<div class="tw-table"><div class="tw-thead"><div class="tw-th">Tarih / Saat</div><div class="tw-th">İşlem Açıklaması</div><div class="tw-th tw-right">Tutar</div></div>';
    foreach($rows as $r){ echo '<div class="tw-tr"><div class="tw-td">'.esc_html($r['date']).'</div><div class="tw-td">'.$r['desc'].' <span class="tw-status">'.esc_html($r['status']).'</span></div><div class="tw-td tw-right">'.$r['amount'].'</div></div>'; }
    echo '</div>';
  }
  echo '</div>';
});

/* Para Çek butonu + modal (USD) — GÜNCELLENDİ: Kullanıcı seçimli (Bank / Crypto) */
add_action('woocommerce_account_cuzdanim_endpoint', function () {
    if (!is_user_logged_in()) return;

    $uid        = get_current_user_id();
    $bal        = uv_wallet_get($uid);
    $bal_attr   = esc_attr($bal);
    $bal_price  = '$'.number_format($bal,2);
    $user       = wp_get_current_user();
    $name       = trim(($user->first_name ?? '') . ' ' . ($user->last_name ?? ''));
    if ($name === '') { $name = $user->display_name ?: $user->user_login; }
    $name_attr  = esc_attr($name);
    $action_url = esc_url(admin_url('admin-post.php'));
    $nonce_field = wp_nonce_field('xeco_withdraw_usd', 'xw_nonce', true, false);

    // form template with method selection (bank or crypto)
    $tpl = <<<'HTML'
<div style="margin:18px 0"><button id="xw-open" class="xw-btn">Para Çek</button></div>

<style>
.xw-btn{background:#16a34a;color:#fff;border:0;border-radius:999px;padding:10px 18px;cursor:pointer}
.xw-btn:hover{filter:brightness(1.08)}
.xw-modal{position:fixed;inset:0;background:rgba(0,0,0,.55);display:none;align-items:center;justify-content:center;z-index:10000}
.xw-modal.show{display:flex}
.xw-card{width:min(720px,96vw);background:#0f1319;border:1px solid #202733;border-radius:14px;
  box-shadow:0 12px 50px rgba(0,0,0,.45);color:#e8f0fb}
.xw-head{display:flex;align-items:center;justify-content:space-between;padding:14px 16px;border-bottom:1px solid #243041}
.xw-body{padding:16px}
.xw-grid{display:grid;grid-template-columns:1fr 1fr;gap:14px}
.xw-grid + .xw-grid{margin-top:12px}
.xw-full{grid-column:1/-1}
.xw-label{display:block;margin:0 0 6px;color:#9aa4b2;font-size:13px}
.xw-input,.xw-text,select{
  width:100%;
  background:#0b0f14;
  border:1px solid #2a3340;
  color:#e8f0fb;
  border-radius:10px;
  padding:10px 12px;
  outline:none;
}
.xw-foot{display:flex;gap:10px;justify-content:flex-end;padding:12px 16px;border-top:1px solid #243041}
.xw-cancel{background:#263245;color:#cbd5e1;border:0;border-radius:10px;padding:9px 14px;cursor:pointer}
.xw-submit{background:#16a34a;color:#fff;border:0;border-radius:10px;padding:10px 16px;cursor:pointer}
.xw-submit:hover{filter:brightness(1.08)}
.xw-hint{font-size:12px;color:#9aa4b2;margin-top:4px}
.xw-radio{display:flex;gap:12px;align-items:center}
.xw-coin-row{display:flex;gap:8px}
.xw-input::placeholder{color:#9aa4b2}
</style>

<div class="xw-modal" id="xw-modal">
  <div class="xw-card">
    <div class="xw-head">
      <strong>Para Çekim Talebi</strong>
      <button type="button" id="xw-close" class="xw-cancel">Kapat</button>
    </div>

    <form method="post" action="{{ACTION}}">
      <div class="xw-body">
        <div class="xw-grid">
          <div>
            <label class="xw-label">Yatırımcı Adı Soyadı</label>
            <input class="xw-input" type="text" name="name" value="{{NAME}}" readonly>
          </div>
          <div>
            <label class="xw-label">Çekilmek İstenen Tutar (USD) *</label>
            <input class="xw-input" type="number" step="0.01" min="1" max="{{BAL_ATTR}}" name="amount" required placeholder="ör: 1500.00">
            <div class="xw-hint">Mevcut Bakiye: <strong>{{BAL_PRICE}}</strong></div>
          </div>
        </div>

        <div class="xw-grid">
          <div class="xw-full">
            <label class="xw-label">Çekim Yöntemi</label>
            <div class="xw-radio">
              <label><input type="radio" name="method" value="bank" checked> Havale / EFT (IBAN)</label>
              <label><input type="radio" name="method" value="crypto"> Kripto (Adres)</label>
            </div>
          </div>
        </div>

        <div class="xw-grid xw-bank-block">
          <div class="xw-full">
            <label class="xw-label">Banka Adı</label>
            <input class="xw-input" type="text" name="bank_name" placeholder="Banka adı (ör: Ziraat Bankası)">
          </div>
          <div class="xw-full">
            <label class="xw-label">IBAN</label>
            <input class="xw-input" type="text" name="iban" placeholder="TR________________________">
          </div>
        </div>

        <div class="xw-grid xw-crypto-block" style="display:none">
          <div>
            <label class="xw-label">Coin</label>
            <select name="crypto_coin" class="xw-input">
              <option value="">Seçiniz…</option>
              <option value="USDT">USDT (TRC20)</option>
              <option value="BTC">BTC</option>
              <option value="ETH">ETH</option>
            </select>
          </div>
          <div>
            <label class="xw-label">Kripto Adresi</label>
            <input class="xw-input" type="text" name="crypto_address" placeholder="Adres veya etiket girin">
          </div>
          <div class="xw-full">
            <label class="xw-label">Açıklama / Not</label>
            <textarea class="xw-text" name="desc" placeholder="İsteğe bağlı not..."></textarea>
          </div>
        </div>

        <div class="xw-grid">
          <div class="xw-full">
            <label class="xw-label">İlave Açıklama (opsiyonel)</label>
            <textarea class="xw-text" name="desc_general" placeholder="Notunuz..."></textarea>
          </div>
        </div>

      </div>

      <div class="xw-foot">
        <input type="hidden" name="action" value="xeco_withdraw_usd">
        {{NONCE}}
        <button type="button" class="xw-cancel" id="xw-cancel-2">Vazgeç</button>
        <button type="submit" class="xw-submit">Gönder</button>
      </div>
    </form>
  </div>
</div>

<script>
(function(){
  var m = document.getElementById('xw-modal');
  var open = document.getElementById('xw-open');
  var close1 = document.getElementById('xw-close');
  var close2 = document.getElementById('xw-cancel-2');

  function show(){ if(m) m.classList.add('show'); }
  function hide(){ if(m) m.classList.remove('show'); }

  if(open) open.addEventListener('click', show);
  if(close1) close1.addEventListener('click', hide);
  if(close2) close2.addEventListener('click', hide);
  if(m) m.addEventListener('click', function(e){ if(e.target === m) hide(); });

  var radios = document.querySelectorAll('input[name="method"]');
  function toggleBlocks(){
    var v = document.querySelector('input[name="method"]:checked').value;
    var bank = document.querySelectorAll('.xw-bank-block');
    var crypto = document.querySelectorAll('.xw-crypto-block');
    if(v==='bank'){
      bank.forEach(function(el){ el.style.display='grid'; });
      crypto.forEach(function(el){ el.style.display='none'; });
    } else {
      bank.forEach(function(el){ el.style.display='none'; });
      crypto.forEach(function(el){ el.style.display='grid'; });
    }
  }
  radios.forEach(function(r){ r.addEventListener('change', toggleBlocks); });
  document.addEventListener('DOMContentLoaded', toggleBlocks);
})();
</script>
HTML;

    $html = strtr(
        $tpl,
        [
            '{{ACTION}}'   => $action_url,
            '{{NAME}}'     => $name_attr,
            '{{BAL_ATTR}}' => $bal_attr,
            '{{BAL_PRICE}}'=> $bal_price,
            '{{NONCE}}'    => $nonce_field,
        ]
    );

    echo $html;
});

/* Çekim handler (USD) – limit & bakiye kontrol + ledger + e-posta (BANK) */
add_action('admin_post_xeco_withdraw_usd','xeco_handle_withdraw_usd');
add_action('admin_post_nopriv_xeco_withdraw_usd','xeco_handle_withdraw_usd');
function xeco_handle_withdraw_usd(){
  if (!is_user_logged_in()) wp_die('Yetkisiz işlem');
  if (empty($_POST['xw_nonce']) || !wp_verify_nonce($_POST['xw_nonce'], 'xeco_withdraw_usd')) wp_die('Geçersiz istek');

  $uid    = get_current_user_id();
  $amount = round((float) ($_POST['amount'] ?? 0),2);
  $method = sanitize_text_field($_POST['method'] ?? 'bank');
  $desc_general = sanitize_textarea_field($_POST['desc_general'] ?? '');

  $bal   = uv_wallet_get($uid);
  $limit = (float) get_user_meta($uid,'uv_withdraw_limit_USD',true);

  if ($amount <= 0 || $amount > $bal) {
    wc_add_notice('Geçersiz tutar. Lütfen bakiyenizden küçük bir tutar giriniz.','error');
    wp_safe_redirect(wc_get_account_endpoint_url('cuzdanim')); exit;
  }
  if ($amount > $limit){
    wc_add_notice('Günlük çekim limitiniz ($'.number_format($limit,2).') aşıldı.','error');
    wp_safe_redirect(wc_get_account_endpoint_url('cuzdanim')); exit;
  }

  if ($method === 'bank') {
    $iban   = sanitize_text_field($_POST['iban'] ?? '');
    $bank_name = sanitize_text_field($_POST['bank_name'] ?? '');
    if (empty($iban)) {
      wc_add_notice('Lütfen IBAN giriniz.','error');
      wp_safe_redirect(wc_get_account_endpoint_url('cuzdanim')); exit;
    }
    // bütün kontroller geçti -> ledger kaydı ve mail
    uv_wallet_add($uid, -$amount, 'withdraw_bank', 'request');

    $user  = wp_get_current_user();
    $name  = trim(($user->first_name ?? '') . ' ' . ($user->last_name ?? '')) ?: ($user->display_name ?: $user->user_login);
    $admin = get_option('admin_email');
    $subject = 'Yeni Para Çekim Talebi (USD) - Havale/EFT';
    $body = "Kullanıcı: {$name} (ID: {$uid})\n".
            "Tutar: \${$amount}\n".
            "Banka: {$bank_name}\n".
            "IBAN: {$iban}\n".
            "Açıklama: {$desc_general}\n".
            "Kalan Bakiye: $".number_format(uv_wallet_get($uid),2)."\n";
    wp_mail($admin, $subject, $body, ['Content-Type: text/plain; charset=UTF-8']);

    wc_add_notice('Talebiniz alındı. İşleminiz kısa süre içinde değerlendirilecektir.','success');
    wp_safe_redirect(wc_get_account_endpoint_url('cuzdanim')); exit;
  } else {
    // Eğer "crypto" seçildiyse, kullancı adres ve coin bilgileri admin'e gönderilecek.
    // Burada ayrı action veya handler gereksinimi olabilir; biz aynı handler içinde işleriz.
    $coin = sanitize_text_field($_POST['crypto_coin'] ?? '');
    $addr = sanitize_text_field($_POST['crypto_address'] ?? '');
    $desc = sanitize_textarea_field($_POST['desc'] ?? '');
    if (empty($coin) || empty($addr)) {
      wc_add_notice('Lütfen coin türü ve kripto adresi giriniz.','error');
      wp_safe_redirect(wc_get_account_endpoint_url('cuzdanim')); exit;
    }

    // kaydı yap (withdraw_crypto) ve mail at
    uv_wallet_add($uid, -$amount, 'withdraw_crypto', 'request');

    $user  = wp_get_current_user();
    $name  = trim(($user->first_name ?? '') . ' ' . ($user->last_name ?? '')) ?: ($user->display_name ?: $user->user_login);
    $admin = get_option('admin_email');
    $subject = 'Yeni Para Çekim Talebi (USD) - Kripto';
    $body = "Kullanıcı: {$name} (ID: {$uid})\n".
            "Tutar: \${$amount}\n".
            "Coin: {$coin}\n".
            "Adres: {$addr}\n".
            "Açıklama: {$desc}\n".
            "Genel Not: {$desc_general}\n".
            "Kalan Bakiye: $".number_format(uv_wallet_get($uid),2)."\n";
    wp_mail($admin, $subject, $body, ['Content-Type: text/plain; charset=UTF-8']);

    wc_add_notice('Kripto çekim talebiniz alındı. İşlem kısa süre içinde değerlendirilecektir.','success');
    wp_safe_redirect(wc_get_account_endpoint_url('cuzdanim')); exit;
  }
}

/* ===========================
   “Cüzdanım” içeriği – USD + limitler + son işlemler (özet blok)
   =========================== */
add_action('woocommerce_account_cuzdanim_endpoint', function(){
  if(!is_user_logged_in()) return;
  $uid      = get_current_user_id();
  $bal      = uv_wallet_get($uid);
  $invest   = (float)get_user_meta($uid,'uv_invest_limit_USD',true);
  $withdraw = (float)get_user_meta($uid,'uv_withdraw_limit_USD',true);
  $logs     = uv_wallet_logs($uid,10);

  echo '<div style="background:#0f1319;border:1px solid #202733;border-radius:12px;padding:16px;margin-top:14px">';
  echo '<h3>💰 CÜZDAN BAKİYESİ: $'.number_format($bal,2).'</h3>';
  echo '<p style="color:#9aa4b2">Yatırım Limiti: $'.number_format($invest,2).' &nbsp; • &nbsp; Günlük Çekim Limiti: $'.number_format($withdraw,2).'</p>';
  echo '<hr><h4>🧾 Son İşlemler</h4>';
  if(!$logs){ echo '<p>Henüz işlem yok.</p>'; }
  else{
    echo '<table style="width:100%;border-collapse:collapse;font-size:13px">
            <tr><th align="left">Tarih</th><th align="left">Açıklama</th><th align="right">Tutar</th></tr>';
    foreach($logs as $r){
      $clr = $r->delta<0?'#f87171':'#34d399';
      echo '<tr><td>'.esc_html($r->created_at).'</td><td>'.esc_html($r->reason.' '.$r->ref).'</td><td align="right" style="color:'.$clr.'">'.($r->delta>0?'+':'').'$'.number_format($r->delta,2).'</td></tr>';
    }
    echo '</table>';
  }
  echo '</div>';
}, 2);

/* ===========================
   Kayıt formu ekstra alanlar
   =========================== */
add_action('woocommerce_register_form_start', function() {
    ?>
    <p class="form-row form-row-first">
        <label for="reg_first_name">Ad <span class="required">*</span></label>
        <input type="text" name="first_name" id="reg_first_name" value="<?php echo esc_attr($_POST['first_name'] ?? ''); ?>" />
    </p>
    <p class="form-row form-row-last">
        <label for="reg_last_name">Soyad <span class="required">*</span></label>
        <input type="text" name="last_name" id="reg_last_name" value="<?php echo esc_attr($_POST['last_name'] ?? ''); ?>" />
    </p>
    <p class="form-row form-row-wide">
        <label for="reg_phone">Telefon Numarası <span class="required">*</span></label>
        <input type="text" name="phone" id="reg_phone" value="<?php echo esc_attr($_POST['phone'] ?? ''); ?>" />
    </p>
    <div class="clear"></div>
    <?php
});
add_action('woocommerce_register_post', function($username, $email, $errors) {
    if (empty($_POST['first_name']))
        $errors->add('first_name_error', '<strong>Hata:</strong> Lütfen adınızı girin.');
    if (empty($_POST['last_name']))
        $errors->add('last_name_error', '<strong>Hata:</strong> Lütfen soyadınızı girin.');
    if (empty($_POST['phone']))
        $errors->add('phone_error', '<strong>Hata:</strong> Lütfen telefon numaranızı girin.');
}, 10, 3);
add_action('woocommerce_created_customer', function($customer_id) {
    if (!empty($_POST['first_name']))
        update_user_meta($customer_id, 'first_name', sanitize_text_field($_POST['first_name']));
    if (!empty($_POST['last_name']))
        update_user_meta($customer_id, 'last_name', sanitize_text_field($_POST['last_name']));
    if (!empty($_POST['phone']))
        update_user_meta($customer_id, 'billing_phone', sanitize_text_field($_POST['phone']));
});

/* ===========================
   Sembol Seç modalı – scroll
   =========================== */
add_action('wp_head', function(){ ?>
<style>
.tw-modal{position:fixed;inset:0;background:rgba(0,0,0,.5);display:flex;align-items:center;justify-content:center;z-index:9999}
.tw-modal[hidden]{display:none!important}
.tw-modal .tw-modal-content{width:min(700px,94vw);max-height:min(82vh,760px);background:#14161b;color:#fff;border-radius:14px;overflow:hidden;box-shadow:0 12px 50px rgba(0,0,0,.45);border:1px solid rgba(255,255,255,.08);display:flex;flex-direction:column}
.tw-modal .tw-modal-head{display:flex;align-items:center;justify-content:space-between;padding:12px 14px;border-bottom:1px solid rgba(255,255,255,.08);flex:0 0 auto}
.tw-modal .tw-search{width:100%;padding:10px 12px;border:0;outline:none;border-bottom:1px solid rgba(255,255,255,.08);background:#0f1115;color:#fff;flex:0 0 auto}
.tw-modal .tw-list{flex:1 1 auto;overflow-y:auto;overflow-x:hidden;scrollbar-gutter:stable;max-height:56vh}
.tw-modal .tw-list::-webkit-scrollbar{width:10px}
.tw-modal .tw-list::-webkit-scrollbar-track{background:#0e1116}
.tw-modal .tw-list::-webkit-scrollbar-thumb{background:#2b3744;border-radius:8px;border:2px solid #0e1116}
.tw-modal .tw-list::-webkit-scrollbar-thumb:hover{background:#394a5b}
.tw-modal .tw-item{display:block;width:100%;text-align:left;padding:12px 14px;background:transparent;border:0;cursor:pointer;border-bottom:1px solid rgba(255,255,255,.06);color:#e8f5ff}
.tw-modal .tw-item:hover{background:rgba(0,255,200,.08)}
</style>
<script>
(function(){
  function fitListHeight(){
    var m=document.querySelector('.tw-modal:not([hidden]) .tw-modal-content'); if(!m) return;
    var h=m.querySelector('.tw-modal-head'), s=m.querySelector('.tw-search'), l=m.querySelector('.tw-list'); if(!l) return;
    var maxH=Math.min(window.innerHeight*0.82,760), used=(h?h.offsetHeight:0)+(s?s.offsetHeight:0), avail=Math.max(140,maxH-used-6);
    l.style.maxHeight=avail+'px';
  }
  document.addEventListener('click',function(e){
    if(e.target && (e.target.classList.contains('tw-select-btn')||e.target.closest('.tw-modal'))){ setTimeout(fitListHeight,0); }
  });
  window.addEventListener('resize',fitListHeight);
  document.addEventListener('DOMContentLoaded',fitListHeight);
})();
</script>
<?php });
// Shortcode: [wc_customer_id] veya [wc_customer_id order_id="123"]
add_shortcode('wc_customer_id', function($atts){
    $atts = shortcode_atts([
        'order_id' => '',
        'user_id'  => '',
    ], $atts, 'wc_customer_id');

    // order_id öncelikli
    if (!empty($atts['order_id'])) {
        if (!function_exists('wc_get_order')) return '';
        $order = wc_get_order( absint($atts['order_id']) );
        if (!$order) return '';
        return (string) $order->get_customer_id();
    }

    // user_id verilmişse direkt onu döndür
    if (!empty($atts['user_id'])) {
        return (string) absint($atts['user_id']);
    }

    // aksi halde giriş yapan kullanıcının ID'si
    if (is_user_logged_in()) {
        return (string) get_current_user_id();
    }

    return ''; // giriş yoksa boş
});
/* ===========================
   Son notlar
   - Bu dosya, orijinal yapıyı bozmadan; çekim modalını geliştirip, kripto seçeneğini ekleyip
     ayrıca manuel kripto ödeme işlemine TXID alanı ekleyerek çalışmayı kolaylaştırır.
   - Eğer checkout sayfasında ödeme yöntemleri halen görünmüyorsa:
       * Tema veya başka bir eklenti 'woocommerce_checkout' bloklarını veya gatewayleri gizliyor olabilir.
       * Admin > WooCommerce > Settings > Payments kısmından "Banka Havalesi" ve "Kripto Transferi" yöntemlerini aktif edin.
   - Kurulum kontrolü:
       * functions.php'yi temanın köküne koyun ve temayı yeniden etkinleştirin (dbDelta satırı tabloyu oluşturur).
       * Admin > Kullanıcı > Düzenle üzerinden kullanıcı bakiyesini kontrol edin.
       * Test için bir kullanıcıya admin panelden uv_wallet_manager ile bakiye ekleyin ve "Cüzdanımdan öde" seçeneğini kullanarak checkout deneyin.
   ===========================
*/
/* ============ WALLET TOP-UP: AJAX ile sepete ekle ve checkout'a yönlendir ============ */
add_action('wp_ajax_uv_topup_add', 'uv_topup_add');
add_action('wp_ajax_nopriv_uv_topup_add', 'uv_topup_add'); // güvenlik: gerekmez ama ekli

function uv_topup_add() {
  // Nonce & login kontrol
  if (empty($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'uv_topup_nonce')) {
    wp_send_json_error(['msg' => 'Güvenlik doğrulaması başarısız.']);
  }
  if (!is_user_logged_in()) {
    wp_send_json_error(['msg' => 'Lütfen giriş yapın.']);
  }

  // Tutarı al ve doğrula
  $amount = isset($_POST['amount']) ? round((float)$_POST['amount'], 2) : 0;
  if ($amount <= 0) {
    wp_send_json_error(['msg' => 'Geçerli bir tutar girin.']);
  }

  // Ürünü garantile
  $pid = uv_ensure_topup_product();
  if (!$pid) {
    wp_send_json_error(['msg' => 'Top-up ürünü oluşturulamadı.']);
  }

  // Sepete tek kalem olarak ekle (adet=1, fiyatı amount olarak ayarla)
  if (function_exists('WC')) {
    if (WC()->cart) {
      // Aynı anda sadece top-up ödemesi almak için sepeti boşaltmak isteyebiliriz
      // istersen kaldır: WC()->cart->empty_cart();
      $data = [
        '_custom_price' => $amount,
        '_is_topup'     => 1,
      ];
      $added = WC()->cart->add_to_cart($pid, 1, 0, [], $data);
      if (!$added) {
        wp_send_json_error(['msg' => 'Sepete eklenemedi.']);
      }
      wp_send_json_success(['redirect' => wc_get_checkout_url()]);
    }
  }
  wp_send_json_error(['msg' => 'Bilinmeyen hata.']);
}
