<?php
/**
 * Admin dashboard page.
 *
 * @package Inqyra
 */

// If this file is called directly, abort.
if (!defined('WPINC')) {
    die;
}
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template variables from parent scope.

global $wpdb;

// Get statistics
$agent = (new Inqyra_Admin('inqyra', INQYRA_VERSION))->get_current_agent();
$agent_id = $agent ? $agent->id : 0;

// Get conversation stats
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table query.
$today_conversations = $wpdb->get_var($wpdb->prepare(
    'SELECT COUNT(*) FROM %i
     WHERE agent_id = %d AND DATE(started_at) = CURDATE()',
    $wpdb->prefix . 'inqyra_conversations',
    $agent_id
));

// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table query.
$total_conversations = $wpdb->get_var($wpdb->prepare(
    'SELECT COUNT(*) FROM %i WHERE agent_id = %d',
    $wpdb->prefix . 'inqyra_conversations',
    $agent_id
));

// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table query.
$total_messages = $wpdb->get_var($wpdb->prepare(
    'SELECT COUNT(*) FROM %i m
     JOIN %i c ON c.id = m.conversation_id
     WHERE c.agent_id = %d',
    $wpdb->prefix . 'inqyra_messages',
    $wpdb->prefix . 'inqyra_conversations',
    $agent_id
));

// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table query.
$total_chunks = $wpdb->get_var($wpdb->prepare(
    'SELECT COUNT(*) FROM %i WHERE agent_id = %d',
    $wpdb->prefix . 'inqyra_knowledge_chunks',
    $agent_id
));

// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table query.
$pending_embeddings = $wpdb->get_var($wpdb->prepare(
    'SELECT COUNT(*) FROM %i
     WHERE agent_id = %d AND needs_embedding = 1',
    $wpdb->prefix . 'inqyra_knowledge_chunks',
    $agent_id
));


// Get daily usage stats for health monitoring
$daily_token_usage = 0;
$daily_cost_usage = 0.0;
if ($agent_id) {
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table query.
    $daily_token_usage = (int) $wpdb->get_var($wpdb->prepare(
        'SELECT COALESCE(SUM(m.tokens_used), 0) FROM %i m
         JOIN %i c ON c.id = m.conversation_id
         WHERE c.agent_id = %d AND m.created_at > DATE_SUB(NOW(), INTERVAL 1 DAY)',
        $wpdb->prefix . 'inqyra_messages',
        $wpdb->prefix . 'inqyra_conversations',
        $agent_id
    ));
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table query.
    $daily_cost_usage = (float) $wpdb->get_var($wpdb->prepare(
        'SELECT COALESCE(SUM(m.cost_usd), 0) FROM %i m
         JOIN %i c ON c.id = m.conversation_id
         WHERE c.agent_id = %d AND m.created_at > DATE_SUB(NOW(), INTERVAL 1 DAY)',
        $wpdb->prefix . 'inqyra_messages',
        $wpdb->prefix . 'inqyra_conversations',
        $agent_id
    ));
}

// Check provider API key status
$provider_key_configured = false;
if ($agent) {
    $provider_key = Inqyra_AI_Provider_Factory::get_api_key($agent->provider ?? 'claude');
    $provider_key_configured = !empty($provider_key);
}

// Calculate limit percentages
$token_limit = $agent ? (int) ($agent->daily_token_limit ?? 0) : 0;
$cost_limit = $agent ? (float) ($agent->cost_limit_usd ?? 0) : 0;
$token_pct = ($token_limit > 0) ? round(($daily_token_usage / $token_limit) * 100) : 0;
$cost_pct = ($cost_limit > 0) ? round(($daily_cost_usage / $cost_limit) * 100) : 0;

// Get recent conversations
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table query.
$recent_conversations = $wpdb->get_results($wpdb->prepare(
    'SELECT c.*, COUNT(m.id) as message_count
     FROM %i c
     LEFT JOIN %i m ON m.conversation_id = c.id
     WHERE c.agent_id = %d
     GROUP BY c.id
     ORDER BY c.started_at DESC
     LIMIT 5',
    $wpdb->prefix . 'inqyra_conversations',
    $wpdb->prefix . 'inqyra_messages',
    $agent_id
));

