<?php
/**
 * SiteStaffr AI Summary Diagnostics Page
 *
 * Diagnostic tools to debug AI recap generation and display issues.
 *
 * @link       https://github.com/sitestaffr/sitestaffr-plugin
 * @since      0.7.1
 *
 * @package    SiteStaffr
 * @subpackage SiteStaffr/admin/views
 */

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
    die;
}

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound

// Check user permissions
if ( ! current_user_can( 'manage_options' ) ) {
    wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'sitestaffr' ) );
}

// Generate nonce for AJAX requests
$diagnostics_nonce = wp_create_nonce( 'sitestaffr_diagnostics_nonce' );
$http_host          = isset( $_SERVER['HTTP_HOST'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) ) : '';
$is_dev_environment = ( defined( 'WP_DEBUG' ) && WP_DEBUG ) ||
    in_array( isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '', array( '127.0.0.1', '::1' ), true ) ||
    strpos( $http_host, 'localhost' ) !== false ||
    strpos( $http_host, '.local' ) !== false;

global $wpdb;
$calls_table = $wpdb->prefix . 'phoneease_calls';
$transcripts_table = $wpdb->prefix . 'phoneease_transcripts';

// Handle manual database upgrade
if ( isset( $_POST['run_database_upgrade'] ) && check_admin_referer( 'sitestaffr_run_database_upgrade' ) ) {
    SiteStaffr_Logger::legacy( 'SiteStaffr: Manual database upgrade triggered from Diagnostics page' );

    // Run database upgrade
    $upgrade_result = SiteStaffr_Database::upgrade_database();

    if ( $upgrade_result !== false ) {
        // Update stored version
        update_option( 'sitestaffr_version', SITESTAFFR_VERSION );
        update_option( 'sitestaffr_db_version', '1.0.0' );

        echo '<div class="notice notice-success"><p>' . esc_html__( 'Database upgrade completed successfully! Columns added.', 'sitestaffr' ) . '</p></div>';
        SiteStaffr_Logger::legacy( 'SiteStaffr: Manual database upgrade completed successfully' );
    } else {
        echo '<div class="notice notice-error"><p>' . esc_html__( 'Database upgrade failed. Check error logs for details.', 'sitestaffr' ) . '</p></div>';
        SiteStaffr_Logger::legacy( 'SiteStaffr: Manual database upgrade failed' );
    }

    // Refresh page to show updated status
    echo '<script>setTimeout(function(){ window.location.reload(); }, 2000);</script>';
}

// Handle manual recap regeneration
if ( isset( $_POST['regenerate_summary'] ) && isset( $_POST['call_id'] ) && check_admin_referer( 'sitestaffr_regenerate_summary' ) ) {
    $call_id = absint( wp_unslash( $_POST['call_id'] ) );

    // Get transcripts
    $transcripts = SiteStaffr_Database::get_call_transcripts( $call_id );

    if ( ! empty( $transcripts ) ) {
        // Instantiate generator
        $generator = new SiteStaffr_AI_Summary_Generator();

        // Generate recap
        $result = $generator->generate_call_summary( $call_id, $transcripts );

        // Store in database (recap-only; ai_followup intentionally empty)
        if ( ! empty( $result['summary'] ) ) {
            $update_result = SiteStaffr_Database::update_call_ai_summary(
                $call_id,
                $result['summary'],
                ''
            );

            if ( $update_result !== false ) {
                // translators: %d: the call ID number.
                echo '<div class="notice notice-success"><p>' . sprintf( esc_html__( 'Recap regenerated successfully for call #%d', 'sitestaffr' ), intval( $call_id ) ) . '</p></div>';
            } else {
                echo '<div class="notice notice-error"><p>' . esc_html__( 'Failed to store regenerated recap in database', 'sitestaffr' ) . '</p></div>';
            }
        } else {
            echo '<div class="notice notice-warning"><p>' . esc_html__( 'Recap generation returned empty result', 'sitestaffr' ) . '</p></div>';
        }
    } else {
        echo '<div class="notice notice-error"><p>' . esc_html__( 'No transcripts found for this call', 'sitestaffr' ) . '</p></div>';
    }
}

// Get system status
$ai_generator_exists = class_exists( 'SiteStaffr_AI_Summary_Generator' );
$database_class_exists = class_exists( 'SiteStaffr_Database' );
$call_manager_exists = class_exists( 'SiteStaffr_Call_Manager' );

