<?php
/**
 * Admin API Statistics Template
 *
 * This template displays API performance statistics with charts and graphs.
 *
 * @package Askany
 * @since 1.0.0
 */

// Prevent direct access
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}
?>


<?php
// ── Rate Limiting Section ────────────────────────────────────────────────────
$plugin_instance = \Askany\Plugin::get_instance();
$is_pro          = $plugin_instance->is_pro_active();
$rl_enabled      = \Askany\RateLimiter::is_enabled();
$rl_roles        = \Askany\RateLimiter::get_role_settings();
$fallback_active = (bool) get_option( 'askany_fallback_enabled', false );

$role_labels = array(
    'administrator' => __( 'Administrator', 'askany' ),
    'editor'        => __( 'Editor', 'askany' ),
    'author'        => __( 'Author', 'askany' ),
    'contributor'   => __( 'Contributor', 'askany' ),
    'subscriber'    => __( 'Subscriber', 'askany' ),
    'customer'      => __( 'Customer', 'askany' ),
    'shop_manager'  => __( 'Shop Manager', 'askany' ),
    'visitor'       => __( 'Visitors / Logged-Out Users (tracked by IP)', 'askany' ),
);

$limit_options = array( 1, 3, 5, 10, 15, 20, 50, 100, 0 );
$timeframe_labels = array(
    'per_hour'  => __( 'Per Hour', 'askany' ),
    'per_day'   => __( 'Per Day', 'askany' ),
    'per_week'  => __( 'Per Week', 'askany' ),
    'per_month' => __( 'Per Month', 'askany' ),
);
?>

