<?php
/**
 * Freemius SDK Configuration
 *
 * This file initializes the Freemius SDK for premium licensing.
 * Must be included BEFORE other plugin includes in consolety.php.
 *
 * @package Consolety
 */

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

if (!function_exists('consolety_fs')) {
    /**
     * Initialize Freemius SDK
     *
     * @return \Freemius
     */
    function consolety_fs() {
        global $consolety_fs;

        if (!isset($consolety_fs)) {
            // Check if SDK exists
            $sdk_path = dirname(__FILE__) . '/../vendor/freemius/start.php';
            if (!file_exists($sdk_path)) {
                // SDK not installed - return null-safe stub
                return null;
            }

            require_once $sdk_path;

            $consolety_fs = fs_dynamic_init(array(
                'id'                  => '24009',
                'slug'                => 'consolety',
                'premium_slug'        => 'consolety-premium',
                'type'                => 'plugin',
                'public_key'          => 'pk_5393660fcf9c22eb601554eb316b7',
                'is_premium'          => false,
                'premium_suffix'      => 'Pro',
                'has_addons'          => false,
                'has_paid_plans'      => true,
                'is_org_compliant'    => true,
                // Start anonymous: no opt-in wall on first run, no data sent to
                // Freemius until the user chooses to. Without this the SDK enters
                // activation mode and REPLACES the Consolety dashboard with its
                // consent screen (verified on a fresh WP.org install, 2026-07-16),
                // which also suppresses the pricing page and breaks every upgrade CTA.
                'anonymous_mode'      => true,
                                'menu'                => array(
                    'slug'           => 'consolety',
                    'support'        => false,
                    'account'        => false,
                    'contact'        => false,
                    'pricing'        => false,
                    'affiliation'    => false,
                    'addons'         => false,
                ),
            ));
        }

        return $consolety_fs;
    }

    /**
     * Check if current Freemius install is Pro
     *
     * @return bool
     */
    function consolety_is_freemius_pro() {
        if (!function_exists('consolety_fs')) {
            return false;
        }
        $fs = consolety_fs();
        if (!$fs) {
            return false;
        }
        if (method_exists($fs, 'is_paying') && $fs->is_paying()) {
            return true;
        }
        return false;
    }

    // Initialize Freemius (safely - don't crash the site if SDK fails)
    try {
        $consolety_fs_instance = consolety_fs();

        // Signal that Freemius has loaded
        do_action('consolety_fs_loaded');

        // Register tier sync hooks (only if Freemius loaded successfully)
        if ($consolety_fs_instance) {
            // Sync on license activation/change
            $consolety_fs_instance->add_action('after_license_change', 'consolety_sync_tier_to_hub');

            // Sync on subscription cancel
            $consolety_fs_instance->add_action('after_subscription_cancel', 'consolety_sync_tier_to_hub');

            // Sync on plan change (upgrade/downgrade)
            $consolety_fs_instance->add_action('after_plan_change', 'consolety_sync_tier_to_hub');

            // Sync on install (first activation)
            $consolety_fs_instance->add_action('after_install', 'consolety_sync_tier_to_hub');
        }
    } catch (\Exception $e) {
        // Silently handle - don't crash the site if SDK fails
    } catch (\Error $e) {
        // Silently handle PHP fatal errors from broken SDK state
    }
}

/**
 * Sync Freemius tier status to Hub API
 * Called on license change, subscription cancel, plan change
 */
function consolety_sync_tier_to_hub() {
    $fs = consolety_fs();
    if (!$fs) {
        return;
    }

    // Only sync if we have a trust token (site is registered)
    $trust_token = get_option('consolety_trust_token', '');
    if (empty($trust_token)) {
        return;
    }

    // Use canonical get_site() for install/plan/license data
    $site_obj = null;
    if (method_exists($fs, 'get_site')) {
        try {
            $site_obj = $fs->get_site();
        } catch (\Exception $e) {
            // get_site() may fail if not registered yet
        } catch (\Error $e) {
            // Catch fatal errors from broken SDK state
        }
    }

    // Extract install_id from site object
    $install_id = null;
    if ($site_obj && isset($site_obj->id)) {
        $install_id = $site_obj->id;
    }

    // Extract plan_id: try get_plan_id() first, fallback to site object
    $plan_id = null;
    if (method_exists($fs, 'get_plan_id')) {
        try {
            $plan_id = $fs->get_plan_id();
        } catch (\Exception $e) {}
        catch (\Error $e) {}
    }
    if (!$plan_id && $site_obj && isset($site_obj->plan_id)) {
        $plan_id = $site_obj->plan_id;
    }

    // Extract license_id from site object first, then _get_license() fallback
    $license_id = null;
    if ($site_obj && isset($site_obj->license_id) && $site_obj->license_id) {
        $license_id = $site_obj->license_id;
    }
    if (!$license_id) {
        try {
            if (method_exists($fs, '_get_license')) {
                $license = $fs->_get_license();
                if ($license && isset($license->id)) {
                    $license_id = $license->id;
                }
            }
        } catch (\Exception $e) {
            // License may not exist yet, that's OK
        }
    }

    // Check premium status
    $is_premium = false;
    if (method_exists($fs, 'is_paying') && $fs->is_paying()) {
        $is_premium = true;
    }

    // Build sync data - send whatever we have, don't block on missing fields
    $sync_data = [
        'install_id'  => $install_id ? (string) $install_id : null,
        'plan_id'     => $plan_id ? (string) $plan_id : null,
        'license_id'  => $license_id ? (string) $license_id : null,
        'is_premium'  => $is_premium,
    ];

    // If we have no Freemius data at all, at least tell Hub the paying status
    if (empty($install_id) && empty($plan_id) && !$is_premium) {
        return; // Nothing useful to sync
    }

    // Make API call to Hub
    $api = new \Consolety\Api();
    $response = $api->post('/subscription/validate-freemius', $sync_data);

    // Note: Api wrapper returns array, not WP_Error
    if (!$response || (isset($response['success']) && $response['success'] === false)) {
        // Tier sync failed - no action needed
    } else {
        // Update local cache of tier - API returns data.tier
        $tier = $response['data']['tier'] ?? $response['tier'] ?? null;
        if ($tier) {
            $site_info = get_option('consolety_site_info', []);
            $site_info['subscription_tier'] = $tier;
            update_option('consolety_site_info', $site_info);
        }
    }
}