?>
<div class="wrap inqyra-admin">
    <h1><?php esc_html_e('Inqyra Dashboard', 'inqyra'); ?></h1>

    <?php if (get_option('inqyra_upgrade_recrawl_needed')): ?>
        <div class="notice notice-info is-dismissible inqyra-upgrade-recrawl-notice" style="margin: 15px 0;">
            <p>
                <strong><?php esc_html_e('Premium activated!', 'inqyra'); ?></strong>
                <?php esc_html_e('Your content was previously crawled with the free version (pages only). Recrawl and re-embed your content to index posts, products, and custom post types.', 'inqyra'); ?>
            </p>
            <p>
                <a href="<?php echo esc_url(admin_url('admin.php?page=inqyra-knowledge')); ?>" class="button button-primary">
                    <?php esc_html_e('Go to Knowledge Base', 'inqyra'); ?>
                </a>
                <button type="button" class="button inqyra-dismiss-recrawl-notice" style="margin-left: 8px;">
                    <?php esc_html_e('Dismiss', 'inqyra'); ?>
                </button>
            </p>
        </div>
    <?php endif; ?>

    <?php if (!$agent): ?>
        <div class="notice notice-warning">
            <p><?php esc_html_e('No agent configured. Please create an agent first.', 'inqyra'); ?></p>
            <p><a href="<?php echo esc_url(admin_url('admin.php?page=inqyra-config')); ?>" class="button button-primary"><?php esc_html_e('Create Agent', 'inqyra'); ?></a></p>
        </div>
    <?php else: ?>

    <!-- Statistics Cards -->
    <div class="inqyra-stats-grid">
        <div class="inqyra-stat-card">
            <div class="inqyra-stat-icon dashicons dashicons-format-chat"></div>
            <div class="inqyra-stat-content">
                <div class="inqyra-stat-value"><?php echo esc_html($today_conversations); ?></div>
                <div class="inqyra-stat-label"><?php esc_html_e('Conversations Today', 'inqyra'); ?></div>
            </div>
        </div>

        <div class="inqyra-stat-card">
            <div class="inqyra-stat-icon dashicons dashicons-admin-comments"></div>
            <div class="inqyra-stat-content">
                <div class="inqyra-stat-value"><?php echo esc_html($total_conversations); ?></div>
                <div class="inqyra-stat-label"><?php esc_html_e('Total Conversations', 'inqyra'); ?></div>
            </div>
        </div>

        <div class="inqyra-stat-card">
            <div class="inqyra-stat-icon dashicons dashicons-text-page"></div>
            <div class="inqyra-stat-content">
                <div class="inqyra-stat-value"><?php echo esc_html($total_messages); ?></div>
                <div class="inqyra-stat-label"><?php esc_html_e('Total Messages', 'inqyra'); ?></div>
            </div>
        </div>

        <div class="inqyra-stat-card">
            <div class="inqyra-stat-icon dashicons dashicons-database"></div>
            <div class="inqyra-stat-content">
                <div class="inqyra-stat-value"><?php echo esc_html($total_chunks); ?></div>
                <div class="inqyra-stat-label"><?php esc_html_e('Knowledge Chunks', 'inqyra'); ?></div>
            </div>
        </div>
    </div>

    <!-- Status Overview -->
    <div class="inqyra-dashboard-grid">
        <!-- Plan Status -->
        <div class="inqyra-card">
            <h2><?php esc_html_e('Plan', 'inqyra'); ?></h2>
            <?php if ( inqyra_fs()->is__premium_only() && inqyra_fs()->is_paying() ): ?>
                <div class="inqyra-license-status inqyra-status-success">
                    <span class="inqyra-status-badge"><?php esc_html_e('Premium', 'inqyra'); ?></span>
                    <p><?php esc_html_e('All premium features are active.', 'inqyra'); ?></p>
                </div>
                <p><a href="<?php echo esc_url(admin_url('admin.php?page=inqyra-account')); ?>"><?php esc_html_e('Manage Account', 'inqyra'); ?></a></p>
            <?php elseif (inqyra_fs()->is_registered()): ?>
                <div class="inqyra-license-status inqyra-status-warning">
                    <span class="inqyra-status-badge"><?php esc_html_e('Free', 'inqyra'); ?></span>
                    <p><?php esc_html_e('Upgrade to unlock all features.', 'inqyra'); ?></p>
                </div>
                <p>
                    <a href="<?php echo esc_url(inqyra_fs()->get_upgrade_url()); ?>"><?php esc_html_e('Upgrade', 'inqyra'); ?></a>
                    &nbsp;|&nbsp;
                    <a href="<?php echo esc_url(admin_url('admin.php?page=inqyra-account')); ?>"><?php esc_html_e('Manage Account', 'inqyra'); ?></a>
                </p>
            <?php else: ?>
                <div class="inqyra-license-status inqyra-status-warning">
                    <span class="inqyra-status-badge"><?php esc_html_e('Free', 'inqyra'); ?></span>
                    <p><?php esc_html_e('Connect your account to activate a license or upgrade.', 'inqyra'); ?></p>
                </div>
                <p><a href="<?php echo esc_url(inqyra_fs()->get_reconnect_url()); ?>" class="button button-primary"><?php esc_html_e('Connect Account', 'inqyra'); ?></a></p>
            <?php endif; ?>
        </div>

        <!-- Agent Status -->
        <div class="inqyra-card">
            <h2><?php esc_html_e('Active Agent', 'inqyra'); ?></h2>
            <table class="inqyra-info-table">
                <tr>
                    <th><?php esc_html_e('Name', 'inqyra'); ?></th>
                    <td><?php echo esc_html($agent->name); ?></td>
                </tr>
                <tr>
                    <th><?php esc_html_e('Provider', 'inqyra'); ?></th>
                    <td><?php echo esc_html(ucfirst($agent->provider)); ?></td>
                </tr>
                <tr>
                    <th><?php esc_html_e('Model', 'inqyra'); ?></th>
                    <td><?php echo esc_html($agent->model ?: __('Not set', 'inqyra')); ?></td>
                </tr>
                <tr>
                    <th><?php esc_html_e('Status', 'inqyra'); ?></th>
                    <td>
                        <?php if ($agent->active): ?>
                            <span class="inqyra-status-badge inqyra-status-success"><?php esc_html_e('Active', 'inqyra'); ?></span>
                        <?php else: ?>
                            <span class="inqyra-status-badge inqyra-status-warning"><?php esc_html_e('Inactive', 'inqyra'); ?></span>
                        <?php endif; ?>
                    </td>
                </tr>
            </table>
            <p><a href="<?php echo esc_url(admin_url('admin.php?page=inqyra-config&agent_id=' . $agent->id)); ?>"><?php esc_html_e('Edit Agent', 'inqyra'); ?></a></p>
        </div>

        <!-- Knowledge Base Status -->
        <div class="inqyra-card">
            <h2><?php esc_html_e('Knowledge Base', 'inqyra'); ?></h2>
            <table class="inqyra-info-table">
                <tr>
                    <th><?php esc_html_e('Total Chunks', 'inqyra'); ?></th>
                    <td><?php echo esc_html($total_chunks); ?></td>
                </tr>
                <tr>
                    <th><?php esc_html_e('Pending Embeddings', 'inqyra'); ?></th>
                    <td>
                        <?php if ($pending_embeddings > 0): ?>
                            <span class="inqyra-status-badge inqyra-status-warning"><?php echo esc_html($pending_embeddings); ?></span>
                        <?php else: ?>
                            <span class="inqyra-status-badge inqyra-status-success">0</span>
                        <?php endif; ?>
                    </td>
                </tr>
            </table>
            <?php if ($pending_embeddings > 0): ?>
                <div class="inqyra-notice inqyra-notice-warning" style="margin-top: 12px; padding: 10px 14px; background: #fff3cd; border-left: 4px solid #ffc107; border-radius: 4px;">
                    <strong><?php esc_html_e('Action needed:', 'inqyra'); ?></strong>
                    <?php
                    printf(
                        /* translators: %d: number of chunks that still need embeddings */
                        esc_html__('%d chunks need embeddings for semantic search to work. Process them from the Knowledge Base page.', 'inqyra'),
                        intval($pending_embeddings)
                    ); ?>
                    <br>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=inqyra-knowledge')); ?>" class="button button-small" style="margin-top: 6px;">
                        <?php esc_html_e('Process Embeddings', 'inqyra'); ?>
                    </a>
                </div>
            <?php endif; ?>
            <p>
                <a href="<?php echo esc_url(admin_url('admin.php?page=inqyra-knowledge')); ?>"><?php esc_html_e('Manage Knowledge Base', 'inqyra'); ?></a>
            </p>
        </div>

        <!-- System Health -->
        <div class="inqyra-card">
            <h2><?php esc_html_e('System Health', 'inqyra'); ?></h2>
            <table class="inqyra-info-table">
                <tr>
                    <th><?php esc_html_e('API Key', 'inqyra'); ?></th>
                    <td>
                        <?php if ($provider_key_configured): ?>
                            <span class="inqyra-status-badge inqyra-status-success"><?php echo esc_html(ucfirst($agent->provider)); ?> — <?php esc_html_e('configured', 'inqyra'); ?></span>
                        <?php else: ?>
                            <span class="inqyra-status-badge inqyra-status-error"><?php esc_html_e('Not configured', 'inqyra'); ?></span>
                            <br><small><a href="<?php echo esc_url(admin_url('admin.php?page=inqyra-settings')); ?>"><?php esc_html_e('Configure API Key', 'inqyra'); ?></a></small>
                        <?php endif; ?>
                    </td>
                </tr>
                <tr>
                    <th><?php esc_html_e('Daily Tokens', 'inqyra'); ?></th>
                    <td>
                        <?php if ($token_limit > 0): ?>
                            <?php echo esc_html(number_format($daily_token_usage)); ?> / <?php echo esc_html(number_format($token_limit)); ?>
                            <?php if ($token_pct >= 100): ?>
                                <span class="inqyra-status-badge inqyra-status-error"><?php esc_html_e('Limit reached', 'inqyra'); ?></span>
                            <?php elseif ($token_pct >= 80): ?>
                                <span class="inqyra-status-badge inqyra-status-warning"><?php echo esc_html($token_pct); ?>%</span>
                            <?php else: ?>
                                <span class="inqyra-status-badge inqyra-status-success"><?php echo esc_html($token_pct); ?>%</span>
                            <?php endif; ?>
                        <?php else: ?>
                            <?php echo esc_html(number_format($daily_token_usage)); ?> — <em><?php esc_html_e('unlimited', 'inqyra'); ?></em>
                        <?php endif; ?>
                    </td>
                </tr>
                <tr>
                    <th><?php esc_html_e('Daily Cost', 'inqyra'); ?></th>
                    <td>
                        <?php if ($cost_limit > 0): ?>
                            $<?php echo esc_html(number_format($daily_cost_usage, 4)); ?> / $<?php echo esc_html(number_format($cost_limit, 2)); ?>
                            <?php if ($cost_pct >= 100): ?>
                                <span class="inqyra-status-badge inqyra-status-error"><?php esc_html_e('Limit reached', 'inqyra'); ?></span>
                            <?php elseif ($cost_pct >= 80): ?>
                                <span class="inqyra-status-badge inqyra-status-warning"><?php echo esc_html($cost_pct); ?>%</span>
                            <?php else: ?>
                                <span class="inqyra-status-badge inqyra-status-success"><?php echo esc_html($cost_pct); ?>%</span>
                            <?php endif; ?>
                        <?php else: ?>
                            $<?php echo esc_html(number_format($daily_cost_usage, 4)); ?> — <em><?php esc_html_e('unlimited', 'inqyra'); ?></em>
                        <?php endif; ?>
                    </td>
                </tr>
                <tr>
                    <th><?php esc_html_e('Widget', 'inqyra'); ?></th>
                    <td>
                        <?php
                        $widget_hidden_reason = '';
                        if (!$provider_key_configured) {
                            $widget_hidden_reason = __('No API key for provider', 'inqyra');
                        } elseif ($token_pct >= 100) {
                            $widget_hidden_reason = __('Daily token limit reached', 'inqyra');
                        } elseif ($cost_pct >= 100) {
                            $widget_hidden_reason = __('Daily cost limit reached', 'inqyra');
                        }

                        if ($widget_hidden_reason): ?>
                            <span class="inqyra-status-badge inqyra-status-error"><?php esc_html_e('Hidden', 'inqyra'); ?></span>
                            <br><small><?php echo esc_html($widget_hidden_reason); ?></small>
                        <?php else: ?>
                            <span class="inqyra-status-badge inqyra-status-success"><?php esc_html_e('Active', 'inqyra'); ?></span>
                        <?php endif; ?>
                    </td>
                </tr>
            </table>
            <?php if ($token_pct >= 80 && $token_pct < 100): ?>
                <div class="inqyra-notice inqyra-notice-warning" style="margin-top: 12px; padding: 10px 14px; background: #fff3cd; border-left: 4px solid #ffc107; border-radius: 4px;">
                    <strong><?php esc_html_e('Warning:', 'inqyra'); ?></strong>
                    <?php esc_html_e('Daily token usage is approaching the limit. The widget will be hidden when the limit is reached.', 'inqyra'); ?>
                </div>
            <?php endif; ?>
            <?php if ($cost_pct >= 80 && $cost_pct < 100): ?>
                <div class="inqyra-notice inqyra-notice-warning" style="margin-top: 12px; padding: 10px 14px; background: #fff3cd; border-left: 4px solid #ffc107; border-radius: 4px;">
                    <strong><?php esc_html_e('Warning:', 'inqyra'); ?></strong>
                    <?php esc_html_e('Daily cost is approaching the limit. The widget will be hidden when the limit is reached.', 'inqyra'); ?>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Recent Conversations -->
    <div class="inqyra-card inqyra-card-full">
        <h2><?php esc_html_e('Recent Conversations', 'inqyra'); ?></h2>
        <?php if (empty($recent_conversations)): ?>
            <p class="inqyra-empty-state"><?php esc_html_e('No conversations yet.', 'inqyra'); ?></p>
        <?php else: ?>
            <table class="wp-list-table widefat fixed striped">
                <thead>
                    <tr>
                        <th><?php esc_html_e('Session', 'inqyra'); ?></th>
                        <th><?php esc_html_e('Started', 'inqyra'); ?></th>
                        <th><?php esc_html_e('Messages', 'inqyra'); ?></th>
                        <th><?php esc_html_e('Tokens', 'inqyra'); ?></th>
                        <th><?php esc_html_e('Cost', 'inqyra'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($recent_conversations as $conversation): ?>
                        <tr>
                            <td>
                                <a href="<?php echo esc_url(admin_url('admin.php?page=inqyra-conversations&conversation_id=' . $conversation->id)); ?>">
                                    <?php echo esc_html(substr($conversation->session_id, 0, 12) . '...'); ?>
                                </a>
                            </td>
                            <td><?php echo esc_html(date_i18n(get_option('date_format') . ' ' . get_option('time_format'), strtotime($conversation->started_at))); ?></td>
                            <td><?php echo esc_html($conversation->message_count); ?></td>
                            <td><?php echo esc_html(number_format($conversation->total_tokens)); ?></td>
                            <td>$<?php echo esc_html(number_format($conversation->total_cost_usd, 4)); ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <p><a href="<?php echo esc_url(admin_url('admin.php?page=inqyra-conversations')); ?>"><?php esc_html_e('View All Conversations', 'inqyra'); ?></a></p>
        <?php endif; ?>
    </div>

    <?php endif; ?>
</div>

<?php // phpcs:enable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound ?>