<div class="wrap askany-admin-page askany-admin-section <?php echo ! $is_pro ? 'askany-pro-locked' : ''; ?>" style="margin-top: 30px; position: relative;">
    <h1 style="margin-top: 0; display: flex; align-items: center; gap: 10px;">
        <?php _e( 'Token / Rate Limiting', 'askany' ); ?>
        <?php if ( ! $is_pro ) : ?>
            <span class="askany-pro-badge"><?php esc_html_e( 'PRO', 'askany' ); ?></span>
        <?php endif; ?>
    </h1>
    <p class="description"><?php _e( 'Limit how many chat requests each user role can make within a given timeframe.', 'askany' ); ?></p>

    <?php if ( $is_pro ) : ?>

    <!-- Master toggle -->
    <div style="margin-bottom: 20px;">
        <label style="display: flex; align-items: center; gap: 10px; font-weight: 600; cursor: pointer;">
            <input type="checkbox" id="askany-rate-limit-enabled" <?php checked( $rl_enabled ); ?> />
            <?php _e( 'Enable Token Limit', 'askany' ); ?>
        </label>
    </div>

    <!-- Per-role settings (shown when enabled) -->
    <div id="askany-rate-limit-settings" style="<?php echo $rl_enabled ? '' : 'display:none;'; ?>">

        <?php if ( ! $fallback_active ) : ?>
        <div id="askany-rl-fallback-notice" style="padding: 10px 14px; background: #fff3cd; border: 1px solid #f0b429; border-radius: 4px; margin-bottom: 16px;">
            ⚠️ <?php _e( 'Fallback mode is currently <strong>disabled</strong>. If you enable "Use Fallback" for any role below, please also enable Fallback Mode in the main Settings page.', 'askany' ); ?>
        </div>
        <?php endif; ?>

        <table class="wp-list-table widefat fixed striped" style="margin-bottom: 16px;">
            <thead>
                <tr>
                    <th style="width: 22%;"><?php _e( 'Role', 'askany' ); ?></th>
                    <th style="width: 14%;"><?php _e( 'Limit', 'askany' ); ?></th>
                    <th style="width: 14%;"><?php _e( 'Timeframe', 'askany' ); ?></th>
                    <th style="width: 30%;"><?php _e( 'Custom Message', 'askany' ); ?></th>
                    <th style="width: 20%;"><?php _e( 'Use Fallback Instead', 'askany' ); ?></th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ( $role_labels as $role_key => $role_label ) :
                $cfg = isset( $rl_roles[ $role_key ] ) ? $rl_roles[ $role_key ] : array();
                $cfg_limit    = isset( $cfg['limit'] )          ? intval( $cfg['limit'] )          : 100;
                $cfg_tf       = isset( $cfg['timeframe'] )      ? $cfg['timeframe']                : 'per_day';
                $cfg_msg      = isset( $cfg['custom_message'] ) ? $cfg['custom_message']           : __( 'Rate limit exceeded. Please try again later.', 'askany' );
                $cfg_fallback = ! empty( $cfg['use_fallback'] );
            ?>
            <tr>
                <td><strong><?php echo esc_html( $role_label ); ?></strong></td>
                <td>
                    <select class="rl-limit" data-role="<?php echo esc_attr( $role_key ); ?>" style="width:100%;">
                        <?php foreach ( $limit_options as $opt ) : ?>
                        <option value="<?php echo esc_attr( $opt ); ?>" <?php selected( $cfg_limit, $opt ); ?>>
                            <?php echo $opt === 0 ? esc_html__( 'Unlimited', 'askany' ) : esc_html( $opt ); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </td>
                <td>
                    <select class="rl-timeframe" data-role="<?php echo esc_attr( $role_key ); ?>" style="width:100%;">
                        <?php foreach ( $timeframe_labels as $tf_key => $tf_label ) : ?>
                        <option value="<?php echo esc_attr( $tf_key ); ?>" <?php selected( $cfg_tf, $tf_key ); ?>>
                            <?php echo esc_html( $tf_label ); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </td>
                <td>
                    <input type="text" class="rl-message regular-text" data-role="<?php echo esc_attr( $role_key ); ?>"
                           value="<?php echo esc_attr( $cfg_msg ); ?>" style="width:100%;" />
                </td>
                <td style="text-align:center;">
                    <label>
                        <input type="checkbox" class="rl-fallback" data-role="<?php echo esc_attr( $role_key ); ?>"
                               <?php checked( $cfg_fallback ); ?> />
                        <?php _e( 'Use Fallback', 'askany' ); ?>
                    </label>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>

        <button type="button" class="button button-primary" id="askany-save-rate-limit">
            <?php _e( 'Save Rate Limit Settings', 'askany' ); ?>
        </button>
        <span id="askany-rl-save-status" style="margin-left: 12px; display:none;"></span>
    </div><!-- /#askany-rate-limit-settings -->

    <?php else : ?>
    <!-- Pro locked preview (faded, non-interactive) -->
    <div style="pointer-events:none; opacity:0.45;">
        <div style="margin-bottom: 20px;">
            <label style="display: flex; align-items: center; gap: 10px; font-weight: 600;">
                <input type="checkbox" disabled />
                <?php _e( 'Enable Token Limit', 'askany' ); ?>
            </label>
        </div>
        <table class="wp-list-table widefat fixed striped" style="margin-bottom: 16px;">
            <thead>
                <tr>
                    <th><?php _e( 'Role', 'askany' ); ?></th>
                    <th><?php _e( 'Limit', 'askany' ); ?></th>
                    <th><?php _e( 'Timeframe', 'askany' ); ?></th>
                    <th><?php _e( 'Custom Message', 'askany' ); ?></th>
                    <th><?php _e( 'Use Fallback Instead', 'askany' ); ?></th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ( $role_labels as $role_key => $role_label ) : ?>
            <tr>
                <td><strong><?php echo esc_html( $role_label ); ?></strong></td>
                <td><select disabled style="width:100%;"><option>100</option></select></td>
                <td><select disabled style="width:100%;"><option><?php _e( 'Per Day', 'askany' ); ?></option></select></td>
                <td><input type="text" disabled value="<?php esc_attr_e( 'Rate limit exceeded. Please try again later.', 'askany' ); ?>" style="width:100%;" /></td>
                <td style="text-align:center;"><input type="checkbox" disabled /></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <!-- Pro overlay -->
    <div class="askany-pro-overlay">
        <div class="askany-pro-notice-small">
            <div class="askany-pro-notice-icon">
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>
                    <path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
                </svg>
            </div>
            <div class="askany-pro-notice-content">
                <h4><?php esc_html_e( 'Token / Rate Limiting is a Pro Feature', 'askany' ); ?></h4>
                <p><?php esc_html_e( 'Control how many chat requests each user role can make per hour, day, week, or month.', 'askany' ); ?></p>
                <button type="button" class="button button-primary askany-open-pro-modal">
                    <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="currentColor" style="margin-right: 6px;">
                        <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
                    </svg>
                    <?php esc_html_e( 'Upgrade to Pro', 'askany' ); ?>
                </button>
            </div>
        </div>
    </div>
    <?php endif; ?>

</div><!-- /.askany-admin-section -->

