<?php
declare(strict_types=1);

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

use LolaCore\Admin\Settings;
use WordPress\AiClient\AiClient;

// Fetch current configurations
$lolacore_selected_model        = Settings::getConfig('selected_model', 'auto');
$lolacore_tech_level            = Settings::getConfig('technical_level', 'Professional');
$lolacore_decay_rate            = Settings::getConfig('memory_decay_rate', '0.02');
$lolacore_archive_threshold     = Settings::getConfig('memory_archive_threshold', '0.10');
$lolacore_max_context_entries   = Settings::getConfig('memory_max_context_entries', '20');
$lolacore_log_retention_days    = Settings::getConfig('log_retention_days', '90');

$lolacore_safety_confirm_writes = Settings::getConfig('safety_confirm_writes', '1') === '1';
$lolacore_safety_require_backup = Settings::getConfig('safety_require_backup', '0') === '1';
$lolacore_safety_learning_mode  = Settings::getConfig('safety_learning_mode', '0')  === '1';
$lolacore_last_maintenance_at   = Settings::getConfig('last_maintenance_at', '');

// Fetch real memory stats
$lolacore_memory_manager = new \LolaCore\Memory\MemoryManager();
$lolacore_active_facts = $lolacore_memory_manager->getActiveFactCount();
$lolacore_maintenance_text = 'Never';
$lolacore_maintenance_color = 'red'; // Default: never maintained
if (!empty($lolacore_last_maintenance_at)) {
    $lolacore_maintenance_text = human_time_diff(strtotime($lolacore_last_maintenance_at), current_time('timestamp')) . ' ago';
    $lolacore_hours_since = (current_time('timestamp') - strtotime($lolacore_last_maintenance_at)) / 3600;
    if ($lolacore_hours_since < 24) {
        $lolacore_maintenance_color = 'green';
    } elseif ($lolacore_hours_since > 168) { // 7 days
        $lolacore_maintenance_color = 'amber';
    } else {
        $lolacore_maintenance_color = 'green';
    }
}

// Fetch scan data for header pills
$lolacore_scan_json   = Settings::getConfig('last_scan_data', '{}');
$lolacore_scan_data   = json_decode($lolacore_scan_json, true) ?: [];
$lolacore_plugin_count  = isset($lolacore_scan_data['plugins_total']) ? (int) $lolacore_scan_data['plugins_total'] : count(get_plugins());
$lolacore_updates_count = 0;
$lolacore_update_plugins = get_site_transient('update_plugins');
if (!empty($lolacore_update_plugins->response)) {
    $lolacore_updates_count = count($lolacore_update_plugins->response);
}

$lolacore_avatar_attachment_id  = Settings::getConfig('lola_avatar_attachment_id', 0);
$lolacore_avatar_url            = '';
if ($lolacore_avatar_attachment_id > 0) {
    $lolacore_avatar_url = \wp_get_attachment_image_url((int) $lolacore_avatar_attachment_id, 'thumbnail');
}
if (!$lolacore_avatar_url) {
    $lolacore_avatar_url = \plugin_dir_url(LOLACORE_PLUGIN_FILE) . 'assets/img/lola-default.png';
}

// Retrieve available AI models from the WP 7.0 Connectors registry
$lolacore_wp_models = [];
if (class_exists(AiClient::class)) {
    try {
        $lolacore_registry = AiClient::defaultRegistry();
        $lolacore_provider_ids = $lolacore_registry->getRegisteredProviderIds();
        
        foreach ($lolacore_provider_ids as $lolacore_provider_id) {
            try {
                $lolacore_provider_class = $lolacore_registry->getProviderClassName($lolacore_provider_id);
                $lolacore_metadata = $lolacore_provider_class::metadata();
                $lolacore_provider_name = $lolacore_metadata->getName();
                
                $lolacore_model_dir = $lolacore_provider_class::modelMetadataDirectory();
                $lolacore_models = $lolacore_model_dir->listModelMetadata();
                
                foreach ($lolacore_models as $lolacore_model) {
                    $lolacore_caps = $lolacore_model->getSupportedCapabilities();
                    $lolacore_has_text = empty($lolacore_caps); // If empty, assume it's valid to avoid filtering out everything
                    
                    foreach ($lolacore_caps as $lolacore_cap) {
                        if (((string) $lolacore_cap) === 'text_generation') {
                            $lolacore_has_text = true;
                            break;
                        }
                    }
                    
                    if ($lolacore_has_text) {
                        $lolacore_key = $lolacore_provider_id . '|' . $lolacore_model->getId();
                        $lolacore_wp_models[$lolacore_key] = $lolacore_provider_name . ' - ' . $lolacore_model->getName();
                    }
                }
            } catch (\Throwable $e) {
                // Skip provider if it throws an exception (e.g. auth interface not set)
                continue;
            }
        }
    } catch (\Throwable $e) {
        // Fallback quietly if the API structure changes
    }
}
?>

