<?php
if (!defined('ABSPATH')) exit;

/**
 * Plan helpers — Freemius is source of truth.
 * Free  = full manual workflow (real value for small sites).
 * Pro   = automation (bulk, background, scheduled, auto-on-event).
 * Agency = Pro + unlimited sites + white-label.
 *
 * Gate automation with aisb_can_automate(), not aisb_is_pro() alone,
 * so trial users can test automation (BYOK only during trial).
 */

function aisb_default_settings() {
    return [
        'api_key' => '',
        'api_key_verified' => 0,
        'provider' => 'openai',
        'model' => 'gpt-4o-mini',
        'global_context' => '',
        'output_mode' => 'enabled',
        'seo_coexist_mode' => 'smart',
        'global_schema_enabled' => 1,
        'breadcrumb_enabled' => 1,
        'validation_scan_enabled' => 0,
        'enabled_post_types' => [],
        'cpt_schema_map' => [],
        'schema_field_map' => [],
        'cpt_defaults_seeded' => 0,
        'etch_native_ui' => 1,
        'auto_generate' => 0,
        'batch_size' => 3,
        'batch_delay' => 5,
        'onboarding_done' => 0,
        'notify_email_enabled' => 0,
        'notify_email_failures' => 1,
        'notify_email_to' => get_option('admin_email'),
        'whitelabel_enabled' => 0,
        'whitelabel_brand' => '',
        'whitelabel_logo' => '',
    ];
}

function aisb_safe_json($data) {
    return wp_json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}

/**
 * Prefer shared PEWIT Labs hub credentials when 2+ suite plugins are active.
 *
 * @return array{api_key:string,provider:string,model:string,global_context:string,from_hub:bool}
 */
function aisb_effective_api_credentials() {
    if (class_exists('Pewit_Labs_Hub')) {
        $hub = Pewit_Labs_Hub::credentials();
        if ($hub) {
            $hub['from_hub'] = true;
            return $hub;
        }
    }
    $s = aisb_get_settings();
    return [
        'api_key'        => (string) ($s['api_key'] ?? ''),
        'provider'       => (string) ($s['provider'] ?? 'openai'),
        'model'          => (string) ($s['model'] ?? 'gpt-4o-mini'),
        'global_context' => (string) ($s['global_context'] ?? ''),
        'from_hub'       => false,
    ];
}

function aisb_llm_args($overrides = []) {
    $c = aisb_effective_api_credentials();
    $provider = AISB_LLM_API::normalize_provider($c['provider'] ?? 'openai');
    return array_merge([
        'api_key'     => (string) ($c['api_key'] ?? ''),
        'provider'    => $provider,
        'model'       => (string) ($c['model'] ?? AISB_LLM_API::default_model($provider)),
        'pro_allowed' => true,
    ], $overrides);
}

function aisb_llm_localize_message($message) {
    $message = (string) $message;
    $catalog = [
        'Connected successfully'                  => __('Connected successfully', 'pewit-ai-schema-builder'),
        'API key is empty'                        => __('API key is empty', 'pewit-ai-schema-builder'),
        'WordPress AI connectors are not configured for text generation.' => __('WordPress AI connectors are not configured for text generation.', 'pewit-ai-schema-builder'),
        'Empty response from WordPress AI Client.' => __('Empty response from WordPress AI Client.', 'pewit-ai-schema-builder'),
        'Claude and Gemini require Pro or trial.' => __('Claude and Gemini require Pro or trial.', 'pewit-ai-schema-builder'),
        'Empty response from OpenAI.'             => __('Empty response from OpenAI.', 'pewit-ai-schema-builder'),
        'Empty response from Claude.'               => __('Empty response from Claude.', 'pewit-ai-schema-builder'),
        'Empty response from Gemini.'               => __('Empty response from Gemini.', 'pewit-ai-schema-builder'),
        'No messages to send.'                      => __('No messages to send.', 'pewit-ai-schema-builder'),
        'Invalid API key or unauthorized account.'  => __('Invalid API key or unauthorized account.', 'pewit-ai-schema-builder'),
    ];
    if (isset($catalog[$message])) {
        return $catalog[$message];
    }
    if (strpos($message, 'Rate limit or billing issue.') === 0) {
        return __('Rate limit or billing issue.', 'pewit-ai-schema-builder') . substr($message, 30);
    }
    return $message;
}

function aisb_llm_localize_test_result(array $result) {
    if (!empty($result['message'])) {
        $result['message'] = aisb_llm_localize_message($result['message']);
    }
    return $result;
}

function aisb_llm_localize_error($error) {
    if (!is_wp_error($error)) {
        return $error;
    }
    return new WP_Error($error->get_error_code(), aisb_llm_localize_message($error->get_error_message()), $error->get_error_data());
}