/*
 * Dynamic identifiers below are trusted plugin table names and integer-only ID lists.
 */
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching

// Get version information
$current_version = defined( 'SITESTAFFR_VERSION' ) ? SITESTAFFR_VERSION : 'UNKNOWN';
$stored_version = get_option( 'sitestaffr_version', 'NOT SET' );
$stored_db_version = get_option( 'sitestaffr_db_version', 'NOT SET' );

// Check if database columns exist
$columns_check = $wpdb->get_results( $wpdb->prepare( "SHOW COLUMNS FROM %i LIKE 'ai_%%'", $calls_table ) );
$has_ai_summary_column = false;
foreach ( $columns_check as $column ) {
    if ( $column->Field === 'ai_summary' ) {
        $has_ai_summary_column = true;
    }
}

// Check hook registration
global $wp_filter;
$hook_name = 'sitestaffr_call_completed';
$hook_registered = isset( $wp_filter[ $hook_name ] ) && ! empty( $wp_filter[ $hook_name ]->callbacks );
$hook_callbacks = array();

if ( $hook_registered ) {
    foreach ( $wp_filter[ $hook_name ]->callbacks as $priority => $callbacks ) {
        foreach ( $callbacks as $callback ) {
            $callback_name = '';
            if ( is_array( $callback['function'] ) ) {
                if ( is_object( $callback['function'][0] ) ) {
                    $callback_name = get_class( $callback['function'][0] ) . '::' . $callback['function'][1];
                } else {
                    $callback_name = $callback['function'][0] . '::' . $callback['function'][1];
                }
            } elseif ( is_string( $callback['function'] ) ) {
                $callback_name = $callback['function'];
            } else {
                $callback_name = 'Closure';
            }

            $hook_callbacks[] = array(
                'priority' => $priority,
                'callback' => $callback_name,
                'accepted_args' => $callback['accepted_args'],
            );
        }
    }
}

// Get latest 10 calls with recap info
$latest_calls = $wpdb->get_results(
    $wpdb->prepare(
        'SELECT
            id,
            session_id,
            from_number,
            call_status,
            call_duration,
            started_at,
            is_read,
            is_test_call,
            is_billable,
            LENGTH(ai_summary) as summary_length,
            ai_summary
        FROM %i
        ORDER BY id DESC
        LIMIT 10',
        $calls_table
    )
);

// Get transcript count for each call
$transcript_counts = array();
if ( ! empty( $latest_calls ) ) {
    $call_ids = array_map( function( $call ) { return $call->id; }, $latest_calls );
    $placeholders = implode( ',', array_fill( 0, count( $call_ids ), '%d' ) );

    $counts = $wpdb->get_results(
        $wpdb->prepare(
            // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- dynamic placeholder count matches $call_ids count.
            "SELECT call_id, COUNT(*) as count FROM %i WHERE call_id IN ({$placeholders}) GROUP BY call_id",
            array_merge( array( $transcripts_table ), array_map( 'intval', $call_ids ) )
        )
    );

    foreach ( $counts as $count ) {
        $transcript_counts[ $count->call_id ] = $count->count;
    }
}

// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching

// Get the latest call for detailed view
$latest_call = ! empty( $latest_calls ) ? $latest_calls[0] : null;
$latest_transcripts = $latest_call ? SiteStaffr_Database::get_call_transcripts( $latest_call->id ) : array();

?>

