<?php

/**
 * Admin conversations 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.
$admin = new Inqyra_Admin('inqyra', INQYRA_VERSION);
$agent = $admin->get_current_agent();
if ( !$agent ) {
    echo '<div class="wrap"><div class="notice notice-warning"><p>' . esc_html__( 'Please create an agent first.', 'inqyra' ) . '</p></div></div>';
    return;
}
global $wpdb;
$date_filter = ' AND c.started_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)';
// Check if viewing a specific conversation.
$conversation_id = 0;
if ( isset( $_GET['conversation_id'] ) ) {
    if ( !isset( $_GET['_wpnonce'] ) || !wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'inqyra_view_conversation' ) ) {
        wp_die( esc_html__( 'Security check failed.', 'inqyra' ) );
    }
    $conversation_id = absint( wp_unslash( $_GET['conversation_id'] ) );
}
if ( $conversation_id ) {
    // Show conversation detail
    $detail_date_filter = ' AND started_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)';
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Custom table query. $detail_date_filter is a hardcoded SQL fragment.
    $conversation = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE id = %d' . $detail_date_filter, $wpdb->prefix . 'inqyra_conversations', $conversation_id ) );
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Custom table query.
    $messages = $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM %i
         WHERE conversation_id = %d
         ORDER BY created_at ASC', $wpdb->prefix . 'inqyra_messages', $conversation_id ) );
    ?>
    <div class="wrap inqyra-admin">
        <h1>
            <a href="<?php 
    echo esc_url( admin_url( 'admin.php?page=inqyra-conversations' ) );
    ?>" class="page-title-action">&larr; <?php 
    esc_html_e( 'Back', 'inqyra' );
    ?></a>
            <?php 
    esc_html_e( 'Conversation Detail', 'inqyra' );
    ?>
        </h1>

        <div class="inqyra-card">
            <h2><?php 
    esc_html_e( 'Session Information', 'inqyra' );
    ?></h2>
            <table class="inqyra-info-table">
                <tr>
                    <th><?php 
    esc_html_e( 'Session ID', 'inqyra' );
    ?></th>
                    <td><?php 
    echo esc_html( $conversation->session_id );
    ?></td>
                </tr>
                <tr>
                    <th><?php 
    esc_html_e( 'Started', 'inqyra' );
    ?></th>
                    <td><?php 
    echo esc_html( date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), strtotime( $conversation->started_at ) ) );
    ?></td>
                </tr>
                <tr>
                    <th><?php 
    esc_html_e( 'Messages', 'inqyra' );
    ?></th>
                    <td><?php 
    echo esc_html( $conversation->message_count );
    ?></td>
                </tr>
                <tr>
                    <th><?php 
    esc_html_e( 'Total Tokens', 'inqyra' );
    ?></th>
                    <td><?php 
    echo esc_html( number_format( $conversation->total_tokens ) );
    ?></td>
                </tr>
                <tr>
                    <th><?php 
    esc_html_e( 'Total Cost', 'inqyra' );
    ?></th>
                    <td>$<?php 
    echo esc_html( number_format( $conversation->total_cost_usd, 4 ) );
    ?></td>
                </tr>
            </table>
        </div>

        <div class="inqyra-card">
            <h2><?php 
    esc_html_e( 'Messages', 'inqyra' );
    ?></h2>
            <div class="inqyra-conversation-messages">
                <?php 
    foreach ( $messages as $message ) {
        ?>
                    <div class="inqyra-message inqyra-message-<?php 
        echo esc_attr( $message->role );
        ?>">
                        <div class="inqyra-message-header">
                            <strong><?php 
        echo esc_html( ucfirst( $message->role ) );
        ?></strong>
                            <span class="inqyra-message-time">
                                <?php 
        echo esc_html( date_i18n( get_option( 'time_format' ), strtotime( $message->created_at ) ) );
        ?>
                            </span>
                        </div>
                        <div class="inqyra-message-content">
                            <?php 
        echo nl2br( esc_html( $message->content ) );
        ?>
                        </div>
                        <?php 
        if ( $message->tokens_used > 0 ) {
            ?>
                            <div class="inqyra-message-meta">
                                <?php 
            printf( 
                /* translators: 1: Tokens, 2: Cost */
                esc_html__( '%1$s tokens ($%2$s)', 'inqyra' ),
                number_format( $message->tokens_used ),
                number_format( $message->cost_usd, 6 )
             );
            ?>
                            </div>
                        <?php 
        }
        ?>
                    </div>
                <?php 
    }
    ?>
            </div>
        </div>
    </div>
    <?php 
    return;
}
// List conversations
$per_page = 20;
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Standard WordPress pagination parameter.
$current_page = ( isset( $_GET['paged'] ) ? max( 1, intval( wp_unslash( $_GET['paged'] ) ) ) : 1 );
$offset = ($current_page - 1) * $per_page;
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Custom table query. $date_filter is a hardcoded SQL fragment.
$total_conversations = $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i c WHERE c.agent_id = %d' . $date_filter, $wpdb->prefix . 'inqyra_conversations', $agent->id ) );
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Custom table query. $date_filter is a hardcoded SQL fragment.
$conversations = $wpdb->get_results( $wpdb->prepare(
    'SELECT c.*, COUNT(m.id) as message_count_actual
     FROM %i c
     LEFT JOIN %i m ON m.conversation_id = c.id
     WHERE c.agent_id = %d' . $date_filter . '
     GROUP BY c.id
     ORDER BY c.started_at DESC
     LIMIT %d OFFSET %d',
    $wpdb->prefix . 'inqyra_conversations',
    $wpdb->prefix . 'inqyra_messages',
    $agent->id,
    $per_page,
    $offset
) );
// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
$total_pages = ceil( $total_conversations / $per_page );
?>
<div class="wrap inqyra-admin">
    <h1>
        <?php 
