<?php

/**
 * Plugin Name: CloudXM NFe
 * Plugin URI: https://cloudxm.com.br/plugins/woocommerce-cloudxm-nfe
 * Description: Professional CloudXM NFe integration for WooCommerce - Automated electronic invoice generation and management with cloudxm-nfe-server API.
 * Version: 2.14.3
 * Author: CloudXM
 * Author URI: https://cloudxm.com.br
 * License: Proprietary - All rights reserved to CloudXM
 * License URI: https://cloudxm.com.br/license
 * Text Domain: woocommerce-cloudxm-nfe
 * Domain Path: /languages
 * Requires at least: 6.4
 * Tested up to: 6.7
 * Requires PHP: 8.1
 * WC requires at least: 8.0
 * WC tested up to: 9.0
 * Network: false
 */
if (! defined('ABSPATH')) {
    exit;
}

// Declare compatibility with WooCommerce High-Performance order storage
add_action('before_woocommerce_init', function () {
    if (class_exists(\Automattic\WooCommerce\Utilities\FeaturesUtil::class)) {
        \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility('custom_order_tables', __FILE__, true);
    }
});

// Define plugin constants
define('CLOUDXM_NFE_VERSION', '2.10.2');
define('CLOUDXM_NFE_PATH', plugin_dir_path(__FILE__));
define('CLOUDXM_NFE_URL', plugin_dir_url(__FILE__));
define('CLOUDXM_NFE_BASENAME', plugin_basename(__FILE__));

// Load Composer autoloader (includes cloudxm-sdk and other dependencies)
$composer_autoload = CLOUDXM_NFE_PATH.'vendor/autoload.php';
if (file_exists($composer_autoload)) {
    require_once $composer_autoload;
}

// Load plugin autoloader for CloudXM\NFe namespace
require_once CLOUDXM_NFE_PATH.'src/Autoload.php';

/**
 * Ensure database schema is created on plugin activation.
 */
function cloudxm_nfe_activate(): void
{
    try {
        // Initialize plugin and force migration check/run.
        \CloudXM\NFe\Bootstrap\Plugin::getInstance()->boot();

        if (class_exists(\CloudXM\SDK\Persistence\MigrationRunner::class)) {
            $config = new \CloudXM\NFe\Config\Configuration;
            $runner = new \CloudXM\SDK\Persistence\MigrationRunner($config);
            $result = $runner->runMigrations();
            error_log('CloudXM NFe activation migrations: '.wp_json_encode($result));
        }
    } catch (\Throwable $e) {
        error_log('CloudXM NFe activation failed: '.$e->getMessage());
    }
}
register_activation_hook(__FILE__, 'cloudxm_nfe_activate');

// Load plugin text domain
add_action('plugins_loaded', function () {
    load_plugin_textdomain(
        'woocommerce-cloudxm-nfe',
        false,
        dirname(CLOUDXM_NFE_BASENAME).'/languages'
    );
});

// Initialize the plugin using the container architecture
\CloudXM\NFe\Bootstrap\Plugin::getInstance()->boot();