<div class="wrap sitestaffr-diagnostics">
    <?php
    $sitestaffr_page_title = __( 'Diagnostics', 'sitestaffr' );
    include SITESTAFFR_PLUGIN_DIR . 'admin/partials/sitestaffr-header.php';
    ?>
    <h1>
        <span class="dashicons dashicons-admin-tools"></span>
        <?php esc_html_e( 'AI Recap Diagnostics', 'sitestaffr' ); ?>
    </h1>

    <p><?php esc_html_e( 'This page shows diagnostic information about AI recap generation and display.', 'sitestaffr' ); ?></p>

    <?php if ( $is_dev_environment ) : ?>
    <!-- Development-only Setup Actions -->
    <div style="margin: 20px 0;">
        <a href="<?php echo esc_url( admin_url( 'admin.php?page=sitestaffr-setup' ) ); ?>" class="button button-secondary">
            <span class="dashicons dashicons-controls-repeat" style="vertical-align: text-bottom;"></span>
            <?php esc_html_e( 'Run Setup Wizard (Development)', 'sitestaffr' ); ?>
        </a>
    </div>
    <?php endif; ?>

    <div class="sitestaffr-diagnostics-grid sitestaffr-diagnostics-grid--top">
    <!-- Reset to Fresh Install -->
    <div class="card" style="margin-top: 20px; border-left: 4px solid #d63638;">
        <h2 style="color: #d63638;">
            <span class="dashicons dashicons-warning"></span>
            <?php esc_html_e( 'Reset to Fresh Install', 'sitestaffr' ); ?>
        </h2>
        <p class="description">
            <?php esc_html_e( 'Wipes all SiteStaffr data (settings, calls, billing) and re-registers as a new site with a fresh trial. This cannot be undone.', 'sitestaffr' ); ?>
        </p>
        <p style="margin-top: 15px;">
            <button type="button" class="button" id="sitestaffr-reset-fresh-install" style="background: #d63638; border-color: #d63638; color: #fff;">
                <?php esc_html_e( 'Reset Everything', 'sitestaffr' ); ?>
            </button>
            <span class="spinner" id="sitestaffr-reset-spinner" style="float: none; margin-left: 10px;"></span>
        </p>
        <div id="sitestaffr-reset-error" style="display: none; margin-top: 10px; padding: 10px; background: #fff3cd; border-left: 4px solid #ffc107; color: #856404;"></div>
    </div>

    <!-- Billing State Test Controls -->
    <div class="card" style="margin-top: 20px; border-left: 4px solid #2271b1;">
        <h2>
            <span class="dashicons dashicons-chart-line"></span>
            <?php esc_html_e( 'Billing State Test Controls', 'sitestaffr' ); ?>
        </h2>
        <p class="description">
            <?php esc_html_e( 'Drain AI minutes through real middleware usage events so you can test Low and Critical UI states end-to-end.', 'sitestaffr' ); ?>
        </p>
        <p style="margin-top: 15px;">
            <button type="button" class="button button-secondary" id="sitestaffr-drain-to-low">
                <?php esc_html_e( 'Drain to Low', 'sitestaffr' ); ?>
            </button>
            <button type="button" class="button button-secondary" id="sitestaffr-drain-to-critical" style="margin-left: 8px;">
                <?php esc_html_e( 'Drain to Critical', 'sitestaffr' ); ?>
            </button>
            <span class="spinner" id="sitestaffr-drain-spinner" style="float: none; margin-left: 10px;"></span>
        </p>
        <div id="sitestaffr-drain-result" style="display: none; margin-top: 10px; padding: 10px; border-left: 4px solid #2271b1; background: #f0f6fc; color: #1d2327;"></div>
        <p class="description" style="margin-top: 10px;">
            <?php esc_html_e( 'Use only for QA. This consumes real account minutes and is not reversible except by purchase or reset.', 'sitestaffr' ); ?>
        </p>
    </div>
    </div>

    <!-- Token Usage Analytics (Developer Tool) -->
    <div class="card sitestaffr-diagnostics-card--full" style="margin-top: 20px;">
        <h2>
            <span class="dashicons dashicons-chart-bar"></span>
            <?php esc_html_e( 'Token Usage Analytics', 'sitestaffr' ); ?>
        </h2>
        <p class="description">
            <?php esc_html_e( 'Cost tracking for AI API calls (Internal SiteStaffr team use only)', 'sitestaffr' ); ?>
        </p>

        <!-- Search by Call Reference -->
        <div class="token-search" style="margin: 20px 0; padding: 15px; background: #f9f9f9; border-left: 4px solid #1FB6CC;">
            <h3 style="margin-top: 0;"><?php esc_html_e( 'Analyze Call by Reference', 'sitestaffr' ); ?></h3>
            <div class="token-search-controls" style="display: flex; align-items: center; gap: 10px;">
                <label for="token-callsid" style="font-weight: 600;">
                    <?php esc_html_e( 'Call Reference:', 'sitestaffr' ); ?>
                </label>
                <input type="text" id="token-callsid" class="token-callsid-input" placeholder="legacy SID, sess_..., or call ID" style="width: 400px; padding: 8px;" value="">
                <button type="button" class="button button-primary" id="analyze-tokens">
                    <span class="dashicons dashicons-search" style="vertical-align: middle;"></span>
                    <?php esc_html_e( 'Analyze Tokens', 'sitestaffr' ); ?>
                </button>
            </div>
            <p class="description" style="margin-top: 10px;">
                <?php esc_html_e( 'Use legacy Call SID (CA...), WebRTC Session ID (sess_...), or numeric Call ID to view token usage.', 'sitestaffr' ); ?>
            </p>
        </div>

        <!-- Token Metrics Display (hidden until analysis runs) -->
        <div id="token-metrics-display" style="display: none; margin-top: 20px;">
            <!-- Call Info Header -->
            <div style="background: #f0f6fc; padding: 15px; border-left: 4px solid #0073aa; margin-bottom: 20px;">
                <h3 style="margin: 0 0 10px 0;"><?php esc_html_e( 'Call Information', 'sitestaffr' ); ?></h3>
                <div class="token-call-info-grid" style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px;">
                    <div>
                        <strong><?php esc_html_e( 'CallSid:', 'sitestaffr' ); ?></strong><br>
                        <code id="display-callsid"></code>
                    </div>
                    <div>
                        <strong><?php esc_html_e( 'From Number:', 'sitestaffr' ); ?></strong><br>
                        <code id="display-from-number"></code>
                    </div>
                    <div>
                        <strong><?php esc_html_e( 'Duration:', 'sitestaffr' ); ?></strong><br>
                        <code id="display-duration"></code>
                    </div>
                    <div>
                        <strong><?php esc_html_e( 'Started At:', 'sitestaffr' ); ?></strong><br>
                        <code id="display-started-at"></code>
                    </div>
                    <div>
                        <strong><?php esc_html_e( 'AI Model:', 'sitestaffr' ); ?></strong><br>
                        <code id="display-model"></code>
                    </div>
                </div>
            </div>

            <!-- Operations Table -->
            <h3><?php esc_html_e( 'Token Usage by Operation', 'sitestaffr' ); ?></h3>
            <table class="widefat striped">
                <thead>
                    <tr>
                        <th><?php esc_html_e( 'Operation Type', 'sitestaffr' ); ?></th>
                        <th><?php esc_html_e( 'Input Tokens', 'sitestaffr' ); ?></th>
                        <th><?php esc_html_e( 'Output Tokens', 'sitestaffr' ); ?></th>
                        <th><?php esc_html_e( 'Cached Tokens', 'sitestaffr' ); ?></th>
                        <th><?php esc_html_e( 'Total Tokens', 'sitestaffr' ); ?></th>
                        <th><?php esc_html_e( 'Model', 'sitestaffr' ); ?></th>
                        <th><?php esc_html_e( 'Response Time', 'sitestaffr' ); ?></th>
                        <th><?php esc_html_e( 'Timestamp', 'sitestaffr' ); ?></th>
                    </tr>
                </thead>
                <tbody id="token-operations-body">
                    <!-- Populated by JavaScript -->
                </tbody>
            </table>

            <!-- Cost Summary -->
            <div class="token-cost-summary" style="margin-top: 20px; padding: 20px; background: #f0f6fc; border-left: 4px solid #1FB6CC;">
                <h3 style="margin-top: 0;"><?php esc_html_e( 'Cost Analysis Summary', 'sitestaffr' ); ?></h3>
                <div class="token-cost-grid" style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px;">
                    <div>
                        <h4><?php esc_html_e( 'Token Breakdown by Operation:', 'sitestaffr' ); ?></h4>
                        <ul style="font-size: 14px; line-height: 1.8;">
                            <li><strong><?php esc_html_e( 'Conversation:', 'sitestaffr' ); ?></strong> <span id="token-conversation">0</span> <?php esc_html_e( 'tokens', 'sitestaffr' ); ?> (<span id="op-count-conversation">0</span> <?php esc_html_e( 'operations', 'sitestaffr' ); ?>)</li>
                            <li><strong><?php esc_html_e( 'Recap:', 'sitestaffr' ); ?></strong> <span id="token-recap">0</span> <?php esc_html_e( 'tokens', 'sitestaffr' ); ?> (<span id="op-count-recap">0</span> <?php esc_html_e( 'operations', 'sitestaffr' ); ?>)</li>
                            <li><strong><?php esc_html_e( 'Other:', 'sitestaffr' ); ?></strong> <span id="token-other">0</span> <?php esc_html_e( 'tokens', 'sitestaffr' ); ?> (<span id="op-count-other">0</span> <?php esc_html_e( 'operations', 'sitestaffr' ); ?>)</li>
                        </ul>
                    </div>
                    <div>
                        <h4><?php esc_html_e( 'Total Costs:', 'sitestaffr' ); ?></h4>
                        <ul style="font-size: 14px; line-height: 1.8;">
                            <li><strong><?php esc_html_e( 'Total Input:', 'sitestaffr' ); ?></strong> <span id="token-input">0</span> <?php esc_html_e( 'tokens', 'sitestaffr' ); ?> ($<span id="cost-input">0.000000</span>)</li>
                            <li><strong><?php esc_html_e( 'Total Output:', 'sitestaffr' ); ?></strong> <span id="token-output">0</span> <?php esc_html_e( 'tokens', 'sitestaffr' ); ?> ($<span id="cost-output">0.000000</span>)</li>
                            <li><strong><?php esc_html_e( 'Total Cached:', 'sitestaffr' ); ?></strong> <span id="token-cached">0</span> <?php esc_html_e( 'tokens', 'sitestaffr' ); ?> ($<span id="cost-cached">0.000000</span>)</li>
                            <li style="font-size: 16px; margin-top: 10px; padding-top: 10px; border-top: 2px solid #1FB6CC;">
                                <strong><?php esc_html_e( 'Estimated Total Cost:', 'sitestaffr' ); ?></strong>
                                <span style="color: #1FB6CC; font-size: 18px; font-weight: 700;">$<span id="token-total-cost">0.000000</span></span>
                            </li>
                        </ul>
                    </div>
                </div>
                <p class="description" style="margin-top: 15px; font-style: italic;">
                    <span id="pricing-note"><?php esc_html_e( 'Recap model: configured in middleware environment variables.', 'sitestaffr' ); ?></span>
                </p>
            </div>
        </div>

        <!-- Error Display -->
        <div id="token-error-display" style="display: none; margin-top: 20px; padding: 15px; background: #fff3cd; border-left: 4px solid #ffc107;">
            <p style="margin: 0; color: #856404;"><strong><?php esc_html_e( 'Error:', 'sitestaffr' ); ?></strong> <span id="token-error-message"></span></p>
        </div>

        <!-- Loading Indicator -->
        <div id="token-loading" style="display: none; margin-top: 20px; padding: 15px; text-align: center;">
            <span class="spinner is-active" style="float: none; margin: 0;"></span>
            <span style="margin-left: 10px;"><?php esc_html_e( 'Analyzing token usage...', 'sitestaffr' ); ?></span>
        </div>
    </div>

    <div class="sitestaffr-diagnostics-grid sitestaffr-diagnostics-grid--meta">

    <!-- System Status -->
    <div class="card" style="margin-top: 20px;">
        <h2><?php esc_html_e( 'System Status', 'sitestaffr' ); ?></h2>
        <table class="widefat striped">
            <tbody>
                <tr>
                    <th style="width: 40%;"><?php esc_html_e( 'Current Plugin Version', 'sitestaffr' ); ?></th>
                    <td><code><?php echo esc_html( $current_version ); ?></code></td>
                </tr>
                <tr>
                    <th><?php esc_html_e( 'Stored Plugin Version', 'sitestaffr' ); ?></th>
                    <td>
                        <code><?php echo esc_html( $stored_version ); ?></code>
                        <?php if ( $stored_version !== $current_version && $stored_version !== 'NOT SET' ) : ?>
                            <span style="color: orange;"> (<?php esc_html_e( 'Version mismatch detected', 'sitestaffr' ); ?>)</span>
                        <?php endif; ?>
                    </td>
                </tr>
                <tr>
                    <th><?php esc_html_e( 'Database Schema Version', 'sitestaffr' ); ?></th>
                    <td><code><?php echo esc_html( $stored_db_version ); ?></code></td>
                </tr>
                <tr>
                    <th style="width: 40%;"><?php esc_html_e( 'AI Summary Generator Class', 'sitestaffr' ); ?></th>
                    <td>
                        <?php if ( $ai_generator_exists ) : ?>
                            <span class="dashicons dashicons-yes-alt" style="color: green;"></span>
                            <?php esc_html_e( 'Loaded', 'sitestaffr' ); ?>
                        <?php else : ?>
                            <span class="dashicons dashicons-dismiss" style="color: red;"></span>
                            <?php esc_html_e( 'NOT LOADED', 'sitestaffr' ); ?>
                        <?php endif; ?>
                    </td>
                </tr>
                <tr>
                    <th><?php esc_html_e( 'Database Class', 'sitestaffr' ); ?></th>
                    <td>
                        <?php if ( $database_class_exists ) : ?>
                            <span class="dashicons dashicons-yes-alt" style="color: green;"></span>
                            <?php esc_html_e( 'Loaded', 'sitestaffr' ); ?>
                        <?php else : ?>
                            <span class="dashicons dashicons-dismiss" style="color: red;"></span>
                            <?php esc_html_e( 'NOT LOADED', 'sitestaffr' ); ?>
                        <?php endif; ?>
                    </td>
                </tr>
                <tr>
                    <th><?php esc_html_e( 'Call Manager Class', 'sitestaffr' ); ?></th>
                    <td>
                        <?php if ( $call_manager_exists ) : ?>
                            <span class="dashicons dashicons-yes-alt" style="color: green;"></span>
                            <?php esc_html_e( 'Loaded', 'sitestaffr' ); ?>
                        <?php else : ?>
                            <span class="dashicons dashicons-dismiss" style="color: red;"></span>
                            <?php esc_html_e( 'NOT LOADED', 'sitestaffr' ); ?>
                        <?php endif; ?>
                    </td>
                </tr>
                <tr>
                    <th><?php esc_html_e( 'Database Column: ai_summary', 'sitestaffr' ); ?></th>
                    <td>
                        <?php if ( $has_ai_summary_column ) : ?>
                            <span class="dashicons dashicons-yes-alt" style="color: green;"></span>
                            <?php esc_html_e( 'EXISTS', 'sitestaffr' ); ?>
                        <?php else : ?>
                            <span class="dashicons dashicons-dismiss" style="color: red;"></span>
                            <?php esc_html_e( 'MISSING', 'sitestaffr' ); ?>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php if ( ! $has_ai_summary_column ) : ?>
                <tr>
                    <th><?php esc_html_e( 'Manual Database Upgrade', 'sitestaffr' ); ?></th>
                    <td>
                        <form method="post" style="display: inline;">
                            <?php wp_nonce_field( 'sitestaffr_run_database_upgrade' ); ?>
                            <button type="submit" name="run_database_upgrade" class="button button-primary" onclick="return confirm('<?php esc_attr_e( 'This will add the missing database columns. Continue?', 'sitestaffr' ); ?>');">
                                <span class="dashicons dashicons-database-import" style="vertical-align: middle;"></span>
                                <?php esc_html_e( 'Run Database Upgrade', 'sitestaffr' ); ?>
                            </button>
                        </form>
                        <p class="description">
                            <?php esc_html_e( 'Click this button to manually add the missing ai_summary column to the database.', 'sitestaffr' ); ?>
                        </p>
                    </td>
                </tr>
                <?php endif; ?>
                <tr>
                    <th><?php esc_html_e( 'Hook: sitestaffr_call_completed', 'sitestaffr' ); ?></th>
                    <td>
                        <?php if ( $hook_registered ) : ?>
                            <span class="dashicons dashicons-yes-alt" style="color: green;"></span>
                            <?php // translators: %d: number of registered callbacks. ?>
                            <?php echo esc_html( sprintf( __( 'Registered (%d callbacks)', 'sitestaffr' ), count( $hook_callbacks ) ) ); ?>
                        <?php else : ?>
                            <span class="dashicons dashicons-dismiss" style="color: red;"></span>
                            <?php esc_html_e( 'NOT REGISTERED', 'sitestaffr' ); ?>
                        <?php endif; ?>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>

    <!-- Hook Callbacks -->
    <?php if ( ! empty( $hook_callbacks ) ) : ?>
    <div class="card" style="margin-top: 20px;">
        <h2><?php esc_html_e( 'Registered Callbacks for sitestaffr_call_completed', 'sitestaffr' ); ?></h2>
        <table class="widefat striped">
            <thead>
                <tr>
                    <th><?php esc_html_e( 'Priority', 'sitestaffr' ); ?></th>
                    <th><?php esc_html_e( 'Callback', 'sitestaffr' ); ?></th>
                    <th><?php esc_html_e( 'Accepted Args', 'sitestaffr' ); ?></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ( $hook_callbacks as $callback_info ) : ?>
                <tr>
                    <td><?php echo esc_html( $callback_info['priority'] ); ?></td>
                    <td><code><?php echo esc_html( $callback_info['callback'] ); ?></code></td>
                    <td><?php echo esc_html( $callback_info['accepted_args'] ); ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
    </div>

    <div class="sitestaffr-diagnostics-grid sitestaffr-diagnostics-grid--calls">

    <!-- Latest 10 Calls -->
    <div class="card" style="margin-top: 20px;">
        <h2><?php esc_html_e( 'Latest 10 Calls Summary', 'sitestaffr' ); ?></h2>
        <?php if ( ! empty( $latest_calls ) ) : ?>
        <table class="widefat striped">
            <thead>
                <tr>
                    <th><?php esc_html_e( 'ID', 'sitestaffr' ); ?></th>
                    <th><?php esc_html_e( 'From', 'sitestaffr' ); ?></th>
                    <th><?php esc_html_e( 'Status', 'sitestaffr' ); ?></th>
                    <th><?php esc_html_e( 'Duration', 'sitestaffr' ); ?></th>
                    <th><?php esc_html_e( 'Started At', 'sitestaffr' ); ?></th>
                    <th><?php esc_html_e( 'Transcripts', 'sitestaffr' ); ?></th>
                    <th><?php esc_html_e( 'Recap Length', 'sitestaffr' ); ?></th>
                    <th><?php esc_html_e( 'Actions', 'sitestaffr' ); ?></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ( $latest_calls as $call ) : ?>
                <tr>
                    <td><strong><?php echo esc_html( $call->id ); ?></strong></td>
                    <td><?php echo esc_html( $call->from_number ); ?></td>
                    <td>
                        <?php echo esc_html( $call->call_status ); ?>
                        <?php if ( $call->is_test_call ) : ?>
                            <br><span style="color: #888; font-size: 11px;">(Test)</span>
                        <?php endif; ?>
                    </td>
                    <td><?php echo esc_html( $call->call_duration ); ?>s</td>
                    <td><?php echo esc_html( $call->started_at ); ?></td>
                    <td>
                        <?php
                        $transcript_count = isset( $transcript_counts[ $call->id ] ) ? $transcript_counts[ $call->id ] : 0;
                        echo esc_html( $transcript_count );
                        ?>
                    </td>
                    <td>
                        <?php if ( $call->summary_length > 0 ) : ?>
                            <span style="color: green;"><?php echo esc_html( $call->summary_length ); ?> chars</span>
                        <?php else : ?>
                            <span style="color: red;">Empty</span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <form method="post" style="display: inline;">
                            <?php wp_nonce_field( 'sitestaffr_regenerate_summary' ); ?>
                            <input type="hidden" name="call_id" value="<?php echo esc_attr( $call->id ); ?>">
                            <button type="submit" name="regenerate_summary" class="button button-small">
                                <?php esc_html_e( 'Regenerate', 'sitestaffr' ); ?>
                            </button>
                        </form>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <?php else : ?>
        <p><?php esc_html_e( 'No calls found in the database.', 'sitestaffr' ); ?></p>
        <?php endif; ?>
    </div>

    <!-- Latest Call Details -->
    <?php if ( $latest_call ) : ?>
    <div class="card" style="margin-top: 20px;">
        <?php // translators: %d: the call ID number. ?>
        <h2><?php echo esc_html( sprintf( __( 'Latest Call Details (ID: %d)', 'sitestaffr' ), $latest_call->id ) ); ?></h2>

        <h3><?php esc_html_e( 'AI Recap', 'sitestaffr' ); ?></h3>
        <div style="background: #f9f9f9; padding: 15px; border-left: 4px solid #0073aa;">
            <?php if ( ! empty( $latest_call->ai_summary ) ) : ?>
                <div><?php echo wp_kses_post( stripslashes( $latest_call->ai_summary ) ); ?></div>
            <?php else : ?>
                <p style="color: #d63638;"><em><?php esc_html_e( 'No AI recap generated yet.', 'sitestaffr' ); ?></em></p>
            <?php endif; ?>
        </div>

        <h3 style="margin-top: 20px;"><?php esc_html_e( 'Call Transcripts', 'sitestaffr' ); ?></h3>
        <?php if ( ! empty( $latest_transcripts ) ) : ?>
        <div style="background: #f9f9f9; padding: 15px; border-left: 4px solid #46b450;">
            <?php foreach ( $latest_transcripts as $transcript ) : ?>
                <p style="margin: 10px 0;">
                    <strong><?php echo esc_html( $transcript->speaker === 'ai' ? 'AI' : 'Visitor' ); ?>:</strong>
                    <?php echo esc_html( stripslashes( $transcript->message_text ) ); ?>
                    <br>
                    <span style="color: #888; font-size: 11px;">
                        <?php echo esc_html( $transcript->timestamp ); ?>
                        <?php if ( $transcript->confidence_score !== null ) : ?>
                            (Confidence: <?php echo esc_html( number_format( $transcript->confidence_score * 100, 0 ) ); ?>%)
                        <?php endif; ?>
                    </span>
                </p>
            <?php endforeach; ?>
        </div>
        <?php else : ?>
        <p style="color: #d63638;"><em><?php esc_html_e( 'No transcripts found for this call.', 'sitestaffr' ); ?></em></p>
        <?php endif; ?>
    </div>
    <?php endif; ?>
    </div>