esc_html_e( 'Conversations', 'inqyra' );
?>
        <button type="button" id="inqyra-export-conversations" class="page-title-action" data-agent-id="<?php 
echo esc_attr( $agent->id );
?>">
            <?php 
esc_html_e( 'Export CSV', 'inqyra' );
?>
        </button>
    </h1>

    <div class="inqyra-card">
        <?php 
if ( empty( $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 style="width: 150px;"><?php 
    esc_html_e( 'Started', 'inqyra' );
    ?></th>
                        <th style="width: 80px;"><?php 
    esc_html_e( 'Messages', 'inqyra' );
    ?></th>
                        <th style="width: 100px;"><?php 
    esc_html_e( 'Tokens', 'inqyra' );
    ?></th>
                        <th style="width: 80px;"><?php 
    esc_html_e( 'Cost', 'inqyra' );
    ?></th>
                        <th style="width: 80px;"><?php 
    esc_html_e( 'Status', 'inqyra' );
    ?></th>
                        <th style="width: 120px;"><?php 
    esc_html_e( 'Actions', 'inqyra' );
    ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
    foreach ( $conversations as $conversation ) {
        ?>
                        <tr>
                            <td>
                                <a href="<?php 
        echo esc_url( wp_nonce_url( add_query_arg( 'conversation_id', $conversation->id ), 'inqyra_view_conversation' ) );
        ?>">
                                    <?php 
        echo esc_html( substr( $conversation->session_id, 0, 20 ) . '...' );
        ?>
                                </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_actual );
        ?></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>
                            <td>
                                <?php 
        if ( $conversation->archived ) {
            ?>
                                    <span class="inqyra-status-badge"><?php 
            esc_html_e( 'Archived', 'inqyra' );
            ?></span>
                                <?php 
        } else {
            ?>
                                    <span class="inqyra-status-badge inqyra-status-success"><?php 
            esc_html_e( 'Active', 'inqyra' );
            ?></span>
                                <?php 
        }
        ?>
                            </td>
                            <td>
                                <?php 
        if ( !$conversation->archived ) {
            ?>
                                    <button type="button" class="button button-small inqyra-archive-conversation" data-id="<?php 
            echo esc_attr( $conversation->id );
            ?>">
                                        <?php 
            esc_html_e( 'Archive', 'inqyra' );
            ?>
                                    </button>
                                <?php 
        }
        ?>
                                <button type="button" class="button button-small inqyra-delete-conversation" data-id="<?php 
        echo esc_attr( $conversation->id );
        ?>">
                                    <?php 
        esc_html_e( 'Delete', 'inqyra' );
        ?>
                                </button>
                            </td>
                        </tr>
                    <?php 
    }
    ?>
                </tbody>
            </table>

            <?php 
    if ( $total_pages > 1 ) {
        ?>
                <div class="tablenav bottom">
                    <div class="tablenav-pages">
                        <?php 
        echo wp_kses_post( paginate_links( [
            'base'      => add_query_arg( 'paged', '%#%' ),
            'format'    => '',
            'prev_text' => '&laquo;',
            'next_text' => '&raquo;',
            'total'     => $total_pages,
            'current'   => $current_page,
        ] ) );
        ?>
                    </div>
                </div>
            <?php 
    }
    ?>
        <?php 
}
?>
    </div>
</div>

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