<script>
(function() {
    const toggle   = document.getElementById('askany-rate-limit-enabled');
    const settings = document.getElementById('askany-rate-limit-settings');
    const saveBtn  = document.getElementById('askany-save-rate-limit');
    const status   = document.getElementById('askany-rl-save-status');

    if ( toggle ) {
        toggle.addEventListener('change', function() {
            settings.style.display = this.checked ? '' : 'none';
        });
    }

    if ( saveBtn ) {
        saveBtn.addEventListener('click', function() {
            const enabled = toggle.checked ? 1 : 0;
            const roles   = {};

            document.querySelectorAll('.rl-limit').forEach(function(el) {
                const role = el.getAttribute('data-role');
                if ( ! roles[role] ) roles[role] = {};
                roles[role].limit = el.value;
            });
            document.querySelectorAll('.rl-timeframe').forEach(function(el) {
                const role = el.getAttribute('data-role');
                if ( ! roles[role] ) roles[role] = {};
                roles[role].timeframe = el.value;
            });
            document.querySelectorAll('.rl-message').forEach(function(el) {
                const role = el.getAttribute('data-role');
                if ( ! roles[role] ) roles[role] = {};
                roles[role].custom_message = el.value;
            });
            document.querySelectorAll('.rl-fallback').forEach(function(el) {
                const role = el.getAttribute('data-role');
                if ( ! roles[role] ) roles[role] = {};
                roles[role].use_fallback = el.checked ? 1 : 0;
            });

            saveBtn.disabled = true;
            saveBtn.textContent = '<?php esc_html_e( 'Saving…', 'askany' ); ?>';

            fetch(ajaxurl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({
                    action: 'askany_save_rate_limit_settings',
                    nonce:  '<?php echo esc_js( wp_create_nonce( 'askany_chat_nonce' ) ); ?>',
                    rate_limit_enabled: enabled,
                    rate_limit_roles:   JSON.stringify(roles),
                })
            })
            .then(r => r.json())
            .then(data => {
                status.style.display = 'inline';
                if ( data.success ) {
                    status.style.color = '#00a32a';
                    status.textContent = '✅ <?php esc_html_e( 'Saved!', 'askany' ); ?>';
                } else {
                    status.style.color = '#d63638';
                    status.textContent = '❌ ' + (data.data?.message || '<?php esc_html_e( 'Error saving.', 'askany' ); ?>');
                }
                setTimeout(() => { status.style.display = 'none'; }, 3000);
            })
            .catch(() => {
                status.style.display = 'inline';
                status.style.color   = '#d63638';
                status.textContent   = '❌ <?php esc_html_e( 'Network error.', 'askany' ); ?>';
            })
            .finally(() => {
                saveBtn.disabled    = false;
                saveBtn.textContent = '<?php esc_html_e( 'Save Rate Limit Settings', 'askany' ); ?>';
            });
        });
    }
})();
</script>


