<?php

/**
 * Plugin Name: CDP Fast Crypto Gateway
 * Plugin URI: https://berdl.com
 * Description: CDP Fast Crypto Gateway with wallet selector + QR
 * Version: 1.0.0
 * Author: Berdl team
 * Text Domain: spg-crypto-manual
 * License: GPLv2 
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 */

if (!defined('ABSPATH'))
  exit;

if (!defined('SPG_VERSION'))
  define('SPG_VERSION', '1.0.0');
if (!defined('SPG_PATH'))
  define('SPG_PATH', plugin_dir_path(__FILE__));
if (!defined('SPG_URL'))
  define('SPG_URL', plugin_dir_url(__FILE__));

/**
 * Ensure "minute" cron schedule exists globally.
 * (Important: activation hook may run before poller classes add this schedule.)
 */
add_filter('cron_schedules', function ($schedules) {
  if (!isset($schedules['minute'])) {
    $schedules['minute'] = ['interval' => 60, 'display' => 'Every Minute'];
  }
  return $schedules;
});

function spg_safe_require($relative_path)
{
  $file = SPG_PATH . ltrim($relative_path, '/');
  if (file_exists($file)) {
    require_once $file;
    return true;
  }
  return false;
}

function spg_admin_notice($type, $message)
{
  add_action('admin_notices', function () use ($type, $message) {
    if (!current_user_can('activate_plugins'))
      return;
    printf(
      '<div class="notice notice-%1$s"><p>%2$s</p></div>',
      esc_attr($type),
      wp_kses_post($message)
    );
  });
}

// add_action('init', function () {
//   load_plugin_textdomain('spg-crypto-manual', false, dirname(plugin_basename(__FILE__)) . '/languages');
// });

