<?php
/**
 * Licensing Module Bootstrap
 *
 * @package WooNooW\Modules\Licensing
 */

namespace WooNooW\Modules\Licensing;

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

use WooNooW\Core\ModuleRegistry;
use WooNooW\Modules\LicensingSettings;

class LicensingModule {
    
    /**
     * Initialize the licensing module
     */
    public static function init() {
        // Register settings schema
        LicensingSettings::init();
        
        // Initialize license manager immediately since we're already in plugins_loaded
        // Note: This is called from woonoow.php inside plugins_loaded action,
        // so we can call maybe_init_manager directly instead of scheduling another hook
        self::maybe_init_manager();
        
        // Install tables on module enable
        add_action('woonoow/module/enabled', [__CLASS__, 'on_module_enabled']);
        
        // Add product meta fields
        add_action('woocommerce_product_options_general_product_data', [__CLASS__, 'add_product_licensing_fields']);
        add_action('woocommerce_process_product_meta', [__CLASS__, 'save_product_licensing_fields']);
    }
    
    /**
     * Initialize manager if module is enabled
     */
    public static function maybe_init_manager() {
        if (ModuleRegistry::is_enabled('licensing')) {
            // Ensure tables exist
            self::ensure_tables();
            LicenseManager::init();
        }
    }
    
    /**
     * Ensure database tables exist
     */
    private static function ensure_tables() {
        global $wpdb;
        $table = $wpdb->prefix . 'woonoow_licenses';
        
        // Check if table exists
        if ($wpdb->get_var("SHOW TABLES LIKE '$table'") !== $table) {
            LicenseManager::create_tables();
        }
    }
    
    /**
     * Handle module enable
     */
    public static function on_module_enabled($module_id) {
        if ($module_id === 'licensing') {
            LicenseManager::create_tables();
        }
    }
    
    /**
     * Add licensing fields to product edit page
     */
    public static function add_product_licensing_fields() {
        global $post;
        
        if (!ModuleRegistry::is_enabled('licensing')) {
            return;
        }
        
        echo '<div class="options_group show_if_simple show_if_downloadable">';
        
        woocommerce_wp_checkbox([
            'id' => '_woonoow_licensing_enabled',
            'label' => __('Enable Licensing', 'woonoow'),
            'description' => __('Generate license keys for this product on purchase', 'woonoow'),
        ]);
        
        woocommerce_wp_text_input([
            'id' => '_woonoow_license_activation_limit',
            'label' => __('Activation Limit', 'woonoow'),
            'description' => __('Max activations per license (0 = use default, leave empty for unlimited)', 'woonoow'),
            'type' => 'number',
            'custom_attributes' => [
                'min' => '0',
                'step' => '1',
            ],
        ]);
        
        woocommerce_wp_text_input([
            'id' => '_woonoow_license_expiry_days',
            'label' => __('License Expiry (Days)', 'woonoow'),
            'description' => __('Days until license expires (0 = never expires)', 'woonoow'),
            'type' => 'number',
            'custom_attributes' => [
                'min' => '0',
                'step' => '1',
            ],
        ]);
        
        echo '</div>';
    }
    
    /**
     * Save licensing fields
     */
    public static function save_product_licensing_fields($post_id) {
        $licensing_enabled = isset($_POST['_woonoow_licensing_enabled']) ? 'yes' : 'no';
        update_post_meta($post_id, '_woonoow_licensing_enabled', $licensing_enabled);
        
        if (isset($_POST['_woonoow_license_activation_limit'])) {
            update_post_meta($post_id, '_woonoow_license_activation_limit', absint($_POST['_woonoow_license_activation_limit']));
        }
        
        if (isset($_POST['_woonoow_license_expiry_days'])) {
            update_post_meta($post_id, '_woonoow_license_expiry_days', absint($_POST['_woonoow_license_expiry_days']));
        }
    }
}