<div class="lc-settings-container">

    <div class="lc-settings-header">
        <img src="<?php echo esc_url($lolacore_avatar_url); ?>" alt="Lola Avatar" class="lc-avatar header-avatar">
        <div class="lc-settings-header-text">
            <span class="lc-eyebrow">Lola &middot; V<?php echo esc_html(LOLACORE_VERSION); ?></span>
            <h2>Lola Configuration</h2>
            <span class="lc-header-subtitle">Your AI admin agent. Configure once and forget &mdash; Lola remembers the rest.</span>
        </div>
        <div class="lc-header-status">
            <?php if ($lolacore_active_facts > 0) : ?>
                <span class="lc-pill mint">MEMORY ACTIVE</span>
            <?php else : ?>
                <span class="lc-pill gray">NO MEMORY</span>
            <?php endif; ?>
            <span class="lc-pill plum"><?php echo esc_html($lolacore_plugin_count); ?> PLUGINS</span>
            <?php if ($lolacore_updates_count > 0) : ?>
                <span class="lc-pill amber"><?php echo esc_html($lolacore_updates_count); ?> UPDATES</span>
            <?php endif; ?>
        </div>
    </div>

    <div id="lolacore-settings-messages"></div>

    <form id="lolacore-settings-form" method="post">

        <!-- Section 1: Lola's Brain (BYOM) -->
        <div class="lc-card">
            <div class="lc-card-header">
                <span class="lc-section-number">1</span>
                <h3>Lola's Brain (AI Model)</h3>
            </div>
            <p class="description">Lola uses the AI model configured in your WordPress installation. You can add or change providers in <a href="<?php echo esc_url(admin_url('options-connectors.php')); ?>">Settings &rsaquo; Connectors</a>.</p>

            <div style="margin-top: 16px;">
                <label for="lolacore-model" style="display:block; font-weight:600; margin-bottom:8px;">Preferred model for Lola:</label>
                <select id="lolacore-model" name="selected_model" class="lc-select">
                    <option value="auto" <?php selected($lolacore_selected_model, 'auto'); ?>>
                        Automatic (use WordPress default)
                    </option>
                    <?php if (!empty($lolacore_wp_models)) : ?>
                        <?php foreach ($lolacore_wp_models as $lolacore_model_id => $lolacore_model_label) : ?>
                            <option value="<?php echo esc_attr($lolacore_model_id); ?>" <?php selected($lolacore_selected_model, $lolacore_model_id); ?>>
                                <?php echo esc_html($lolacore_model_label); ?>
                            </option>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </select>
                <p class="description" style="margin-top:8px;">
                    <?php if (empty($lolacore_wp_models)) : ?>
                        No AI providers connected yet.
                        <a href="<?php echo esc_url(admin_url('options-connectors.php')); ?>">Connect one now &rarr;</a>
                    <?php else : ?>
                        Select which model Lola will use. "Automatic" uses the first available text generation model.
                    <?php endif; ?>
                </p>
            </div>
        </div>

        <!-- Section 2: Communication Style -->
        <div class="lc-card">
            <div class="lc-card-header">
                <span class="lc-section-number">2</span>
                <h3>Communication Style</h3>
            </div>
            <p class="description">How do you prefer Lola to talk to you?</p>

            <div class="lc-radio-grid">
                <label class="lc-radio-card">
                    <input type="radio" name="technical_level" value="Technical" <?php checked($lolacore_tech_level, 'Technical'); ?>>
                    <div class="lc-radio-content">
                        <strong>Technical</strong>
                        <span>Development terminology, shows code, doesn't explain basics.</span>
                    </div>
                </label>
                <label class="lc-radio-card">
                    <input type="radio" name="technical_level" value="Professional" <?php checked($lolacore_tech_level, 'Professional'); ?>>
                    <div class="lc-radio-content">
                        <strong>Professional</strong>
                        <span>Clear language, explains technical decisions without jargon.</span>
                    </div>
                </label>
                <label class="lc-radio-card">
                    <input type="radio" name="technical_level" value="Direct" <?php checked($lolacore_tech_level, 'Direct'); ?>>
                    <div class="lc-radio-content">
                        <strong>Direct</strong>
                        <span>Minimal explanations, maximum action.</span>
                    </div>
                </label>
            </div>
        </div>

        <!-- Section 3: Lola's Avatar -->
        <div class="lc-card">
            <div class="lc-card-header">
                <span class="lc-section-number">3</span>
                <h3>Lola's Avatar</h3>
            </div>
            
            <div class="lc-avatar-group">
                <img src="<?php echo esc_url($lolacore_avatar_url); ?>" id="current-lola-avatar" class="lc-avatar-preview" alt="Lola Avatar">
                <div>
                    <div style="display:flex; gap:8px; margin-bottom:8px;">
                        <button type="button" id="btn-change-avatar" class="lc-action-btn ghost">Change Avatar</button>
                        <button type="button" id="btn-restore-avatar" class="lc-action-btn ghost">Restore Default</button>
                        <input type="hidden" id="lola_avatar_attachment_id" name="lola_avatar_attachment_id" value="<?php echo esc_attr($lolacore_avatar_attachment_id); ?>">
                    </div>
                    <p class="description">Formats: JPG, PNG, WebP. Recommended: 128&times;128px.</p>
                </div>
            </div>
        </div>

        <!-- Section 4: Memory Settings -->
        <div class="lc-card">
            <div class="lc-card-header">
                <span class="lc-section-number">4</span>
                <h3>Memory Settings</h3>
            </div>
            <p class="description">Configure how Lola stores and forgets information about your site.</p>

            <table class="lc-form-table">
                <tr>
                    <th scope="row"><label for="memory_decay_rate">Decay Rate</label></th>
                    <td>
                        <input type="number" id="memory_decay_rate" name="memory_decay_rate" class="lc-input"
                               value="<?php echo esc_attr($lolacore_decay_rate); ?>"
                               step="0.01" min="0" max="0.10">
                        <p class="description">How fast old facts are forgotten. Default 0.02.</p>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="memory_archive_threshold">Archive Threshold</label></th>
                    <td>
                        <input type="number" id="memory_archive_threshold" name="memory_archive_threshold" class="lc-input"
                               value="<?php echo esc_attr($lolacore_archive_threshold); ?>"
                               step="0.05" min="0" max="0.50">
                        <p class="description">Score below which a fact is archived. Default 0.10.</p>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="memory_max_context_entries">Max Context Entries</label></th>
                    <td>
                        <input type="number" id="memory_max_context_entries" name="memory_max_context_entries" class="lc-input"
                               value="<?php echo esc_attr($lolacore_max_context_entries); ?>"
                               step="5" min="5" max="50">
                        <p class="description">Maximum memory facts injected into the system prompt. Default 20.</p>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="log_retention_days">Log Retention Days</label></th>
                    <td>
                        <input type="number" id="log_retention_days" name="log_retention_days" class="lc-input"
                               value="<?php echo esc_attr($lolacore_log_retention_days); ?>"
                               step="1" min="30" max="365">
                        <p class="description">How long to keep action logs. Default 90.</p>
                    </td>
                </tr>
            </table>

            <div style="margin-top: 16px;">
                <button type="button" id="btn-restore-memory-defaults" class="lc-action-btn ghost">Restore Memory Defaults</button>
            </div>

            <div class="lc-status-bar lc-status-bar--<?php echo esc_attr($lolacore_maintenance_color); ?>">
                <span class="lc-status-dot lc-status-dot--<?php echo esc_attr($lolacore_maintenance_color); ?>"></span>
                <span class="lc-status-text" id="memory-status-text"><?php echo esc_html($lolacore_active_facts); ?> facts in memory. Last maintenance: <?php echo esc_html($lolacore_maintenance_text); ?>.</span>
            </div>
        </div>

        <!-- Section 5: What Lola Can Do -->
        <?php
        $lolacore_settings_inst = new \LolaCore\Admin\Settings();
        $lolacore_domain_summary = $lolacore_settings_inst->getAbilityDomainSummary();
        $lolacore_total_abilities = 0;
        foreach ($lolacore_domain_summary as $lolacore_dom) { $lolacore_total_abilities += $lolacore_dom['count']; }
        $lolacore_total_domains = count($lolacore_domain_summary);
        ?>
        <div class="lc-card">
            <div class="lc-card-header">
                <span class="lc-section-number">5</span>
                <h3>What Lola Can Do</h3>
            </div>
            <p class="description"><?php echo esc_html($lolacore_total_abilities); ?> abilities across <?php echo esc_html($lolacore_total_domains); ?> domains. Enable or disable categories based on your needs.</p>

            <div class="lc-grid-2">
                <?php foreach ($lolacore_domain_summary as $lolacore_slug => $lolacore_data): ?>
                <?php
                $lolacore_is_locked = !empty($lolacore_data['is_premium']) && empty($lolacore_data['license_active']);
                ?>
                <div class="lc-toggle-wrapper"<?php echo $lolacore_is_locked ? ' style="opacity: 0.6;"' : ''; ?>>
                    <div class="lc-toggle-label">
                        <strong><?php echo esc_html($lolacore_data['label']); ?></strong>
                        <span><?php echo esc_html($lolacore_data['count']); ?> abilities</span>
                        <?php if (!empty($lolacore_data['is_premium']) || !empty($lolacore_data['badge'])): ?>
                            <div style="margin-top: 4px;">
                                <?php if (!empty($lolacore_data['badge'])): ?>
                                    <span class="lc-pill amber" style="font-size: 10px; padding: 2px 6px;"><?php echo esc_html(mb_strtoupper($lolacore_data['badge'])); ?></span>
                                <?php elseif ($lolacore_is_locked): ?>
                                    <span class="lc-pill" style="font-size: 10px; padding: 2px 6px; background: var(--lc-plum-wash); color: var(--lc-plum);">LICENSE REQUIRED</span>
                                <?php else: ?>
                                    <span class="lc-pill amber" style="font-size: 10px; padding: 2px 6px;">PREMIUM ADDON</span>
                                <?php endif; ?>
                            </div>
                            <?php if (!empty($lolacore_data['is_premium']) && !empty($lolacore_data['license_url'])): ?>
                                <a href="<?php echo esc_url($lolacore_data['license_url']); ?>" style="display: inline-block; font-size: 11px; margin-top: 4px; color: var(--lc-plum); text-decoration: none;">
                                    <?php echo $lolacore_is_locked ? 'Activate license to unlock &rarr;' : 'Manage license &rarr;'; ?>
                                </a>
                            <?php elseif (!empty($lolacore_data['settings_url'])): ?>
                                <a href="<?php echo esc_url($lolacore_data['settings_url']); ?>" style="display: inline-block; font-size: 11px; margin-top: 4px; color: var(--lc-plum); text-decoration: none;">
                                    Configure &rarr;
                                </a>
                            <?php endif; ?>
                        <?php endif; ?>
                    </div>
                    <label class="lc-toggle">
                        <input type="checkbox" class="lc-domain-toggle" data-domain="<?php echo esc_attr($lolacore_slug); ?>" <?php checked($lolacore_data['enabled']); ?> <?php echo $lolacore_is_locked ? 'disabled' : ''; ?>>
                        <span class="lc-toggle-slider"></span>
                    </label>
                </div>
                <?php endforeach; ?>
            </div>

            <div style="margin-top: 16px; font-size: 13px;">
                <a href="#" id="lc-toggle-abilities-list" style="text-decoration: none; color: var(--lc-plum); font-weight: 500;">View all <?php echo esc_html($lolacore_total_abilities); ?> abilities &darr;</a>
                <div id="lc-abilities-list" style="display: none; margin-top: 12px; padding: 16px; background: #fff; border: 1px solid var(--lc-border); border-radius: 8px; max-height: 300px; overflow-y: auto;">
                    <?php
                    $lolacore_ab_registry = new \LolaCore\Actions\AbilitiesRegistry();
                    $lolacore_all_abilities = $lolacore_ab_registry->getRegisteredAbilities();
                    foreach ($lolacore_domain_summary as $lolacore_slug => $lolacore_data):
                        $lolacore_domain_abilities = [];
                        if (!empty($lolacore_data['is_premium'])) {
                            foreach ($lolacore_all_abilities as $lolacore_ability_name => $lolacore_ability) {
                                if (($lolacore_ability['category'] ?? '') === $lolacore_data['category']) {
                                    $lolacore_domain_abilities[] = $lolacore_ability_name;
                                }
                            }
                        } else {
                            $lolacore_categories = \LolaCore\Admin\Settings::DOMAIN_MAP[$lolacore_slug] ?? [];
                            foreach ($lolacore_all_abilities as $lolacore_ability_name => $lolacore_ability) {
                                if (in_array($lolacore_ability['category'] ?? 'uncategorized', $lolacore_categories, true)) {
                                    $lolacore_domain_abilities[] = $lolacore_ability_name;
                                }
                            }
                        }
                        if (!empty($lolacore_domain_abilities)):
                    ?>
                        <div style="margin-bottom: 12px;">
                            <strong style="color: var(--lc-text-primary);"><?php echo esc_html($lolacore_data['label']); ?></strong>
                            <ul style="margin: 4px 0 0 16px; color: var(--lc-text-secondary); list-style-type: disc; font-size: 12px; font-family: var(--lc-font-mono);">
                                <?php foreach ($lolacore_domain_abilities as $lolacore_ab): ?>
                                    <li><?php echo esc_html($lolacore_ab); ?></li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                    <?php endif; endforeach; ?>
                </div>
            </div>
        </div>

        <!-- Section 6: Safety & Confirmations -->
        <div class="lc-card">
            <div class="lc-card-header">
                <span class="lc-section-number">6</span>
                <h3>Safety &amp; Confirmations</h3>
            </div>
            <p class="description">Configure when Lola requires your explicit approval to act.</p>

            <div class="lc-toggle-wrapper">
                <div class="lc-toggle-label">
                    <strong>Confirm before every write action</strong>
                    <span>Recommended. If disabled, Lola will execute actions without asking.<br><span style="color: var(--lc-salmon); font-style: italic;">Disclaimer: Lola is an AI and can make mistakes.</span></span>
                </div>
                <label class="lc-toggle">
                    <input type="checkbox" class="lc-safety-toggle" id="safety_confirm_writes" <?php checked($lolacore_safety_confirm_writes); ?>>
                    <span class="lc-toggle-slider"></span>
                </label>
            </div>
            <div class="lc-toggle-wrapper">
                <div class="lc-toggle-label">
                    <strong>Block destructive actions without verified backup</strong>
                    <span>Lola checks for a recent backup before deleting content.</span>
                </div>
                <label class="lc-toggle">
                    <input type="checkbox" class="lc-safety-toggle" id="safety_require_backup" <?php checked($lolacore_safety_require_backup); ?>>
                    <span class="lc-toggle-slider"></span>
                </label>
            </div>
            <div class="lc-toggle-wrapper">
                <div class="lc-toggle-label">
                    <strong>Learning mode</strong>
                    <span>Lola explains what she's about to do before showing the preview, so you understand each action.</span>
                </div>
                <label class="lc-toggle">
                    <input type="checkbox" class="lc-safety-toggle" id="safety_learning_mode" <?php checked($lolacore_safety_learning_mode); ?>>
                    <span class="lc-toggle-slider"></span>
                </label>
            </div>

            <div style="margin-top: 16px;">
                <button type="button" id="btn-save-safety" class="lc-action-btn primary">Save Safety Settings</button>
                <span class="spinner" id="safety-spinner" style="float:none; vertical-align:middle;"></span>
            </div>
        </div>

        <!-- Section 7: Maintenance -->
        <div class="lc-card">
            <div class="lc-card-header">
                <span class="lc-section-number">7</span>
                <h3>Maintenance</h3>
            </div>
            <p class="description">Manual controls for database and memory health.</p>

            <div style="display:flex; flex-wrap:wrap; gap:12px;">
                <button type="button" id="btn-maint-rescan" class="lc-action-btn ghost">Re-scan site</button>
                <button type="button" id="btn-maint-export" class="lc-action-btn ghost">Export memory</button>
                <button type="button" id="btn-maint-import" class="lc-action-btn ghost">Import memory</button>
                <button type="button" id="btn-maint-compact" class="lc-action-btn ghost">Compact memory</button>
                <button type="button" id="btn-maint-wipe" class="lc-action-btn danger">Wipe all memory</button>
            </div>

            <?php if (!empty($lolacore_last_maintenance_at)) : ?>
                <div class="lc-status-bar" style="margin-top: 16px;">
                    <span class="lc-pill mint">OK</span>
                    <span class="lc-status-text">Last maintenance: <?php echo esc_html($lolacore_maintenance_text); ?></span>
                </div>
            <?php endif; ?>
        </div>

        <!-- Section 8: Skills -->
        <div class="lc-card">
            <div class="lc-card-header">
                <span class="lc-section-number">8</span>
                <h3>Skills</h3>
            </div>
            <p class="description">Behavioral overlays loaded into Lola's system prompt. Skills shape how Lola responds based on context.</p>

            <?php
            $lolacore_settings_skills = new \LolaCore\Admin\Settings();
            $lolacore_settings_skills->renderSkillsSection();
            ?>
        </div>

        <div class="lc-sticky-footer" id="lc-sticky-footer" style="display: none;">
            <span class="lc-dirty-label" id="lc-dirty-label"></span>
            <span class="spinner" id="save-spinner"></span>
            <button type="button" class="lc-action-btn ghost" id="btn-discard-settings">Discard</button>
            <button type="submit" class="lc-action-btn primary" id="btn-save-settings">Save Changes</button>
        </div>

    </form>

    <!-- Wipe Memory Modal -->
    <div id="lc-wipe-modal" class="lc-modal-overlay" style="display: none;">
        <div class="lc-modal-card">
            <div class="lc-modal-header">
                <h3>⚠️ Wipe All Memory</h3>
            </div>
            <div class="lc-modal-body">
                <p>Are you sure you want to wipe ALL of Lola's memory? This cannot be undone.</p>
                <p style="margin-top: 16px; font-weight: 600;">Type WIPE to confirm:</p>
                <input type="text" id="lc-wipe-token" class="lc-input" autocomplete="off" placeholder="WIPE">
            </div>
            <div class="lc-modal-footer">
                <button type="button" class="lc-action-btn ghost" id="btn-wipe-cancel">Cancel</button>
                <button type="button" class="lc-action-btn danger" id="btn-wipe-confirm">Wipe Memory</button>
            </div>
        </div>
    </div>

    <!-- Generic Confirmation Modal -->
    <div id="lc-confirm-modal" class="lc-modal-overlay" style="display: none;">
        <div class="lc-modal-card">
            <div class="lc-modal-header" style="background: var(--lc-paper); border-bottom-color: var(--lc-border);">
                <h3 id="lc-confirm-title" style="color: var(--lc-text-primary);">Confirm Action</h3>
            </div>
            <div class="lc-modal-body">
                <p id="lc-confirm-message">Are you sure?</p>
            </div>
            <div class="lc-modal-footer">
                <button type="button" class="lc-action-btn ghost" id="btn-confirm-cancel">Cancel</button>
                <button type="button" class="lc-action-btn primary" id="btn-confirm-ok">Confirm</button>
            </div>
        </div>
    </div>

    <!-- Hidden File Input for Memory Import (Outside the Form to avoid F5 caching) -->
    <input type="file" id="maint-import-file" accept="application/json,.json" style="display:none;" autocomplete="off">

</div>