<!-- API Stat  -->
<div class="wrap askany-admin-page">
    <h1><?php _e( 'API Statistics & Performance', 'askany' ); ?></h1>
    <p class="description"><?php _e( 'Monitor your AI API performance, response times, and failure rates.', 'askany' ); ?></p>

    <!-- Performance Overview Cards -->
    <div class="askany-stats-overview">
        <div class="askany-stats-cards">
            <!-- Today's Performance -->
            <div class="askany-stat-card">
                <div class="stat-icon">
                    <span class="dashicons dashicons-clock"></span>
                </div>
                <div class="stat-content">
                    <h3><?php _e( 'Today', 'askany' ); ?></h3>
                    <div class="stat-number"><?php echo esc_html( $performance_today['total_requests'] ); ?></div>
                    <div class="stat-label"><?php _e( 'API Requests', 'askany' ); ?></div>
                    <div class="stat-meta">
                        <span class="success-rate"><?php echo esc_html( $performance_today['success_rate'] ); ?>% <?php _e( 'API Success', 'askany' ); ?></span>
                        <?php if ( $performance_today['fallback_requests'] > 0 ): ?>
                            <span class="fallback-rate"><?php echo esc_html( $performance_today['fallback_requests'] ); ?> <?php _e( 'Fallback', 'askany' ); ?></span>
                        <?php endif; ?>
                        <?php if ( $performance_today['avg_response_time'] > 0 ): ?>
                            <span class="response-time"><?php echo esc_html( $performance_today['avg_response_time'] ); ?>s <?php _e( 'Avg Time', 'askany' ); ?></span>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- This Week's Performance -->
            <div class="askany-stat-card">
                <div class="stat-icon">
                    <span class="dashicons dashicons-calendar-alt"></span>
                </div>
                <div class="stat-content">
                    <h3><?php _e( 'This Week', 'askany' ); ?></h3>
                    <div class="stat-number"><?php echo esc_html( $performance_week['total_requests'] ); ?></div>
                    <div class="stat-label"><?php _e( 'API Requests', 'askany' ); ?></div>
                    <div class="stat-meta">
                        <span class="success-rate"><?php echo esc_html( $performance_week['success_rate'] ); ?>% <?php _e( 'API Success', 'askany' ); ?></span>
                        <?php if ( $performance_week['fallback_requests'] > 0 ): ?>
                            <span class="fallback-rate"><?php echo esc_html( $performance_week['fallback_requests'] ); ?> <?php _e( 'Fallback', 'askany' ); ?></span>
                        <?php endif; ?>
                        <?php if ( $performance_week['avg_response_time'] > 0 ): ?>
                            <span class="response-time"><?php echo esc_html( $performance_week['avg_response_time'] ); ?>s <?php _e( 'Avg Time', 'askany' ); ?></span>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- This Month's Performance -->
            <div class="askany-stat-card">
                <div class="stat-icon">
                    <span class="dashicons dashicons-chart-area"></span>
                </div>
                <div class="stat-content">
                    <h3><?php _e( 'This Month', 'askany' ); ?></h3>
                    <div class="stat-number"><?php echo esc_html( $performance_month['total_requests'] ); ?></div>
                    <div class="stat-label"><?php _e( 'API Requests', 'askany' ); ?></div>
                    <div class="stat-meta">
                        <span class="success-rate"><?php echo esc_html( $performance_month['success_rate'] ); ?>% <?php _e( 'API Success', 'askany' ); ?></span>
                        <?php if ( $performance_month['fallback_requests'] > 0 ): ?>
                            <span class="fallback-rate"><?php echo esc_html( $performance_month['fallback_requests'] ); ?> <?php _e( 'Fallback', 'askany' ); ?></span>
                        <?php endif; ?>
                        <?php if ( $performance_month['avg_response_time'] > 0 ): ?>
                            <span class="response-time"><?php echo esc_html( $performance_month['avg_response_time'] ); ?>s <?php _e( 'Avg Time', 'askany' ); ?></span>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Fallback Usage -->
            <div class="askany-stat-card">
                <div class="stat-icon">
                    <span class="dashicons dashicons-backup"></span>
                </div>
                <div class="stat-content">
                    <h3><?php _e( 'Fallback Usage', 'askany' ); ?></h3>
                    <div class="stat-number"><?php echo esc_html( $performance_month['fallback_requests'] ); ?></div>
                    <div class="stat-label"><?php _e( 'Fallback Requests', 'askany' ); ?></div>
                    <div class="stat-meta">
                        <span class="fallback-rate"><?php echo esc_html( $performance_month['fallback_rate'] ); ?>% <?php _e( 'of Total', 'askany' ); ?></span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Charts Section -->
    <div class="askany-charts-section">
        <div class="askany-chart-container">
            <div class="chart-header">
                <h2><?php _e( 'Daily Performance Trend (Last 30 Days)', 'askany' ); ?></h2>
                <div class="chart-legend">
                    <span class="legend-item success"><span class="legend-color"></span><?php _e( 'Successful Requests', 'askany' ); ?></span>
                    <span class="legend-item failed"><span class="legend-color"></span><?php _e( 'Failed Requests', 'askany' ); ?></span>
                    <span class="legend-item response-time"><span class="legend-color"></span><?php _e( 'Avg Response Time', 'askany' ); ?></span>
                </div>
            </div>
            <canvas id="dailyPerformanceChart" width="800" height="400"></canvas>
        </div>

        <div class="askany-chart-row">
            <!-- API Provider Breakdown -->
            <div class="askany-chart-container half-width">
                <div class="chart-header">
                    <h3><?php _e( 'API Provider Usage', 'askany' ); ?></h3>
                </div>
                <canvas id="providerChart" width="400" height="300"></canvas>
                <div class="provider-stats">
                    <?php if ( ! empty( $stats_30_days['providers'] ) ): ?>
                        <?php foreach ( $stats_30_days['providers'] as $provider ): ?>
                            <div class="provider-stat">
                                <span class="provider-name"><?php echo esc_html( ucfirst( $provider['api_provider'] ) ); ?></span>
                                <span class="provider-requests"><?php echo esc_html( $provider['total_requests'] ); ?> <?php _e( 'requests', 'askany' ); ?></span>
                                <span class="provider-success-rate"><?php echo esc_html( round( ( $provider['successful_requests'] / $provider['total_requests'] ) * 100, 1 ) ); ?>% <?php _e( 'success', 'askany' ); ?></span>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <p class="no-data"><?php _e( 'No API usage data available yet.', 'askany' ); ?></p>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Request Types Breakdown -->
            <div class="askany-chart-container half-width">
                <div class="chart-header">
                    <h3><?php _e( 'Request Types', 'askany' ); ?></h3>
                </div>
                <canvas id="requestTypesChart" width="400" height="300"></canvas>
                <div class="request-type-stats">
                    <?php if ( ! empty( $stats_30_days['request_types'] ) ): ?>
                        <?php foreach ( $stats_30_days['request_types'] as $type ): ?>
                            <div class="request-type-stat">
                                <span class="type-name"><?php echo esc_html( ucfirst( $type['request_type'] ) ); ?></span>
                                <span class="type-requests"><?php echo esc_html( $type['total_requests'] ); ?> <?php _e( 'requests', 'askany' ); ?></span>
                                <span class="type-success-rate"><?php echo esc_html( round( ( $type['successful_requests'] / $type['total_requests'] ) * 100, 1 ) ); ?>% <?php _e( 'success', 'askany' ); ?></span>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <p class="no-data"><?php _e( 'No request type data available yet.', 'askany' ); ?></p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Detailed Statistics Table -->
    <div class="askany-detailed-stats">
        <h2><?php _e( 'Detailed Performance Metrics', 'askany' ); ?></h2>
        
        <div class="stats-table-container">
            <table class="wp-list-table widefat fixed striped">
                <thead>
                    <tr>
                        <th><?php _e( 'Metric', 'askany' ); ?></th>
                        <th><?php _e( 'Today', 'askany' ); ?></th>
                        <th><?php _e( 'This Week', 'askany' ); ?></th>
                        <th><?php _e( 'This Month', 'askany' ); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td><strong><?php _e( 'Total Requests', 'askany' ); ?></strong></td>
                        <td><?php echo esc_html( $performance_today['total_requests'] ); ?></td>
                        <td><?php echo esc_html( $performance_week['total_requests'] ); ?></td>
                        <td><?php echo esc_html( $performance_month['total_requests'] ); ?></td>
                    </tr>
                    <tr>
                        <td><strong><?php _e( 'Successful Requests', 'askany' ); ?></strong></td>
                        <td><span class="success-count"><?php echo esc_html( $performance_today['successful_requests'] ); ?></span></td>
                        <td><span class="success-count"><?php echo esc_html( $performance_week['successful_requests'] ); ?></span></td>
                        <td><span class="success-count"><?php echo esc_html( $performance_month['successful_requests'] ); ?></span></td>
                    </tr>
                    <tr>
                        <td><strong><?php _e( 'Failed Requests', 'askany' ); ?></strong></td>
                        <td><span class="error-count"><?php echo esc_html( $performance_today['error_requests'] ); ?></span></td>
                        <td><span class="error-count"><?php echo esc_html( $performance_week['error_requests'] ); ?></span></td>
                        <td><span class="error-count"><?php echo esc_html( $performance_month['error_requests'] ); ?></span></td>
                    </tr>
                    <tr>
                        <td><strong><?php _e( 'Success Rate', 'askany' ); ?></strong></td>
                        <td><span class="success-rate"><?php echo esc_html( $performance_today['success_rate'] ); ?>%</span></td>
                        <td><span class="success-rate"><?php echo esc_html( $performance_week['success_rate'] ); ?>%</span></td>
                        <td><span class="success-rate"><?php echo esc_html( $performance_month['success_rate'] ); ?>%</span></td>
                    </tr>
                    <tr>
                        <td><strong><?php _e( 'Fallback Usage', 'askany' ); ?></strong></td>
                        <td><span class="fallback-count"><?php echo esc_html( $performance_today['fallback_requests'] ); ?></span></td>
                        <td><span class="fallback-count"><?php echo esc_html( $performance_week['fallback_requests'] ); ?></span></td>
                        <td><span class="fallback-count"><?php echo esc_html( $performance_month['fallback_requests'] ); ?></span></td>
                    </tr>
                    <tr>
                        <td><strong><?php _e( 'Average Response Time', 'askany' ); ?></strong></td>
                        <td><?php echo esc_html( $performance_today['avg_response_time'] ); ?>s</td>
                        <td><?php echo esc_html( $performance_week['avg_response_time'] ); ?>s</td>
                        <td><?php echo esc_html( $performance_month['avg_response_time'] ); ?>s</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Recent Errors Section -->
    <div class="askany-recent-errors">
        <div class="section-header">
            <h2><?php _e( 'Recent API Errors', 'askany' ); ?></h2>
            <div class="section-actions">
                <button type="button" class="button" id="view-all-errors"><?php _e( 'View All Errors', 'askany' ); ?></button>
                <button type="button" class="button button-secondary" id="clear-old-errors"><?php _e( 'Clear Old Errors', 'askany' ); ?></button>
                <button type="button" class="button button-link-delete" id="clear-all-errors"><?php _e( 'Clear All Errors', 'askany' ); ?></button>
            </div>
        </div>

         
        <!-- Quick Overview -->
        <?php if ( ! empty( $stats_30_days['recent_errors'] ) ): ?>
        <div class="errors-overview">
            <div class="errors-table-container">
                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr>
                            <th><?php _e( 'Date', 'askany' ); ?></th>
                            <th><?php _e( 'Provider', 'askany' ); ?></th>
                            <th><?php _e( 'Error Message', 'askany' ); ?></th>
                            <th><?php _e( 'Query', 'askany' ); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ( $stats_30_days['recent_errors'] as $error ): ?>
                        <tr>
                            <td><?php echo esc_html( date( 'M j, Y H:i', strtotime( $error['created_at'] ) ) ); ?></td>
                            <td><span class="provider-badge <?php echo esc_attr( $error['api_provider'] ); ?>"><?php echo esc_html( ucfirst( $error['api_provider'] ) ); ?></span></td>
                            <td class="error-message"><?php echo esc_html( wp_trim_words( $error['error_message'], 10 ) ); ?></td>
                            <td class="query-text"><?php echo esc_html( wp_trim_words( $error['query_text'], 8 ) ); ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <p class="description"><?php _e( 'Showing 5 most recent errors. Click "View All Errors" to see complete list with pagination.', 'askany' ); ?></p>
        </div>
        <?php else: ?>
        <div class="no-errors-message">
            <p><?php _e( 'No recent API errors found. Your system is running smoothly!', 'askany' ); ?></p>
        </div>
        <?php endif; ?>

    </div>
