<?php require_once "/var/www/html/config.database.php"; ?>
<?php
/**
 * FXHunterAI sync_license.php
 *
 * - Runs after order/license creation (triggered by fxh-license-sync plugin)
 * - Reads licenses from License Manager for WooCommerce
 * - Uses plugin's own decryption (getDecryptedLicenseKey)
 * - Stores ONLY readable keys into fxh_licenses
 * - Fires fxh_license_synced($readable_key, $email)
 * - Auto-creates /webhook/signals/latest_signal_{readable_key}.txt
 */

//
// 0. Bootstrap WordPress if called directly
//
if ( ! defined('ABSPATH') ) {
    // this file is in /webhook/, go one level up to WP root
    $wp_load = dirname(__DIR__) . '/wp-load.php';
    if (file_exists($wp_load)) {
        require_once $wp_load;
    } else {
        error_log('❌ FXH sync_license.php: wp-load.php not found. Abort.');
        return;
    }
}

if ( ! function_exists('do_action') ) {
    error_log('❌ FXH sync_license.php: WordPress core not loaded. Abort.');
    return;
}

global $wpdb;

error_log('✅ FXH sync_license.php loaded (decrypt-fix final)');

//
// 1. Resolve table names
//
$source_table = $wpdb->prefix . 'lmfwc_licenses'; // LMFWC licenses table
$target_table = 'fxh_licenses';                   // your custom table (NO prefix)

//
// 2. Helper: get readable (decrypted) license key
//
function fxh_sync_readable_key($lic) {

    // Already readable? (doesn't look like LMFWC encrypted blob)
    if (!empty($lic->license_key) && strpos($lic->license_key, 'def5020') !== 0) {
        return sanitize_text_field(trim($lic->license_key));
    }

    $plain = '';

    // a) Use Repository + getDecryptedLicenseKey() if available
    try {
        if (class_exists('LicenseManagerForWooCommerce\\Repositories\\Resources\\License')) {
            $repo = LicenseManagerForWooCommerce\Repositories\Resources\License::instance();

            if ($repo && method_exists($repo, 'find')) {
                $obj = $repo->find($lic->id);
                if ($obj && method_exists($obj, 'getDecryptedLicenseKey')) {
                    $tmp = $obj->getDecryptedLicenseKey();
                    if (!empty($tmp) && strpos($tmp, 'def5020') !== 0) {
                        $plain = $tmp;
                    }
                }
            }
        }
    } catch (Throwable $e) {
        error_log('⚠️ FXH decrypt(repo/find) failed for ID ' . $lic->id . ': ' . $e->getMessage());
    }

    // b) Try global helper lmfwc_decrypt()
    if ($plain === '' && function_exists('lmfwc_decrypt')) {
        try {
            $tmp = lmfwc_decrypt($lic->license_key);
            if (!empty($tmp) && strpos($tmp, 'def5020') !== 0) {
                $plain = $tmp;
            }
        } catch (Throwable $e) {
            error_log('⚠️ FXH decrypt(lmfwc_decrypt) failed for ID ' . $lic->id . ': ' . $e->getMessage());
        }
    }

    // c) Try License model decrypt()
    if ($plain === '' && class_exists('LicenseManagerForWooCommerce\\Models\\License')) {
        try {
            $m = new LicenseManagerForWooCommerce\Models\License();
            if (method_exists($m, 'decrypt')) {
                $tmp = $m->decrypt($lic->license_key);
                if (!empty($tmp) && strpos($tmp, 'def5020') !== 0) {
                    $plain = $tmp;
                }
            }
        } catch (Throwable $e) {
            error_log('⚠️ FXH decrypt(Model) failed for ID ' . $lic->id . ': ' . $e->getMessage());
        }
    }

    // d) Try filter hook (legacy)
    if ($plain === '' && has_filter('lmfwc_decrypt_license_key')) {
        try {
            $tmp = apply_filters('lmfwc_decrypt_license_key', $lic->license_key);
            if (!empty($tmp) && strpos($tmp, 'def5020') !== 0) {
                $plain = $tmp;
            }
        } catch (Throwable $e) {
            error_log('⚠️ FXH decrypt(filter) failed for ID ' . $lic->id . ': ' . $e->getMessage());
        }
    }

    // e) Final fallback: if still empty OR still def502..., log and use encrypted
    if ($plain === '' || strpos($plain, 'def5020') === 0) {
        error_log('⚠️ FXH decrypt: using encrypted key for ID ' . $lic->id . ' (no valid decrypt result)');
        $plain = $lic->license_key;
    }

    return sanitize_text_field(trim($plain));
}

