<?php
namespace PayCal\Modules\Bit;

defined('ABSPATH') || exit;

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

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

    $loaded = true;
    $loaded = self::safe_require('includes/Modules/Bit/BitSettings.php', 'Bit settings') && $loaded;
    $loaded = self::safe_require('includes/Modules/Bit/BitOrderStatus.php', 'Bit order status') && $loaded;
    $loaded = self::safe_require('includes/Modules/Bit/BitCheckoutUI.php', 'Bit checkout UI') && $loaded;
    $loaded = self::safe_require('includes/Modules/Bit/BitAdminActions.php', 'Bit admin actions') && $loaded;
    $loaded = self::safe_require('includes/Modules/Bit/BitThankYouText.php', 'Bit thank-you text') && $loaded;

    if (!$loaded || !class_exists(BitOrderStatus::class) || !class_exists(BitCheckoutUI::class) || !class_exists(BitAdminActions::class) || !class_exists(BitThankYouText::class)) {
      self::notice('PayCal Bit module could not load all required files. The rest of the site continues to run.');
      return;
    }

    self::safe_init(BitOrderStatus::class, 'Bit order status');
    self::safe_init(BitCheckoutUI::class, 'Bit checkout UI');
    self::safe_init(BitAdminActions::class, 'Bit admin actions');
    self::safe_init(BitThankYouText::class, 'Bit thank-you text');

    // Load the existing Bit gateway (internal module)
    if (self::safe_require('includes/Modules/Bit/BitGatewayLoader.php', 'Bit gateway loader') && class_exists(BitGatewayLoader::class)) {
      self::safe_init(BitGatewayLoader::class, 'Bit gateway loader');
    }
  }

  private static function safe_require(string $relative_path, string $label): bool {
    if (class_exists(Plugin::class)) {
      return Plugin::safe_require($relative_path, $label);
    }

    $file = PAYCAL_PATH . ltrim($relative_path, '/');
    if (!file_exists($file)) {
      \paycal_debug_log('[PayCal] Missing file: ' . $relative_path);
      return false;
    }

    try {
      require_once $file;
      return true;
    } catch (\Throwable $e) {
      \paycal_debug_log('[PayCal] Failed loading ' . $relative_path . ': ' . $e->getMessage());
      return false;
    }
  }

  private static function safe_init(string $class, string $label): void {
    try {
      $class::init();
    } catch (\Throwable $e) {
      self::notice('PayCal ' . $label . ' failed to initialize safely.');
      \paycal_debug_log('[PayCal] ' . $label . ' init failed: ' . $e->getMessage());
    }
  }

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