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

/**
 * Plan helpers — Freemius is source of truth.
 * Free  = full manual workflow with your own key (BYOK), one item at a time.
 * Pro   = automation (bulk, background, scheduled scans, history) + Claude/Gemini.
 * Agency = Pro + unlimited sites + white-label + competitor monitoring + client reports.
 *
 * Gate automation with aivt_can_automate(), not aivt_is_pro() alone,
 * so trial users can test automation (BYOK only during trial).
 */

function aivt_default_settings() {
    return [
        'api_key'            => '',
        'api_key_verified'   => 0,
        'provider'           => 'openai',
        'model'              => 'gpt-4o-mini',
        'brand_name'         => get_bloginfo('name'),
        'brand_aliases'      => '',
        'business_type'      => '',
        'location'           => '',
        'global_context'     => '',
        'target_keywords'    => '',
        'competitors'        => '',
        'enabled_post_types' => ['post', 'page'],
        // Automation (Pro)
        'auto_analyze'       => 0,
        'batch_size'         => 3,
        'batch_delay'        => 5,
        'prompt_schedule'    => 'off', // off|weekly|monthly
        // Notifications
        'notify_email_enabled'  => 0,
        'notify_email_to'       => get_option('admin_email'),
        // White-label (Agency)
        'whitelabel_enabled' => 0,
        'whitelabel_brand'   => '',
        'whitelabel_logo'    => '',
        'onboarding_done'    => 0,
    ];
}

function aivt_get_settings() {
    return wp_parse_args(get_option(AIVT_OPTION, []), aivt_default_settings());
}

function aivt_update_settings($settings) {
    update_option(AIVT_OPTION, wp_parse_args($settings, aivt_default_settings()));
}

