<?php
namespace PayCal\Modules\Bit;

defined('ABSPATH') || exit;

use PayCal\Core\Plugin;
use PayCal\Licensing\Gate;

/**
 * Loads the existing ASP Bit gateway only when the Bit entitlement is active.
 * Drop this file under: includes/Modules/Bit/BitGatewayLoader.php in PayCal Core,
 * and drop the Gateway folder under: includes/Modules/Bit/Gateway/
 */
class BitGatewayLoader {

  public static function init(): void {
    if (!class_exists('\WooCommerce')) return;
    if (!class_exists(Gate::class) || !Gate::has('bit')) return;

    // Load gateway class
    $gateway_file = PAYCAL_PATH . 'includes/Modules/Bit/Gateway/class-wc-gateway-asp-bit.php';
    if (!file_exists($gateway_file)) {
      self::notice('PayCal Bit gateway file is missing. Checkout will continue without the Bit gateway.');
      \paycal_debug_log('[PayCal] Missing Bit gateway file: ' . $gateway_file);
      return;
    }

    try {
      require_once $gateway_file;
    } catch (\Throwable $e) {
      self::notice('PayCal Bit gateway failed to load safely.');
      \paycal_debug_log('[PayCal] Bit gateway load failed: ' . $e->getMessage());
      return;
    }

    // Register gateway
    add_filter('woocommerce_payment_gateways', function($methods){
      if (class_exists('WC_Gateway_ASP_Bit')) {
        $methods[] = 'WC_Gateway_ASP_Bit';
      }
      return $methods;
    });

    // Load legacy gateway assets (if needed)
    add_action('wp_enqueue_scripts', function(){
      wp_enqueue_style(
        'asp-bit-style',
        PAYCAL_URL . 'includes/Modules/Bit/Gateway/assets/css/style.css',
        [],
        PAYCAL_VERSION
      );

      wp_enqueue_script(
        'asp-bit-js',
        PAYCAL_URL . 'includes/Modules/Bit/Gateway/assets/js/asp.js',
        ['jquery'],
        PAYCAL_VERSION,
        true
      );
    });
  }

  private static function notice(string $message): void {
    if (class_exists(Plugin::class)) {
      Plugin::register_admin_notice($message);
    }
  }
}
