<?php

/**
 * Affiliate Manager
 *
 * Handles database table creation and core management.
 *
 * @package WooNooW\Modules\Affiliate
 */

namespace WooNooW\Modules\Affiliate;

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

class AffiliateManager
{
    private static $affiliates_table = 'woonoow_affiliates';
    private static $referrals_table = 'woonoow_referrals';
    private static $payouts_table = 'woonoow_affiliate_payouts';

    /**
     * Initialize
     */
    public static function init()
    {
        // Initialization logic for the manager if needed
    }

    /**
     * Create database tables
     */
    public static function create_tables()
    {
        global $wpdb;
        $charset_collate = $wpdb->get_charset_collate();

        $affiliates_table = $wpdb->prefix . self::$affiliates_table;
        $referrals_table = $wpdb->prefix . self::$referrals_table;
        $payouts_table = $wpdb->prefix . self::$payouts_table;

        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

        // Affiliates Table
        $sql_affiliates = "CREATE TABLE $affiliates_table (
            id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            user_id bigint(20) UNSIGNED NOT NULL,
            referral_code varchar(50) NOT NULL,
            coupon_id bigint(20) UNSIGNED DEFAULT NULL,
            commission_rate decimal(10,2) NOT NULL DEFAULT '0.00',
            custom_commission_rate decimal(10,2) DEFAULT NULL,
            status varchar(20) NOT NULL DEFAULT 'pending',
            total_referrals int(11) NOT NULL DEFAULT 0,
            total_earnings decimal(19,4) NOT NULL DEFAULT '0.0000',
            paid_earnings decimal(19,4) NOT NULL DEFAULT '0.0000',
            payment_bank_name varchar(100) DEFAULT NULL,
            payment_bank_account varchar(100) DEFAULT NULL,
            payment_email varchar(100) DEFAULT NULL,
            created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY  (id),
            UNIQUE KEY user_id (user_id),
            UNIQUE KEY referral_code (referral_code),
            KEY status (status)
        ) $charset_collate;";

        dbDelta($sql_affiliates);

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

        // Add payment details columns if they don't exist (for existing installations)
        $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 = '$affiliates_table' AND COLUMN_NAME = '$col'") == 0) {
                $col_def = $col === 'payment_email' ? "varchar(100) DEFAULT NULL" : "varchar(100) DEFAULT NULL";
                $wpdb->query("ALTER TABLE $affiliates_table ADD COLUMN $col $col_def AFTER paid_earnings");
            }
        }

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

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

        // Referrals Table
        $sql_referrals = "CREATE TABLE $referrals_table (
            id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            affiliate_id bigint(20) UNSIGNED NOT NULL,
            order_id bigint(20) UNSIGNED NOT NULL,
            customer_id bigint(20) UNSIGNED DEFAULT NULL,
            commission_amount decimal(19,4) NOT NULL DEFAULT '0.0000',
            currency varchar(10) NOT NULL DEFAULT 'USD',
            status varchar(20) NOT NULL DEFAULT 'pending',
            cancelled_reason varchar(100) DEFAULT NULL,
            cancelled_at datetime DEFAULT NULL,
            utm_source varchar(100) DEFAULT NULL,
            utm_medium varchar(100) DEFAULT NULL,
            utm_campaign varchar(255) DEFAULT NULL,
            utm_content varchar(255) DEFAULT NULL,
            utm_term varchar(255) DEFAULT NULL,
            referrer_url varchar(500) DEFAULT NULL,
            created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
            approved_at datetime DEFAULT NULL,
            paid_at datetime DEFAULT NULL,
            PRIMARY KEY  (id),
            KEY affiliate_id (affiliate_id),
            KEY order_id (order_id),
            KEY status (status)
        ) $charset_collate;";

        dbDelta($sql_referrals);

        // Add cancelled columns if they don't exist (for existing installations)
        if ($wpdb->get_var("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '$referrals_table' AND COLUMN_NAME = 'cancelled_reason'") == 0) {
            $wpdb->query("ALTER TABLE $referrals_table ADD COLUMN cancelled_reason varchar(100) DEFAULT NULL AFTER status");
        }
        if ($wpdb->get_var("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '$referrals_table' AND COLUMN_NAME = 'cancelled_at'") == 0) {
            $wpdb->query("ALTER TABLE $referrals_table ADD COLUMN cancelled_at datetime DEFAULT NULL AFTER cancelled_reason");
        }

        // Add UTM columns if they don't exist (for existing installations)
        $utm_columns = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term', 'referrer_url'];
        foreach ($utm_columns as $col) {
            if ($wpdb->get_var("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '$referrals_table' AND COLUMN_NAME = '$col'") == 0) {
                $col_def = $col === 'referrer_url' ? "varchar(500) DEFAULT NULL" : ($col === 'utm_campaign' || $col === 'utm_content' || $col === 'utm_term' ? "varchar(255) DEFAULT NULL" : "varchar(100) DEFAULT NULL");
                $after_col = $col === 'utm_source' ? 'cancelled_at' : ($col === 'utm_medium' ? 'utm_source' : ($col === 'utm_campaign' ? 'utm_medium' : ($col === 'utm_content' ? 'utm_campaign' : ($col === 'utm_term' ? 'utm_content' : 'utm_term'))));
                $wpdb->query("ALTER TABLE $referrals_table ADD COLUMN $col $col_def AFTER cancelled_at");
            }
        }

        // Payouts Table
        $sql_payouts = "CREATE TABLE $payouts_table (
            id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            affiliate_id bigint(20) UNSIGNED NOT NULL,
            amount decimal(19,4) NOT NULL,
            currency varchar(10) NOT NULL DEFAULT 'USD',
            method varchar(50) NOT NULL,
            status varchar(20) NOT NULL DEFAULT 'pending',
            notes text DEFAULT NULL,
            created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
            completed_at datetime DEFAULT NULL,
            PRIMARY KEY  (id),
            KEY affiliate_id (affiliate_id),
            KEY status (status)
        ) $charset_collate;";

        dbDelta($sql_payouts);
    }
}