function aivt_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 aivt_effective_api_credentials() {
    if (class_exists('Pewit_Labs_Hub')) {
        $hub = Pewit_Labs_Hub::credentials();
        if ($hub) {
            $hub['from_hub'] = true;
            return $hub;
        }
    }
    $s = aivt_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 aivt_llm_args($overrides = []) {
    $c = aivt_effective_api_credentials();
    $provider = AIVT_LLM_API::normalize_provider($c['provider'] ?? 'openai');
    return array_merge([
        'api_key'     => (string) ($c['api_key'] ?? ''),
        'provider'    => $provider,
        'model'       => (string) ($c['model'] ?? AIVT_LLM_API::default_model($provider)),
        'pro_allowed' => aivt_is_pro() || aivt_is_trial(),
    ], $overrides);
}

function aivt_llm_localize_message($message) {
    $message = (string) $message;
    $catalog = [
        'Connected successfully'                    => __('Connected successfully', 'pewit-geo-analysis-tool'),
        'API key is empty'                          => __('API key is empty', 'pewit-geo-analysis-tool'),
        'Claude and Gemini require Pro or trial.'    => __('Claude and Gemini require Pro or trial.', 'pewit-geo-analysis-tool'),
        'Empty response from OpenAI.'               => __('Empty response from OpenAI.', 'pewit-geo-analysis-tool'),
        'Empty response from Claude.'               => __('Empty response from Claude.', 'pewit-geo-analysis-tool'),
        'Empty response from Gemini.'               => __('Empty response from Gemini.', 'pewit-geo-analysis-tool'),
        'No messages to send.'                      => __('No messages to send.', 'pewit-geo-analysis-tool'),
        'Invalid API key or unauthorized account.'  => __('Invalid API key or unauthorized account.', 'pewit-geo-analysis-tool'),
    ];
    if (isset($catalog[$message])) {
        return $catalog[$message];
    }
    if (strpos($message, 'Rate limit or billing issue.') === 0) {
        return __('Rate limit or billing issue.', 'pewit-geo-analysis-tool') . substr($message, 30);
    }
    return $message;
}

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

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

function aivt_render_provider_select(array $settings, array $args = []) {
    $id = $args['id'] ?? 'aivt_provider';
    $name = $args['name'] ?? 'provider';
    $pro = !empty($args['pro_allowed']);
    $current = AIVT_LLM_API::sanitize_provider_setting($settings['provider'] ?? 'openai', $pro);
    ?>
    <label for="<?php echo esc_attr($id); ?>"><?php esc_html_e('Provider', 'pewit-geo-analysis-tool'); ?></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 aivt_api_ready() {
    if (class_exists('Pewit_Labs_Hub')) {
        $hub = Pewit_Labs_Hub::credentials();
        if ($hub) {
            return true;
        }
    }
    $s = aivt_get_settings();
    return !empty($s['api_key']) && !empty($s['api_key_verified']);
}

function aivt_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 aivt_admin_url($tab = 'dashboard') {
    $pages = [
        'dashboard'   => 'pewit-geo-analysis-tool',
        'content'     => 'pewit-geo-analysis-tool-content',
        'prompts'     => 'pewit-geo-analysis-tool-prompts',
        'competitors' => 'pewit-geo-analysis-tool-competitors',
        'jobs'        => 'pewit-geo-analysis-tool-jobs',
        'suggestions' => 'pewit-geo-analysis-tool-suggestions',
        'settings'    => 'pewit-geo-analysis-tool-settings',
    ];
    $page = $pages[$tab] ?? $pages['dashboard'];
    return admin_url('admin.php?page=' . $page);
}

function aivt_brand_name() {
    $s = aivt_get_settings();
    if (!empty($s['whitelabel_enabled']) && !empty($s['whitelabel_brand']) && aivt_is_agency()) {
        return $s['whitelabel_brand'];
    }
    return 'Pewit GEO Analysis Tool';
}

/** The site's own brand/business name used across prompts and citation checks. */
function aivt_site_brand() {
    $s = aivt_get_settings();
    $brand = trim((string) ($s['brand_name'] ?? ''));
    return $brand !== '' ? $brand : get_bloginfo('name');
}

function aivt_brand_aliases() {
    $s = aivt_get_settings();
    $raw = (string) ($s['brand_aliases'] ?? '');
    $parts = array_filter(array_map('trim', preg_split('/[\n,]+/', $raw)));
    return array_values($parts);
}

function aivt_competitors_list() {
    $s = aivt_get_settings();
    $raw = (string) ($s['competitors'] ?? '');
    $parts = array_filter(array_map('trim', preg_split('/[\n,]+/', $raw)));
    return array_values(array_slice($parts, 0, aivt_is_agency() ? 10 : (aivt_is_pro() ? 3 : 1)));
}

function aivt_plan() {
    return 'free';
}

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

function aivt_is_pro() {
    return true;
}

function aivt_is_agency() {
    return true;
}

function aivt_is_trial() {
    return false;
}

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

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

/** Monthly prompt-test run allowance per plan (manual single runs are always free with BYOK). */
function aivt_prompt_history_enabled() {
    return aivt_can_automate();
}

function aivt_upgrade_url() {
    if (function_exists('aivt_freemius')) {
        $fs = aivt_freemius();
        if ($fs && method_exists($fs, 'get_upgrade_url')) {
            $url = $fs->get_upgrade_url();
            if ($url) return $url;
        }
    }
    return 'https://pewitlabs.com/product-ai-visibility-toolkit.html';
}

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

function aivt_whitelabel() {
    $s = aivt_get_settings();
    $on = aivt_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 aivt_docs_url($path = '') {
    $base = 'https://pewitlabs.com/docs/pewit-geo-analysis-tool/';
    return $path ? $base . ltrim($path, '/') : $base;
}

/** Informational note about automation features (all included for free, BYOK). */
function aivt_automation_upgrade_message() {
    return __('Bulk scans, scheduled monitoring, history and competitor tracking are all included for free. Use your own API key (BYOK).', 'pewit-geo-analysis-tool');
}

function aivt_enabled_post_types() {
    $s = aivt_get_settings();
    $types = $s['enabled_post_types'] ?? ['post', 'page'];
    if (!is_array($types) || empty($types)) {
        $types = ['post', 'page'];
    }
    return array_values(array_intersect($types, get_post_types(['public' => true])));
}