add_action('plugins_loaded', function () {

  // Woo required
  if (!class_exists('WooCommerce')) {
    spg_admin_notice('error', '<strong>CryptoDir Payments</strong> requires <strong>WooCommerce</strong> to be installed and active.');
    return;
  }

  /**
   * ✅ THANK YOU PAGE: hide header/menu ONLY for orders paid via our gateway
   */
  add_filter('body_class', function ($classes) {
    if (!function_exists('is_order_received_page') || !is_order_received_page()) {
      return $classes;
    }

    if (!function_exists('wc_get_order'))
      return $classes;

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

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

    if ($order->get_payment_method() === 'spg_crypto_manual') {
      $classes[] = 'spg-ty-hide-header';
    }

    return $classes;
  }, 20);
  // ✅ THANK YOU PAGE: replace default "order received" notice ONLY for our gateway
  add_filter('woocommerce_thankyou_order_received_text', function ($text, $order) {

    if (!($order instanceof WC_Order)) {
      return $text;
    }

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

    $msg = __('Make your transfer using the details below. After it’s sent, your order will be completed AUTOMATICALLY once the payment is confirmed.', 'spg-crypto-manual');

    $icon = '<span class="spg-ty-info-icon" aria-hidden="true">i</span>';

    return '<span class="spg-ty-order-received">'
      . $icon
      . '<span class="spg-ty-order-received-text">' . wp_kses_post($msg) . '</span>'
      . '</span>';

  }, 20, 2);

  add_action('wp_enqueue_scripts', function () {
    if (!function_exists('is_order_received_page') || !is_order_received_page()) {
      return;
    }
    if (!function_exists('wc_get_order'))
      return;

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

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

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

    // Add inline CSS for common theme headers
    $css = "
/* CDP: hide header/menu only on thank you page for our gateway */
body.spg-ty-hide-header header,
body.spg-ty-hide-header #masthead,
body.spg-ty-hide-header .site-header,
body.spg-ty-hide-header .header,
body.spg-ty-hide-header .main-header,
body.spg-ty-hide-header .elementor-location-header,
body.spg-ty-hide-header .et-l--header,
body.spg-ty-hide-header .fusion-header-wrapper,
body.spg-ty-hide-header .wp-block-template-part.header {
  display: none !important;
}

/* Optional: remove spacing caused by fixed headers in some themes */
body.spg-ty-hide-header {
  padding-top: 0 !important;
  margin-top: 0 !important;
}
";

    wp_register_style('spg-ty-inline', false, [], SPG_VERSION);
    wp_enqueue_style('spg-ty-inline');
    wp_add_inline_style('spg-ty-inline', $css);
  }, 20);

  // Core includes
  spg_safe_require('includes/class-spg-api.php');
  spg_safe_require('includes/class-spg-qr.php');

  if (!class_exists('SPG_QR')) {
    spg_admin_notice('warning', '<strong>CryptoDir Payments</strong>: QR class not loaded (<code>includes/class-spg-qr.php</code>).');
  }
  add_action('wp_head', function () {
    if (!function_exists('is_order_received_page') || !is_order_received_page())
      return;
    if (!function_exists('wc_get_order'))
      return;

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

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

    // Only for your gateway
    if ($order->get_payment_method() !== 'spg_crypto_manual')
      return;
    ?>
    <style>
      /* JivoChat uses <jdiv> custom nodes */
      jdiv {
        display: none !important;
      }
    </style>
    <?php
  }, 99);
  /**
   * ✅ GLOBAL cancel handler (must NOT be inside gateway class)
   * Cron/Action Scheduler runs later without instantiating the gateway.
   */
  add_action('spg_timer_cancel_unpaid_order', function ($order_id) {
    if (!function_exists('wc_get_order'))
      return;

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

    if ($order->is_paid())
      return;

    $st = $order->get_status();
    if (!in_array($st, ['pending', 'on-hold'], true))
      return;

    $expires_at = (int) $order->get_meta('_spg_timer_expires_at');
    if ($expires_at > 0 && time() < $expires_at)
      return;

    $order->update_status('cancelled', __('Payment timer expired - order automatically cancelled.', 'spg-crypto-manual'));
  }, 10, 1);

  // Helpers
  $ok_helpers = spg_safe_require('includes/helpers.php');
  if (!$ok_helpers) {
    spg_admin_notice('warning', '<strong>CryptoDir Payments</strong>: missing file <code>includes/helpers.php</code>.');
  }

  // Wallets admin
  $ok_admin = spg_safe_require('includes/class-spg-wallets-admin.php');
  if (!$ok_admin) {
    spg_admin_notice('warning', '<strong>CryptoDir Payments</strong>: missing file <code>includes/class-spg-wallets-admin.php</code>.');
  } else {
    if (class_exists('SPG_Wallets_Admin') && method_exists('SPG_Wallets_Admin', 'init')) {
      SPG_Wallets_Admin::init();
    }
  }

  // Order admin UI block
  $ok_order_admin = spg_safe_require('includes/class-spg-order-admin.php');
  if (!$ok_order_admin) {
    spg_admin_notice('warning', '<strong>CryptoDir Payments</strong>: missing file <code>includes/class-spg-order-admin.php</code>.');
  }

  // TRON poller
  $ok_tron = spg_safe_require('includes/class-spg-tron-poller.php');
  if (!$ok_tron) {
    spg_admin_notice('warning', '<strong>CryptoDir Payments</strong>: missing file <code>includes/class-spg-tron-poller.php</code>. Auto-tracking disabled.');
  } else {
    if (class_exists('SPG_Tron_Poller') && method_exists('SPG_Tron_Poller', 'init')) {
      SPG_Tron_Poller::init();
      if (method_exists('SPG_Tron_Poller', 'ensure_recurring_poll')) {
        SPG_Tron_Poller::ensure_recurring_poll();
      }
    }
  }

  // SOL poller
  $ok_sol = spg_safe_require('includes/class-spg-sol-poller.php');
  if (!$ok_sol) {
    spg_admin_notice('warning', '<strong>CryptoDir Payments</strong>: missing file <code>includes/class-spg-sol-poller.php</code>. SOL auto-tracking disabled.');
  } else {
    if (class_exists('SPG_SOL_Poller') && method_exists('SPG_SOL_Poller', 'init')) {
      SPG_SOL_Poller::init();
      if (method_exists('SPG_SOL_Poller', 'ensure_recurring_poll')) {
        SPG_SOL_Poller::ensure_recurring_poll();
      }
    }
  }

  // EVM poller
  $ok_evm = spg_safe_require('includes/class-spg-evm-poller.php');
  if (!$ok_evm) {
    spg_admin_notice('warning', '<strong>CryptoDir Payments</strong>: missing file <code>includes/class-spg-evm-poller.php</code>. EVM auto-tracking disabled.');
  } else {
    if (class_exists('SPG_EVM_Poller') && method_exists('SPG_EVM_Poller', 'init')) {
      SPG_EVM_Poller::init();
      if (method_exists('SPG_EVM_Poller', 'ensure_recurring_poll')) {
        SPG_EVM_Poller::ensure_recurring_poll();
      }
    }
  }

  // Rates + UTXO poller
  $ok_rates = spg_safe_require('includes/class-spg-rates.php');
  if (!$ok_rates) {
    spg_admin_notice('warning', '<strong>CryptoDir Payments</strong>: missing file <code>includes/class-spg-rates.php</code>. BTC-family auto-tracking disabled.');
  }

  $ok_utxo = spg_safe_require('includes/class-spg-utxo-poller.php');
  if (!$ok_utxo) {
    spg_admin_notice('warning', '<strong>CryptoDir Payments</strong>: missing file <code>includes/class-spg-utxo-poller.php</code>. BTC-family auto-tracking disabled.');
  } else {
    if (class_exists('SPG_UTXO_Poller') && method_exists('SPG_UTXO_Poller', 'init')) {
      SPG_UTXO_Poller::init();
      if (method_exists('SPG_UTXO_Poller', 'ensure_recurring_poll')) {
        SPG_UTXO_Poller::ensure_recurring_poll();
      }
    }
  }

  // Gateway
  $ok_gateway = spg_safe_require('includes/class-spg-gateway.php');
  if (!$ok_gateway) {
    spg_admin_notice('error', '<strong>CryptoDir Payments</strong>: missing file <code>includes/class-spg-gateway.php</code>.');
    return;
  }

  add_filter('woocommerce_payment_gateways', function ($methods) {
    if (class_exists('WC_Gateway_SPG_Crypto')) {
      $methods[] = 'WC_Gateway_SPG_Crypto';
    }
    return $methods;
  });
}, 20);