function aisb_render_provider_select(array $settings, array $args = []) {
    $id = $args['id'] ?? 'aisb_provider';
    $name = $args['name'] ?? 'provider';
    $pro = !empty($args['pro_allowed']);
    $current = AISB_LLM_API::sanitize_provider_setting($settings['provider'] ?? 'openai', $pro);
    ?>
    <label for="<?php echo esc_attr($id); ?>"><?php esc_html_e('Provider', 'pewit-ai-schema-builder'); ?></label>
    <select id="<?php echo esc_attr($id); ?>" name="<?php echo esc_attr($name); ?>">
        <option value="openai" <?php selected($current, 'openai'); ?>>OpenAI</option>
        <option value="anthropic" <?php selected($current, 'anthropic'); ?> <?php disabled(!$pro); ?>>Claude<?php echo $pro ? '' : ' (Pro)'; ?></option>
        <option value="google" <?php selected($current, 'google'); ?> <?php disabled(!$pro); ?>>Gemini<?php echo $pro ? '' : ' (Pro)'; ?></option>
    </select>
    <?php if (!empty($args['description'])): ?>
    <p class="description"><?php echo esc_html($args['description']); ?></p>
    <?php endif;
}

function aisb_api_ready() {
    if (AISB_LLM_API::core_text_generation_supported()) {
        return true;
    }
    if (class_exists('Pewit_Labs_Hub')) {
        $hub = Pewit_Labs_Hub::credentials();
        if ($hub) {
            return true;
        }
    }
    $s = aisb_get_settings();
    return !empty($s['api_key']) && !empty($s['api_key_verified']);
}

function aisb_api_key_masked_label($key) {
    $key = trim((string) $key);
    if ($key === '') {
        return '';
    }
    if (strlen($key) <= 4) {
        return str_repeat('•', 12);
    }
    return '••••••••' . substr($key, -4);
}

function aisb_admin_url($tab = 'dashboard') {
    $pages = [
        'dashboard' => 'pewit-ai-schema-builder',
        'schema'    => 'pewit-ai-schema-builder-schema',
        'jobs'      => 'pewit-ai-schema-builder-jobs',
        'settings'  => 'pewit-ai-schema-builder-settings',
    ];
    $page = $pages[$tab] ?? $pages['dashboard'];
    return admin_url('admin.php?page=' . $page);
}

function aisb_get_settings() {
    return wp_parse_args(get_option(AISB_OPTION, []), aisb_default_settings());
}

function aisb_update_settings($settings) {
    update_option(AISB_OPTION, wp_parse_args($settings, aisb_default_settings()));
}

function aisb_brand_name() {
    $s = aisb_get_settings();
    if (!empty($s['whitelabel_enabled']) && !empty($s['whitelabel_brand'])) {
        return $s['whitelabel_brand'];
    }
    return 'Pewit AI Schema Builder';
}

function aisb_plan() {
    return 'free';
}

/**
 * Feature gates.
 *
 * In the wordpress.org FREE build (AISB_PRO is false/undefined) every feature is
 * markers, leaving the free fallback. In the Freemius PRO build (AISB_PRO === true)
 * features are gated by the real Freemius plan, so the paid product can sell Pro/Agency tiers.
 */
function aisb_is_pro_build() {
    return defined('AISB_PRO') && AISB_PRO;
}

function aisb_is_pro() {
    return true;
}

function aisb_is_agency() {
    return true;
}

function aisb_is_trial() {
    return false;
}

/**
 * Automation gate: background jobs, bulk ops, scheduled tasks, auto-on-upload/publish.
 * Manual single-item actions stay available on Free.
 */
function aisb_can_automate() {
    return true;
}

/**
 * Managed AI credits (external paid service, not implemented here). BYOK only.
 */
function aisb_managed_credits_enabled() {
    return false;
}

function aisb_plan_label() {
    $map = ['free' => 'Free', 'pro' => 'Pro', 'agency' => 'Agency'];
    return $map[aisb_plan()] ?? 'Free';
}

function aisb_upgrade_url() {
    if (function_exists('aisb_freemius')) {
        $fs = aisb_freemius();
        if ($fs && method_exists($fs, 'get_upgrade_url')) {
            $url = $fs->get_upgrade_url();
            if ($url) return $url;
        }
    }
    return 'https://pewitlabs.com/product-ai-schema-builder.html';
}

function aisb_account_url() {
    if (function_exists('aisb_freemius')) {
        $fs = aisb_freemius();
        if ($fs && method_exists($fs, 'get_account_url')) {
            $url = $fs->get_account_url();
            if ($url) return $url;
        }
    }
    return '';
}

function aisb_whitelabel() {
    $s = aisb_get_settings();
    $on = aisb_is_agency() && !empty($s['whitelabel_enabled']);
    return [
        'enabled' => $on,
        'brand'   => $on && !empty($s['whitelabel_brand']) ? (string) $s['whitelabel_brand'] : '',
        'logo'    => $on && !empty($s['whitelabel_logo']) ? (string) $s['whitelabel_logo'] : '',
    ];
}

function aisb_docs_url($path = '') {
    $base = 'https://pewitlabs.com/docs/pewit-ai-schema-builder/';
    return $path ? $base . ltrim($path, '/') : $base;
}

/** Human message when a free user hits an automation feature. */
function aisb_automation_upgrade_message() {
    return sprintf(
        /* translators: %s: Pro plan name */
        __('Bulk and background automation requires %s or Agency. Manual actions remain free with your own OpenAI key.', 'pewit-ai-schema-builder'),
        'Pro'
    );
}