</div>

<!-- Paginated Errors Modal -->
<div id="errors-modal" class="askany-modal" style="display: none;">
    <div class="askany-modal-content">
        <div class="askany-modal-header">
            <h3><?php _e( 'All API Errors', 'askany' ); ?></h3>
            <span class="askany-modal-close">&times;</span>
        </div>
        <div class="askany-modal-body">
            <div class="errors-filters">
                <label for="errors-per-page"><?php _e( 'Show:', 'askany' ); ?></label>
                <select id="errors-per-page">
                    <option value="10">10 <?php _e( 'per page', 'askany' ); ?></option>
                    <option value="25">25 <?php _e( 'per page', 'askany' ); ?></option>
                    <option value="50">50 <?php _e( 'per page', 'askany' ); ?></option>
                </select>
                
                <label for="errors-days"><?php _e( 'From last:', 'askany' ); ?></label>
                <select id="errors-days">
                    <option value="7">7 <?php _e( 'days', 'askany' ); ?></option>
                    <option value="30" selected>30 <?php _e( 'days', 'askany' ); ?></option>
                    <option value="90">90 <?php _e( 'days', 'askany' ); ?></option>
                </select>
            </div>
            
            <div id="paginated-errors-container">
                <!-- Paginated errors will be loaded here -->
            </div>
            
            <div id="errors-pagination" class="tablenav">
                <!-- Pagination will be loaded here -->
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Prepare data for charts
    const dailyStats = <?php echo json_encode( $stats_30_days['daily_stats'] ); ?>;
    const providerStats = <?php echo json_encode( $stats_30_days['providers'] ); ?>;
    const requestTypeStats = <?php echo json_encode( $stats_30_days['request_types'] ); ?>;

    // Daily Performance Chart
    const dailyCtx = document.getElementById('dailyPerformanceChart').getContext('2d');
    new Chart(dailyCtx, {
        type: 'line',
        data: {
            labels: dailyStats.map(stat => {
                const date = new Date(stat.date);
                return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
            }),
            datasets: [{
                label: 'Successful Requests',
                data: dailyStats.map(stat => stat.successful_requests),
                borderColor: '#4CAF50',
                backgroundColor: 'rgba(76, 175, 80, 0.1)',
                tension: 0.4,
                fill: true
            }, {
                label: 'Failed Requests',
                data: dailyStats.map(stat => stat.failed_requests),
                borderColor: '#f44336',
                backgroundColor: 'rgba(244, 67, 54, 0.1)',
                tension: 0.4,
                fill: true
            }, {
                label: 'Avg Response Time (s)',
                data: dailyStats.map(stat => stat.avg_response_time || 0),
                borderColor: '#FF9800',
                backgroundColor: 'rgba(255, 152, 0, 0.1)',
                tension: 0.4,
                yAxisID: 'y1'
            }]
        },
        options: {
            responsive: true,
            interaction: {
                mode: 'index',
                intersect: false,
            },
            scales: {
                y: {
                    type: 'linear',
                    display: true,
                    position: 'left',
                    title: {
                        display: true,
                        text: 'Number of Requests'
                    }
                },
                y1: {
                    type: 'linear',
                    display: true,
                    position: 'right',
                    title: {
                        display: true,
                        text: 'Response Time (seconds)'
                    },
                    grid: {
                        drawOnChartArea: false,
                    },
                }
            },
            plugins: {
                legend: {
                    display: false
                }
            }
        }
    });

    // Provider Usage Chart
    if (providerStats.length > 0) {
        const providerCtx = document.getElementById('providerChart').getContext('2d');
        new Chart(providerCtx, {
            type: 'doughnut',
            data: {
                labels: providerStats.map(stat => stat.api_provider.charAt(0).toUpperCase() + stat.api_provider.slice(1)),
                datasets: [{
                    data: providerStats.map(stat => stat.total_requests),
                    backgroundColor: [
                        '#4CAF50',
                        '#2196F3',
                        '#FF9800',
                        '#9C27B0',
                        '#F44336'
                    ]
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        position: 'bottom'
                    }
                }
            }
        });
    }

    // Request Types Chart
    if (requestTypeStats.length > 0) {
        const requestTypesCtx = document.getElementById('requestTypesChart').getContext('2d');
        new Chart(requestTypesCtx, {
            type: 'bar',
            data: {
                labels: requestTypeStats.map(stat => stat.request_type.charAt(0).toUpperCase() + stat.request_type.slice(1)),
                datasets: [{
                    label: 'Successful',
                    data: requestTypeStats.map(stat => stat.successful_requests),
                    backgroundColor: '#4CAF50'
                }, {
                    label: 'Failed',
                    data: requestTypeStats.map(stat => stat.failed_requests),
                    backgroundColor: '#f44336'
                }]
            },
            options: {
                responsive: true,
                scales: {
                    x: {
                        stacked: true
                    },
                    y: {
                        stacked: true,
                        title: {
                            display: true,
                            text: 'Number of Requests'
                        }
                    }
                },
                plugins: {
                    legend: {
                        position: 'bottom'
                    }
                }
            }
        });
    }

    // Error Management Functionality
    let currentErrorPage = 1;
    let errorsPerPage = 10;
    let errorsDays = 30;

    // Modal functionality
    const errorsModal = document.getElementById('errors-modal');
    const viewAllErrorsBtn = document.getElementById('view-all-errors');
    const clearOldErrorsBtn = document.getElementById('clear-old-errors');
    const clearAllErrorsBtn = document.getElementById('clear-all-errors');
    const modalClose = document.querySelector('.askany-modal-close');

    // Open modal
    viewAllErrorsBtn.addEventListener('click', function() {
        errorsModal.style.display = 'block';
        loadPaginatedErrors(1);
    });

    // Close modal
    modalClose.addEventListener('click', function() {
        errorsModal.style.display = 'none';
    });

    // Close modal when clicking outside
    window.addEventListener('click', function(event) {
        if (event.target === errorsModal) {
            errorsModal.style.display = 'none';
        }
    });

    // Filter changes
    document.getElementById('errors-per-page').addEventListener('change', function() {
        errorsPerPage = parseInt(this.value);
        loadPaginatedErrors(1);
    });

    document.getElementById('errors-days').addEventListener('change', function() {
        errorsDays = parseInt(this.value);
        loadPaginatedErrors(1);
    });

    // Clear errors functionality
    clearOldErrorsBtn.addEventListener('click', function() {
        Toast.ask('<?php _e( 'Clear Old Errors', 'askany' ); ?>', '<?php _e( 'Are you sure you want to clear errors older than 30 days?', 'askany' ); ?>')
            .then(result => {
                if (result.ok) {
                    clearErrors(30);
                }
            });
    });

    clearAllErrorsBtn.addEventListener('click', function() {
        Toast.ask('<?php _e( 'Clear All Errors', 'askany' ); ?>', '<?php _e( 'Are you sure you want to clear ALL error logs? This action cannot be undone.', 'askany' ); ?>')
            .then(result => {
                if (result.ok) {
                    clearErrors(0);
                }
            });
    });

    // Load paginated errors
    function loadPaginatedErrors(page) {
        currentErrorPage = page;
        
        const container = document.getElementById('paginated-errors-container');
        container.innerHTML = '<div class="loading"><?php _e( 'Loading errors...', 'askany' ); ?></div>';

        jQuery.post(ajaxurl, {
            action: 'askany_get_paginated_errors',
            nonce: '<?php echo wp_create_nonce( 'askany_chat_nonce' ); ?>',
            page: page,
            per_page: errorsPerPage,
            days: errorsDays
        }, function(response) {
            if (response.success) {
                displayPaginatedErrors(response.data);
            } else {
                container.innerHTML = '<div class="error">' + response.data.message + '</div>';
                // Use Toastmaster for error notification
                if (typeof Toastmaster !== 'undefined') {
                    Toastmaster.error('<?php _e( 'Error loading errors:', 'askany' ); ?> ' + response.data.message);
                }
            }
        }).fail(function() {
            container.innerHTML = '<div class="error"><?php _e( 'Network error. Please try again.', 'askany' ); ?></div>';
            // Use Toastmaster for network error
            if (typeof Toastmaster !== 'undefined') {
                Toastmaster.error('<?php _e( 'Network error. Please try again.', 'askany' ); ?>');
            }
        });
    }

    // Display paginated errors
    function displayPaginatedErrors(data) {
        const container = document.getElementById('paginated-errors-container');
        const paginationContainer = document.getElementById('errors-pagination');

        if (data.errors.length === 0) {
            container.innerHTML = '<div class="no-data"><?php _e( 'No errors found for the selected period.', 'askany' ); ?></div>';
            paginationContainer.innerHTML = '';
            return;
        }

        // Build errors table
        let html = '<table class="wp-list-table widefat fixed striped">';
        html += '<thead><tr>';
        html += '<th><?php _e( 'Date', 'askany' ); ?></th>';
        html += '<th><?php _e( 'Provider', 'askany' ); ?></th>';
        html += '<th><?php _e( 'Status', 'askany' ); ?></th>';
        html += '<th><?php _e( 'Error Message', 'askany' ); ?></th>';
        html += '<th><?php _e( 'Query', 'askany' ); ?></th>';
        html += '<th><?php _e( 'Response Time', 'askany' ); ?></th>';
        html += '</tr></thead><tbody>';

        data.errors.forEach(function(error) {
            const date = new Date(error.created_at);
            const formattedDate = date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
            const provider = error.api_provider.charAt(0).toUpperCase() + error.api_provider.slice(1);
            const status = error.status.replace('_', ' ').toUpperCase();
            const responseTime = error.response_time ? parseFloat(error.response_time).toFixed(3) + 's' : 'N/A';

            html += '<tr>';
            html += '<td>' + formattedDate + '</td>';
            html += '<td><span class="provider-badge ' + error.api_provider + '">' + provider + '</span></td>';
            html += '<td><span class="status-badge ' + error.status + '">' + status + '</span></td>';
            html += '<td class="error-message" title="' + (error.error_message || '') + '">' + 
                    (error.error_message ? error.error_message.substring(0, 80) + (error.error_message.length > 80 ? '...' : '') : 'N/A') + '</td>';
            html += '<td class="query-text" title="' + (error.query_text || '') + '">' + 
                    (error.query_text ? error.query_text.substring(0, 50) + (error.query_text.length > 50 ? '...' : '') : 'N/A') + '</td>';
            html += '<td>' + responseTime + '</td>';
            html += '</tr>';
        });

        html += '</tbody></table>';
        container.innerHTML = html;

        // Build pagination
        buildErrorsPagination(data.pagination);
    }

    // Build pagination controls
    function buildErrorsPagination(pagination) {
        const container = document.getElementById('errors-pagination');
        
        if (pagination.total_pages <= 1) {
            container.innerHTML = '';
            return;
        }

        let html = '<div class="tablenav-pages">';
        html += '<span class="displaying-num">' + pagination.total_errors + ' <?php _e( 'errors', 'askany' ); ?></span>';
        html += '<span class="pagination-links">';

        // First page
        if (pagination.current_page > 1) {
            html += '<a class="first-page button" href="#" data-page="1">&laquo;</a>';
            html += '<a class="prev-page button" href="#" data-page="' + (pagination.current_page - 1) + '">&lsaquo;</a>';
        } else {
            html += '<span class="tablenav-pages-navspan button disabled">&laquo;</span>';
            html += '<span class="tablenav-pages-navspan button disabled">&lsaquo;</span>';
        }

        // Page numbers
        html += '<span class="paging-input">';
        html += '<label for="current-page-selector" class="screen-reader-text"><?php _e( 'Current Page', 'askany' ); ?></label>';
        html += '<input class="current-page" id="current-page-selector" type="text" name="paged" value="' + pagination.current_page + '" size="2" aria-describedby="table-paging">';
        html += '<span class="tablenav-paging-text"> <?php _e( 'of', 'askany' ); ?> <span class="total-pages">' + pagination.total_pages + '</span></span>';
        html += '</span>';

        // Next/Last page
        if (pagination.current_page < pagination.total_pages) {
            html += '<a class="next-page button" href="#" data-page="' + (pagination.current_page + 1) + '">&rsaquo;</a>';
            html += '<a class="last-page button" href="#" data-page="' + pagination.total_pages + '">&raquo;</a>';
        } else {
            html += '<span class="tablenav-pages-navspan button disabled">&rsaquo;</span>';
            html += '<span class="tablenav-pages-navspan button disabled">&raquo;</span>';
        }

        html += '</span></div>';
        container.innerHTML = html;

        // Add click handlers for pagination
        container.querySelectorAll('a[data-page]').forEach(function(link) {
            link.addEventListener('click', function(e) {
                e.preventDefault();
                const page = parseInt(this.getAttribute('data-page'));
                loadPaginatedErrors(page);
            });
        });

        // Handle direct page input
        const pageInput = container.querySelector('#current-page-selector');
        pageInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                const page = parseInt(this.value);
                if (page >= 1 && page <= pagination.total_pages) {
                    loadPaginatedErrors(page);
                }
            }
        });
    }

    // Clear errors function
    function clearErrors(days) {
        const button = days === 0 ? clearAllErrorsBtn : clearOldErrorsBtn;
        const originalText = button.textContent;
        
        button.textContent = '<?php _e( 'Clearing...', 'askany' ); ?>';
        button.disabled = true;

        jQuery.post(ajaxurl, {
            action: 'askany_clear_api_errors',
            nonce: '<?php echo wp_create_nonce( 'askany_chat_nonce' ); ?>',
            days: days
        }, function(response) {
            if (response.success) {
                // Use Toast for success notification
                Toast.success(response.data.message);
                // Refresh the page to update all statistics
                setTimeout(function() {
                    location.reload();
                }, 1500);
            } else {
                // Use Toast for error notification
                Toast.error('<?php _e( 'Error:', 'askany' ); ?> ' + response.data.message);
            }
        }).fail(function() {
            // Use Toast for network error
            Toast.error('<?php _e( 'Network error. Please try again.', 'askany' ); ?>');
        }).always(function() {
            button.textContent = originalText;
            button.disabled = false;
        });
    }
});
</script>
