<?php
/**
 * Plugin Name:       Variation Hub
 * Plugin URI:        https://bytebays.com/variation-hub
 * Description:       Professional WooCommerce variation management with Excel-like spreadsheet interface for bulk editing
 * Version:           1.0.0
 * Requires at least: 6.0
 * Requires PHP:      8.1
 * Author:            Bakonyi Péter
 * Author URI:        https://bytebays.com
 * License:           GPL v3 or later
 * License URI:       https://www.gnu.org/licenses/gpl-3.0.html
 * Text Domain:       variation-hub
 * Domain Path:       /languages
 * Requires Plugins:  woocommerce
 *
 * WC requires at least: 6.0
 * WC tested up to:      10.3.5
 *
 * @package VariationHub
 */

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

// Declare HPOS compatibility
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
        );
    }
});

defined('ABSPATH') || exit; // Exit if accessed directly

// Plugin constants
define('VARIHU_VERSION', '1.0.0');
define('VARIHU_PLUGIN_FILE', __FILE__);
define('VARIHU_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('VARIHU_PLUGIN_URL', plugin_dir_url(__FILE__));
define('VARIHU_PLUGIN_BASENAME', plugin_basename(__FILE__));

// Composer autoload
if (file_exists(VARIHU_PLUGIN_DIR . 'vendor/autoload.php')) {
    require_once VARIHU_PLUGIN_DIR . 'vendor/autoload.php';
}

// Manual class loading (if no composer)
require_once VARIHU_PLUGIN_DIR . 'includes/class-activator.php';
require_once VARIHU_PLUGIN_DIR . 'includes/class-deactivator.php';
require_once VARIHU_PLUGIN_DIR . 'includes/class-migration.php';
require_once VARIHU_PLUGIN_DIR . 'includes/admin/class-admin.php';
require_once VARIHU_PLUGIN_DIR . 'includes/core/class-cache-table.php';
require_once VARIHU_PLUGIN_DIR . 'includes/core/class-cache-sync.php';
require_once VARIHU_PLUGIN_DIR . 'includes/core/class-cache-hooks.php';
require_once VARIHU_PLUGIN_DIR . 'includes/core/class-license-manager.php';
require_once VARIHU_PLUGIN_DIR . 'includes/api/class-cache-controller.php';
require_once VARIHU_PLUGIN_DIR . 'includes/api/class-license-controller.php';

/**
 * Plugin activation hook
 */
function variation_hub_activate() {
    \VariationHub\Activator::activate();
}
register_activation_hook(__FILE__, 'variation_hub_activate');

/**
 * Plugin deactivation hook
 */
function variation_hub_deactivate() {
    \VariationHub\Deactivator::deactivate();
}
register_deactivation_hook(__FILE__, 'variation_hub_deactivate');

/**
 * Initialize the plugin
 */
function variation_hub_init() {
    // Run database migrations (if needed)
    \VariationHub\Migration::run();
    
    // Check dependencies
    if (!class_exists('WooCommerce')) {
        add_action('admin_notices', function() {
            ?>
            <div class="notice notice-error">
                <p>
                    <?php 
                    echo wp_kses_post(
                        __('<strong>Variation Hub</strong> requires <strong>WooCommerce</strong> to be installed and activated.', 'variation-hub')
                    ); 
                    ?>
                </p>
            </div>
            <?php
        });
        return;
    }
    
    // Check minimum WooCommerce version
    if (version_compare(WC_VERSION, '6.0', '<')) {
        add_action('admin_notices', function() {
            ?>
            <div class="notice notice-error">
                <p>
                    <?php 
                    echo wp_kses_post(
                        sprintf(
                            /* translators: %s: installed WooCommerce version */
                            __('<strong>Variation Hub</strong> requires WooCommerce 6.0 or higher. Current version: %s', 'variation-hub'),
                            WC_VERSION
                        )
                    ); 
                    ?>
                </p>
            </div>
            <?php
        });
        return;
    }
    
    // Initialize admin interface
    if (is_admin()) {
        \VariationHub\Admin\Admin::get_instance();
    }

    // Initialize cache sync hooks
    \VariationHub\Core\Cache_Hooks::init();
    
    // Manual require for controllers (composer classmap workaround)
    require_once VARIHU_PLUGIN_DIR . 'includes/api/class-export-import-controller.php';
    require_once VARIHU_PLUGIN_DIR . 'includes/api/class-fast-variations-controller.php';
    
    // Register REST API routes
    add_action('rest_api_init', function() {
        $variations_controller = new \VariationHub\API\Variations_Controller();
        $variations_controller->register_routes();
        
        $bulk_controller = new \VariationHub\API\Bulk_Operations_Controller();
        $bulk_controller->register_routes();
        
        $attributes_controller = new \VariationHub\API\Attributes_Controller();
        $attributes_controller->register_routes();
        
        $export_import_controller = new \VariationHub\API\Export_Import_Controller();
        $export_import_controller->register_routes();
        
        $fast_controller = new \VariationHub\API\Fast_Variations_Controller();
        $fast_controller->register_routes();
        
        $cache_controller = new \VariationHub\API\Cache_Controller();
        $cache_controller->register_routes();
        
        // ✨ License management (Phase 4 - MVP: returns 'free' tier)
        $license_controller = new \VariationHub\API\License_Controller();
        $license_controller->register_routes();
    });
}
add_action('plugins_loaded', 'variation_hub_init');

/**
 * Add plugin action links
 */
function variation_hub_plugin_action_links($links) {
    $settings_link = sprintf(
        '<a href="%s">%s</a>',
        admin_url('admin.php?page=variation-hub'),
        __('Settings', 'variation-hub')
    );
    
    array_unshift($links, $settings_link);
    
    return $links;
}
add_filter('plugin_action_links_' . VARIHU_PLUGIN_BASENAME, 'variation_hub_plugin_action_links');

/**
 * AJAX endpoint for nonce refresh
 */
add_action('wp_ajax_varihu_refresh_nonce', function() {
    if (!is_user_logged_in()) {
        wp_send_json_error(['message' => 'User not authenticated'], 401);
        return;
    }
    
    $new_nonce = wp_create_nonce('wp_rest');
    
    wp_send_json_success([
        'nonce' => $new_nonce,
        'timestamp' => current_time('timestamp'),
        'message' => 'Nonce refreshed successfully'
    ]);
});
