<?php

/**
 * Software Distribution Module Bootstrap
 *
 * @package WooNooW\Modules\Software
 */

namespace WooNooW\Modules\Software;

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

use WooNooW\Core\ModuleRegistry;
use WooNooW\Modules\SoftwareSettings;

class SoftwareModule
{
    /**
     * Initialize the software distribution module
     */
    public static function init()
    {
        // Register settings schema
        SoftwareSettings::init();

        // Initialize manager if module is enabled
        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_software_fields']);
        add_action('woocommerce_process_product_meta', [__CLASS__, 'save_product_software_fields']);
    }

    /**
     * Initialize manager if module is enabled
     */
    public static function maybe_init_manager()
    {
        if (ModuleRegistry::is_enabled('software')) {
            self::ensure_tables();
            SoftwareManager::init();
        }
    }

    /**
     * Ensure database tables exist
     */
    private static function ensure_tables()
    {
        global $wpdb;
        $table = $wpdb->prefix . 'woonoow_software_versions';

        if ($wpdb->get_var("SHOW TABLES LIKE '$table'") !== $table) {
            SoftwareManager::create_tables();
        }
    }

    /**
     * Handle module enable
     */
    public static function on_module_enabled($module_id)
    {
        if ($module_id === 'software') {
            SoftwareManager::create_tables();
        }
    }

    /**
     * Add software distribution fields to product edit page
     */
    public static function add_product_software_fields()
    {
        global $post;

        if (!ModuleRegistry::is_enabled('software')) {
            return;
        }

        // Check if licensing is enabled for this product
        $licensing_enabled = get_post_meta($post->ID, '_woonoow_licensing_enabled', true) === 'yes';

        echo '<div class="options_group show_if_downloadable">';

        // Software Distribution section header
        echo '<p class="form-field"><strong>' . esc_html__('Software Distribution', 'woonoow') . '</strong></p>';

        woocommerce_wp_checkbox([
            'id' => '_woonoow_software_enabled',
            'label' => __('Enable Software Updates', 'woonoow'),
            'description' => __('Allow customers to check for updates via API', 'woonoow'),
        ]);

        woocommerce_wp_text_input([
            'id' => '_woonoow_software_slug',
            'label' => __('Software Slug', 'woonoow'),
            'description' => __('Unique identifier (e.g., "my-plugin"). Used in update check API.', 'woonoow'),
            'desc_tip' => true,
            'placeholder' => 'my-software',
        ]);

        woocommerce_wp_text_input([
            'id' => '_woonoow_software_current_version',
            'label' => __('Current Version', 'woonoow'),
            'description' => __('Latest version number (e.g., "1.2.3")', 'woonoow'),
            'desc_tip' => true,
            'placeholder' => '1.0.0',
        ]);

        // WordPress Integration section
        echo '<p class="form-field"><em>' . esc_html__('WordPress Integration (Optional)', 'woonoow') . '</em></p>';

        woocommerce_wp_checkbox([
            'id' => '_woonoow_software_wp_enabled',
            'label' => __('WordPress Plugin/Theme', 'woonoow'),
            'description' => __('Enable WordPress-specific update fields', 'woonoow'),
        ]);

        // WordPress-specific fields (shown via JS when checkbox is checked)
        echo '<div class="woonoow-wp-fields" style="' . (get_post_meta($post->ID, '_woonoow_software_wp_enabled', true) === 'yes' ? '' : 'display:none;') . '">';

        woocommerce_wp_text_input([
            'id' => '_woonoow_software_requires_wp',
            'label' => __('Requires WP', 'woonoow'),
            'placeholder' => '6.0',
        ]);

        woocommerce_wp_text_input([
            'id' => '_woonoow_software_tested_wp',
            'label' => __('Tested WP', 'woonoow'),
            'placeholder' => '6.7',
        ]);

        woocommerce_wp_text_input([
            'id' => '_woonoow_software_requires_php',
            'label' => __('Requires PHP', 'woonoow'),
            'placeholder' => '7.4',
        ]);

        echo '</div>'; // .woonoow-wp-fields

        // Inline JS to toggle WP fields
?>
        <script>
            jQuery(function($) {
                $('#_woonoow_software_wp_enabled').on('change', function() {
                    if ($(this).is(':checked')) {
                        $('.woonoow-wp-fields').slideDown();
                    } else {
                        $('.woonoow-wp-fields').slideUp();
                    }
                });
            });
        </script>
<?php

        echo '</div>'; // .options_group
    }

    /**
     * Save software distribution fields
     */
    public static function save_product_software_fields($post_id)
    {
        // Software enabled
        $software_enabled = isset($_POST['_woonoow_software_enabled']) ? 'yes' : 'no';
        update_post_meta($post_id, '_woonoow_software_enabled', $software_enabled);

        // Software slug
        if (isset($_POST['_woonoow_software_slug'])) {
            $slug = sanitize_title($_POST['_woonoow_software_slug']);
            update_post_meta($post_id, '_woonoow_software_slug', $slug);
        }

        // Current version
        if (isset($_POST['_woonoow_software_current_version'])) {
            $version = sanitize_text_field($_POST['_woonoow_software_current_version']);
            update_post_meta($post_id, '_woonoow_software_current_version', $version);
        }

        // WordPress integration
        $wp_enabled = isset($_POST['_woonoow_software_wp_enabled']) ? 'yes' : 'no';
        update_post_meta($post_id, '_woonoow_software_wp_enabled', $wp_enabled);

        // WordPress-specific fields
        $wp_fields = [
            '_woonoow_software_requires_wp',
            '_woonoow_software_tested_wp',
            '_woonoow_software_requires_php',
        ];

        foreach ($wp_fields as $field) {
            if (isset($_POST[$field])) {
                update_post_meta($post_id, $field, sanitize_text_field($_POST[$field]));
            }
        }
    }
}