//
// 3. Fetch latest licenses directly from LMFWC table
//
$licenses = $wpdb->get_results("SELECT * FROM {$source_table} ORDER BY id DESC LIMIT 50");

if (empty($licenses)) {
    error_log('ℹ️ FXH: No licenses found in source table.');
    return;
}

//
// 4. Process each license
//
foreach ($licenses as $lic) {

    // --- Get readable key (or best-effort)
    $license_key = fxh_sync_readable_key($lic);

    // --- Plan / product title
    $plan = 'UNKNOWN';
    if (!empty($lic->product_id)) {
        $t = get_the_title($lic->product_id);
        if ($t) {
            $plan = $t;
        }
    }

    // --- Owner email (user or order)
    $user_email = '';
    if (!empty($lic->user_id)) {
        $user = get_user_by('ID', $lic->user_id);
        if ($user && !empty($user->user_email)) {
            $user_email = $user->user_email;
        }
    }
    if ($user_email === '' && !empty($lic->order_id) && function_exists('wc_get_order')) {
        $order = wc_get_order($lic->order_id);
        if ($order) {
            $user_email = $order->get_billing_email();
        }
    }
    if ($user_email === '') {
        $user_email = 'guest@unknown.com';
    }

    // --- Expiry date
    $expires_at = null;
    if (!empty($lic->expires_at) && $lic->expires_at !== '0000-00-00 00:00:00') {
        $expires_at = date('Y-m-d H:i:s', strtotime($lic->expires_at));
    }

    // --- Skip if this readable key already synced
    $exists = $wpdb->get_var(
        $wpdb->prepare(
            "SELECT COUNT(*) FROM {$target_table} WHERE license_key = %s",
            $license_key
        )
    );
    if ($exists > 0) {
        continue;
    }

    // --- Insert into fxh_licenses
    $inserted = $wpdb->query(
        $wpdb->prepare(
            "INSERT INTO {$target_table}
                (license_key, plan, user_email, mt5_account, active, created_at, expires_at)
             VALUES
                (%s, %s, %s, %d, %d, NOW(), %s)",
            $license_key,
            $plan,
            $user_email,
            0,
            1,
            $expires_at
        )
    );

    if ($inserted === false) {
        error_log('❌ FXH DB insert failed for key ' . $license_key . ' — ' . $wpdb->last_error);
        continue;
    }

    error_log("✅ FXH License Synced — {$license_key} | {$plan} | {$user_email}");

    //
    // 4.a Fire hook for plugin (batched email etc.) with READABLE key
    //
    do_action('fxh_license_synced', $license_key, $user_email);
    error_log("📢 FXH Hook fired for {$license_key}");

    //
    // 4.b Safety: create signal file for this license (READABLE key)
    //
    $signals_dir = __DIR__ . '/signals';
    if (!is_dir($signals_dir)) {
        if (!mkdir($signals_dir, 0755, true) && !is_dir($signals_dir)) {
            error_log('❌ FXH: Failed to create signals dir: ' . $signals_dir);
            continue;
        }
    }

    $licenseClean = preg_replace('/[^A-Za-z0-9_-]/', '', $license_key);
    $file_path    = $signals_dir . '/latest_signal_' . $licenseClean . '.txt';
    $admin_path   = $signals_dir . '/latest_signal.txt';

    $timestamp = gmdate('Y-m-d H:i:s');
    $line      = $license_key . ',noop,INIT,comment=Auto-created-by-sync|' . $timestamp . PHP_EOL;

    file_put_contents($file_path, $line, LOCK_EX);
    file_put_contents($admin_path, $line, LOCK_EX);

    error_log("✅ FXH: Signal file created for {$license_key} at {$file_path}");
}

error_log('✅ FXH sync_license.php executed successfully (decrypt-fix final)');