register_activation_hook(__FILE__, function () {

  // WP-Cron fallback schedules (only if Action Scheduler not available)
  if (!function_exists('as_next_scheduled_action')) {

    if (!wp_next_scheduled('spg_tron_cron_poll')) {
      wp_schedule_event(time() + 60, 'minute', 'spg_tron_cron_poll');
    }

    if (!wp_next_scheduled('spg_sol_cron_poll')) {
      wp_schedule_event(time() + 60, 'minute', 'spg_sol_cron_poll');
    }

    if (!wp_next_scheduled('spg_evm_cron_poll')) {
      wp_schedule_event(time() + 60, 'minute', 'spg_evm_cron_poll');
    }

    if (!wp_next_scheduled('spg_utxo_cron_poll')) {
      wp_schedule_event(time() + 60, 'minute', 'spg_utxo_cron_poll');
    }
  }
});

register_deactivation_hook(__FILE__, function () {

  if (wp_next_scheduled('spg_tron_cron_poll')) {
    wp_clear_scheduled_hook('spg_tron_cron_poll');
  }

  if (wp_next_scheduled('spg_sol_cron_poll')) {
    wp_clear_scheduled_hook('spg_sol_cron_poll');
  }

  if (wp_next_scheduled('spg_evm_cron_poll')) {
    wp_clear_scheduled_hook('spg_evm_cron_poll');
  }

  if (wp_next_scheduled('spg_utxo_cron_poll')) {
    wp_clear_scheduled_hook('spg_utxo_cron_poll');
  }
});

add_action('admin_enqueue_scripts', function ($hook) {
  // Only WooCommerce settings page
  if ($hook !== 'woocommerce_page_wc-settings') {
    return;
  }

  // ✅ Avoid $_GET entirely (Plugin Check friendly)
  if (!class_exists('WC_Admin_Settings')) {
    return;
  }

  // WC_Admin_Settings::$tab / $section are derived from request and already normalized by WC
  $tab = isset(WC_Admin_Settings::$tab) ? (string) WC_Admin_Settings::$tab : '';
  $section = isset(WC_Admin_Settings::$section) ? (string) WC_Admin_Settings::$section : '';

  if ($tab !== 'checkout') {
    return;
  }

  if ($section !== 'spg_crypto_manual') {
    return;
  }

  // Enqueue your admin assets here
  // wp_enqueue_style('cdp-admin', SPG_URL . 'assets/css/admin.css', [], SPG_VERSION);
  // wp_enqueue_script('cdp-admin', SPG_URL . 'assets/js/admin.js', ['jquery'], SPG_VERSION, true);
}, 20);