</div>

<style>
.wrap.sitestaffr-diagnostics {
    max-width: none !important;
    margin: 10px 0 0 0 !important;
    padding-right: 20px;
}

.sitestaffr-diagnostics .card {
    background: white;
    border: 1px solid #ccd0d4;
    box-shadow: 0 1px 1px rgba(0,0,0,.04);
    padding: 20px;
    max-width: none;
}

.sitestaffr-diagnostics .card h2 {
    margin-top: 0;
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;
}

.sitestaffr-diagnostics .card h3 {
    margin-top: 0;
    color: #23282d;
}

.sitestaffr-diagnostics-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(360px, 1fr));
    gap: 20px;
    align-items: start;
}

.sitestaffr-diagnostics-grid .card {
    margin-top: 0 !important;
}

.sitestaffr-diagnostics-grid--top,
.sitestaffr-diagnostics-grid--meta,
.sitestaffr-diagnostics-grid--calls {
    margin-top: 20px;
}

.sitestaffr-diagnostics-card--full {
    max-width: none;
}

.sitestaffr-diagnostics .token-search > div {
    flex-wrap: wrap;
}

.sitestaffr-diagnostics #token-callsid {
    width: auto !important;
    min-width: 280px;
    flex: 1 1 360px;
}

@media screen and (max-width: 1280px) {
    .sitestaffr-diagnostics-grid {
        grid-template-columns: 1fr;
    }
}

@media screen and (max-width: 1024px) {
    .sitestaffr-diagnostics .card table.widefat {
        display: block;
        overflow-x: auto;
        -webkit-overflow-scrolling: touch;
    }

    .sitestaffr-diagnostics .token-search-controls {
        align-items: stretch;
    }

    .sitestaffr-diagnostics .token-callsid-input,
    .sitestaffr-diagnostics #token-callsid {
        width: 100% !important;
        min-width: 0;
        flex: 1 1 100%;
    }

    .sitestaffr-diagnostics .token-call-info-grid {
        grid-template-columns: repeat(2, minmax(0, 1fr)) !important;
    }

    .sitestaffr-diagnostics .token-cost-grid {
        grid-template-columns: 1fr !important;
    }
}

@media screen and (max-width: 782px) {
    .wrap.sitestaffr-diagnostics {
        margin: 10px 0 0 0 !important;
        padding-right: 0;
    }

    .sitestaffr-diagnostics .token-call-info-grid {
        grid-template-columns: 1fr !important;
    }

    .sitestaffr-diagnostics .token-search-controls .button {
        width: 100%;
        justify-content: center;
    }
}
</style>
<?php // phpcs:enable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound ?>
