<?php

/**
 * Affiliate Module Bootstrap
 *
 * @package WooNooW\Modules\Affiliate
 */

namespace WooNooW\Modules\Affiliate;

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

use WooNooW\Core\ModuleRegistry;

class AffiliateModule
{
    /**
     * Initialize the affiliate module
     */
    public static function init()
    {
        self::maybe_init_manager();

        // Install tables on module enable
        add_action('woonoow/module/enabled', [__CLASS__, 'on_module_enabled']);

        // Run migrations on admin init
        add_action('admin_init', [__CLASS__, 'run_migrations']);
    }

    /**
     * Initialize manager if module is enabled
     */
    public static function maybe_init_manager()
    {
        if (ModuleRegistry::is_enabled('affiliate')) {
            self::ensure_tables();
            AffiliateManager::init();
            AffiliateTracker::init();
            AffiliateLifecycle::init();
            AffiliateSettings::init();
        }
    }

    /**
     * Ensure database tables exist and have all required columns
     */
    private static function ensure_tables()
    {
        global $wpdb;
        $table = $wpdb->prefix . 'woonoow_affiliates';

        // Check if table exists
        if ($wpdb->get_var("SHOW TABLES LIKE '$table'") !== $table) {
            AffiliateManager::create_tables();
        } else {
            // Run migrations for existing tables
            self::migrate_existing_tables();
        }
    }

    /**
     * Migrate existing tables to add missing columns
     */
    private static function migrate_existing_tables()
    {
        global $wpdb;
        $table = $wpdb->prefix . 'woonoow_affiliates';
        $referrals_table = $wpdb->prefix . 'woonoow_referrals';

        // Add custom_commission_rate column if missing
        if ($wpdb->get_var("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '$table' AND COLUMN_NAME = 'custom_commission_rate'") == 0) {
            $wpdb->query("ALTER TABLE $table ADD COLUMN custom_commission_rate decimal(10,2) DEFAULT NULL AFTER commission_rate");
        }

        // Add payment detail columns if missing
        $payment_columns = ['payment_bank_name', 'payment_bank_account', 'payment_email'];
        foreach ($payment_columns as $col) {
            if ($wpdb->get_var("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '$table' AND COLUMN_NAME = '$col'") == 0) {
                $wpdb->query("ALTER TABLE $table ADD COLUMN $col varchar(100) DEFAULT NULL AFTER paid_earnings");
            }
        }

        // Add flexible payment_details and payment_method columns
        if ($wpdb->get_var("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '$table' AND COLUMN_NAME = 'payment_details'") == 0) {
            $wpdb->query("ALTER TABLE $table ADD COLUMN payment_details longtext DEFAULT NULL AFTER payment_email");
        }
        if ($wpdb->get_var("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '$table' AND COLUMN_NAME = 'payment_method'") == 0) {
            $wpdb->query("ALTER TABLE $table ADD COLUMN payment_method varchar(50) DEFAULT NULL AFTER payment_details");
        }

        // Add referral attribution columns if missing.
        if ($wpdb->get_var("SHOW TABLES LIKE '$referrals_table'") === $referrals_table) {
            $referral_columns = [
                'cancelled_reason' => ['definition' => 'varchar(100) DEFAULT NULL', 'after' => 'status'],
                'cancelled_at'     => ['definition' => 'datetime DEFAULT NULL', 'after' => 'cancelled_reason'],
                'utm_source'       => ['definition' => 'varchar(100) DEFAULT NULL', 'after' => 'cancelled_at'],
                'utm_medium'       => ['definition' => 'varchar(100) DEFAULT NULL', 'after' => 'utm_source'],
                'utm_campaign'     => ['definition' => 'varchar(255) DEFAULT NULL', 'after' => 'utm_medium'],
                'utm_content'      => ['definition' => 'varchar(255) DEFAULT NULL', 'after' => 'utm_campaign'],
                'utm_term'         => ['definition' => 'varchar(255) DEFAULT NULL', 'after' => 'utm_content'],
                'referrer_url'     => ['definition' => 'varchar(500) DEFAULT NULL', 'after' => 'utm_term'],
            ];

            foreach ($referral_columns as $column => $schema) {
                if ($wpdb->get_var("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '$referrals_table' AND COLUMN_NAME = '$column'") == 0) {
                    $wpdb->query("ALTER TABLE $referrals_table ADD COLUMN $column {$schema['definition']} AFTER {$schema['after']}");
                }
            }
        }
    }

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

    /**
     * Run migrations (called on admin_init)
     */
    public static function run_migrations()
    {
        // Only run once per session (check transient)
        if (get_transient('woonoow_affiliate_migrated')) {
            return;
        }

        self::migrate_existing_tables();
        set_transient('woonoow_affiliate_migrated', true, DAY_IN_SECONDS);
    }
}
