<?php

/**

 * Activity Logs - Enterprise Dashboard

 *

 * @package    SensFRX

 * @subpackage SensFRX/admin/partials

 */



// If this file is called directly, abort.

if (!defined('WPINC')) {

    die;

}



// Get activity data from database

global $wpdb;

$activity_table = $wpdb->prefix . 'sensfrx_real_activity';



// Get filter parameters

$filter_type = isset($_GET['activity_type']) ? sanitize_text_field($_GET['activity_type']) : 'all';

$search_query = isset($_GET['search']) ? sanitize_text_field($_GET['search']) : '';



// Pagination parameters

$current_page = isset($_GET['paged']) ? max(1, intval($_GET['paged'])) : 1;

$per_page = isset($_GET['per_page']) ? intval($_GET['per_page']) : 10;

$per_page = in_array($per_page, [10, 25, 50, 100]) ? $per_page : 10; // Validate per_page

$offset = ($current_page - 1) * $per_page;



// Build query based on filters

$where_clauses = array('1=1');



if ($filter_type !== 'all') {

    switch ($filter_type) {

        case 'orders':

            $where_clauses[] = "(sensfrx_log_type LIKE '%Transaction%' OR sensfrx_log_type LIKE '%Order%')";

            break;

        case 'logins':

            $where_clauses[] = "sensfrx_log_type LIKE '%Account Security%'";

            break;

        case 'emails':

            $where_clauses[] = "sensfrx_log_type LIKE 'Email:%'";

            break;

        case 'bot':

            $where_clauses[] = "sensfrx_log_type LIKE '%Bot%'";

            break;

    }

}



if (!empty($search_query)) {

    $where_clauses[] = $wpdb->prepare(

        "(sensfrx_log1 LIKE %s OR sensfrx_log_type LIKE %s)",

        '%' . $wpdb->esc_like($search_query) . '%',

        '%' . $wpdb->esc_like($search_query) . '%'

    );

}

$where_sql = implode(' AND ', $where_clauses);

$table = esc_sql( $activity_table );

$where = ! empty( $where_sql ) ? "WHERE $where_sql" : '';

// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared -- Table name cannot use placeholders (sanitized with esc_sql()). WHERE clause contains only sanitized hardcoded conditions, no user input.

$sql = "SELECT COUNT(*) FROM {$table} {$where}";

$total_count = (int) $wpdb->get_var( $sql ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Query uses sanitized table name and WHERE clause. See above.

$total_pages = (int) ceil( $total_count / $per_page );



// Get activities with pagination

// Build base query with sanitized table name and WHERE clause (cannot be prepared)

// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name cannot use placeholders (sanitized with esc_sql()). WHERE clause contains only sanitized hardcoded conditions, no user input.

$base_query = "SELECT * FROM {$table} {$where} ORDER BY id DESC";

// Use prepare() only for LIMIT/OFFSET values (which can be prepared)

// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared -- $base_query uses sanitized table name and WHERE clause (see ignore above). Only LIMIT/OFFSET values are being prepared here.

$sql = $wpdb->prepare(

    $base_query . " LIMIT %d OFFSET %d", // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- $base_query contains sanitized table name and WHERE clause. Only LIMIT/OFFSET values are being prepared.

    $per_page,

    $offset

);



$activities = $wpdb->get_results( $sql, ARRAY_A ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Query is prepared for LIMIT/OFFSET values above. Base query uses sanitized table name and WHERE clause.



// Calculate stats (cached for 5 minutes to improve performance)

$stats_cache_key = 'sensfrx_activity_stats_' . md5($where_sql);

$stats = wp_cache_get($stats_cache_key);



if (false === $stats) {

    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared -- Table name cannot use placeholders (sanitized with esc_sql()). WHERE clause contains only sanitized hardcoded conditions, no user input.

    $email_sql = "SELECT COUNT(*) FROM {$table} {$where} AND sensfrx_log_type LIKE 'Email:%'";

    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared -- Table name cannot use placeholders (sanitized with esc_sql()). WHERE clause contains only sanitized hardcoded conditions, no user input.

    $order_sql = "SELECT COUNT(*) FROM {$table} {$where} AND (sensfrx_log_type LIKE '%Transaction%' OR sensfrx_log_type LIKE '%Order%')";

    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared -- Table name cannot use placeholders (sanitized with esc_sql()). WHERE clause contains only sanitized hardcoded conditions, no user input.

    $login_sql = "SELECT COUNT(*) FROM {$table} {$where} AND sensfrx_log_type LIKE '%Account Security%'";

    

    $stats = array(

        'total' => (int) $total_count,

        'email' => (int) $wpdb->get_var( $email_sql ), // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Query uses sanitized table name and WHERE clause. See phpcs:ignore above where $email_sql is defined.

        'order' => (int) $wpdb->get_var( $order_sql ), // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Query uses sanitized table name and WHERE clause. See phpcs:ignore above where $order_sql is defined.

        'login' => (int) $wpdb->get_var( $login_sql ), // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Query uses sanitized table name and WHERE clause. See phpcs:ignore above where $login_sql is defined.

    );

    wp_cache_set($stats_cache_key, $stats, '', 300); // Cache for 5 minutes

}



$email_count = $stats['email'];

$order_count = $stats['order'];

$login_count = $stats['login'];

?>



<div class="sensfrx-enterprise-wrapper">

    <!-- Navigation Tabs -->

    <?php require_once(SENSFRX_DIR . 'admin/partials/sensfrx-navigation.php'); ?>



    <!-- Main Content -->

    <div class="sensfrx-enterprise-dashboard">

        <!-- Page Header -->

        <div class="sensfrx-activity-header">

            <div>

                <h1 class="sensfrx-page-title">Activity Logs</h1>

                <p class="sensfrx-page-subtitle">Everything happening in your store - orders, logins, emails, and security events</p>

            </div>

            <div class="sensfrx-header-actions">

                <button type="button" onclick="location.reload()" class="sensfrx-refresh-btn">

                    <svg width="16" height="16" viewBox="0 0 16 16" fill="none">

                        <path d="M13.65 2.35A7.95 7.95 0 004 1v2.5m0 9a6 6 0 008.65 1.15M2.35 13.65A7.95 7.95 0 0012 15v-2.5m0-9a6 6 0 00-8.65-1.15" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>

                    </svg>

                    Refresh

                </button>

            </div>

        </div>



        <!-- Stats Overview -->

        <div class="sensfrx-stats-grid">

            <div class="sensfrx-stat-card">

                <div class="sensfrx-stat-icon" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">

                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none">

                        <path d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                    </svg>

                </div>

                <div class="sensfrx-stat-content">

                    <div class="sensfrx-stat-label">Total Events</div>

                    <div class="sensfrx-stat-value"><?php echo number_format($total_count); ?></div>

                    <div class="sensfrx-stat-trend">All activity tracked</div>

                </div>

            </div>



            <div class="sensfrx-stat-card">

                <div class="sensfrx-stat-icon" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">

                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none">

                        <path d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                    </svg>

                </div>

                <div class="sensfrx-stat-content">

                    <div class="sensfrx-stat-label">Emails Sent</div>

                    <div class="sensfrx-stat-value"><?php echo number_format($email_count); ?></div>

                    <div class="sensfrx-stat-trend">Customer notifications</div>

                </div>

            </div>



            <div class="sensfrx-stat-card">

                <div class="sensfrx-stat-icon" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">

                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none">

                        <path d="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                    </svg>

                </div>

                <div class="sensfrx-stat-content">

                    <div class="sensfrx-stat-label">Order Activity</div>

                    <div class="sensfrx-stat-value"><?php echo number_format($order_count); ?></div>

                    <div class="sensfrx-stat-trend">Transactions processed</div>

                </div>

            </div>



            <div class="sensfrx-stat-card">

                <div class="sensfrx-stat-icon" style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);">

                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none">

                        <path d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                    </svg>

                </div>

                <div class="sensfrx-stat-content">

                    <div class="sensfrx-stat-label">Login Attempts</div>

                    <div class="sensfrx-stat-value"><?php echo number_format($login_count); ?></div>

                    <div class="sensfrx-stat-trend">Security checks</div>

                </div>

            </div>

        </div>



        <!-- Filters Section -->

        <div class="sensfrx-filters-section">

            <form method="get" action="" class="sensfrx-filters-form">

                <input type="hidden" name="page" value="sensfrx_fpwoo">

                <input type="hidden" name="tab" value="activity">



                <div class="sensfrx-filter-search">

                    <svg width="20" height="20" viewBox="0 0 20 20" fill="none" class="sensfrx-search-icon">

                        <path d="M9 17A8 8 0 109 1a8 8 0 000 16zM19 19l-4.35-4.35" stroke="#9ca3af" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                    </svg>

                    <input

                        type="text"

                        name="search"

                        value="<?php echo esc_attr($search_query); ?>"

                        placeholder="Search by email, order, or activity..."

                        class="sensfrx-search-input"

                    />

                </div>



                <div class="sensfrx-filter-tabs">

                    <a href="?page=sensfrx_fpwoo&tab=activity&activity_type=all<?php echo $search_query ? '&search=' . urlencode($search_query) : ''; ?>"

                       class="sensfrx-filter-tab <?php echo $filter_type === 'all' ? 'active' : ''; ?>">

                        All Activity

                    </a>

                    <a href="?page=sensfrx_fpwoo&tab=activity&activity_type=orders<?php echo $search_query ? '&search=' . urlencode($search_query) : ''; ?>"

                       class="sensfrx-filter-tab <?php echo $filter_type === 'orders' ? 'active' : ''; ?>">

                        Orders

                    </a>

                    <a href="?page=sensfrx_fpwoo&tab=activity&activity_type=emails<?php echo $search_query ? '&search=' . urlencode($search_query) : ''; ?>"

                       class="sensfrx-filter-tab <?php echo $filter_type === 'emails' ? 'active' : ''; ?>">

                        Emails

                    </a>

                    <a href="?page=sensfrx_fpwoo&tab=activity&activity_type=logins<?php echo $search_query ? '&search=' . urlencode($search_query) : ''; ?>"

                       class="sensfrx-filter-tab <?php echo $filter_type === 'logins' ? 'active' : ''; ?>">

                        Logins

                    </a>

                    <a href="?page=sensfrx_fpwoo&tab=activity&activity_type=bot<?php echo $search_query ? '&search=' . urlencode($search_query) : ''; ?>"

                       class="sensfrx-filter-tab <?php echo $filter_type === 'bot' ? 'active' : ''; ?>">

                        Bot Protection

                    </a>

                </div>



                <button type="submit" class="sensfrx-filter-submit">Apply</button>

            </form>

        </div>



        <!-- Activity Timeline -->

        <div class="sensfrx-activity-timeline">

            <?php if (empty($activities)): ?>

                <div class="sensfrx-empty-state">

                    <svg width="120" height="120" viewBox="0 0 120 120" fill="none">

                        <circle cx="60" cy="60" r="50" fill="#f3f4f6"/>

                        <path d="M60 35v50M35 60h50" stroke="#d1d5db" stroke-width="4" stroke-linecap="round"/>

                    </svg>

                    <h3>No Activity Found</h3>

                    <p>Try adjusting your filters or search terms to see more results.</p>

                </div>

            <?php else: ?>

                <?php foreach ($activities as $activity):

                    // Parse activity details

                    preg_match('/([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/', $activity['sensfrx_log1'], $email_matches);

                    $user_email = !empty($email_matches[1]) ? $email_matches[1] : 'Unknown';



                    preg_match('/Order #(\d+)/', $activity['sensfrx_log1'], $order_matches);

                    $order_id = !empty($order_matches[1]) ? $order_matches[1] : null;



                    // Determine activity icon and color

                    $activity_type = $activity['sensfrx_log_type'];

                    $icon_color = '#6366f1'; // Default blue

                    $icon_html = '<circle cx="12" cy="12" r="8" fill="white" stroke="currentColor" stroke-width="2"/>';



                    if (strpos($activity_type, 'Email') !== false) {

                        $icon_color = '#ec4899';

                        $icon_html = '<path d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" stroke="currentColor" stroke-width="2" fill="none"/>';

                    } elseif (strpos($activity_type, 'Transaction') !== false || strpos($activity_type, 'Order') !== false) {

                        $icon_color = '#10b981';

                        $icon_html = '<path d="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z" stroke="currentColor" stroke-width="2" fill="none"/>';

                    } elseif (strpos($activity_type, 'Account') !== false) {

                        $icon_color = '#f59e0b';

                        $icon_html = '<path d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" stroke="currentColor" stroke-width="2" fill="none"/>';

                    } elseif (strpos($activity_type, 'Bot') !== false) {

                        $icon_color = '#8b5cf6';

                        $icon_html = '<path d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" stroke="currentColor" stroke-width="2" fill="none"/>';

                    }



                    // Extract risk level from message

                    $risk_badge = '';

                    if (strpos($activity['sensfrx_log1'], 'low risk') !== false) {

                        $risk_badge = '<span class="sensfrx-risk-badge sensfrx-risk-low">Low Risk</span>';

                    } elseif (strpos($activity['sensfrx_log1'], 'medium risk') !== false) {

                        $risk_badge = '<span class="sensfrx-risk-badge sensfrx-risk-medium">Medium Risk</span>';

                    } elseif (strpos($activity['sensfrx_log1'], 'critical risk') !== false || strpos($activity['sensfrx_log1'], 'high risk') !== false) {

                        $risk_badge = '<span class="sensfrx-risk-badge sensfrx-risk-high">High Risk</span>';

                    }



                    // Extract action (allowed/blocked)

                    $action_badge = '';

                    if (strpos($activity['sensfrx_log1'], 'was allowed') !== false || strpos($activity['sensfrx_log1'], 'approved') !== false || strpos($activity['sensfrx_log1'], 'succeeded') !== false) {

                        $action_badge = '<span class="sensfrx-action-badge sensfrx-action-allowed">✓ Allowed</span>';

                    } elseif (strpos($activity['sensfrx_log1'], 'blocked') !== false || strpos($activity['sensfrx_log1'], 'denied') !== false) {

                        $action_badge = '<span class="sensfrx-action-badge sensfrx-action-blocked">✕ Blocked</span>';

                    }

                ?>

                <div class="sensfrx-timeline-item">

                    <div class="sensfrx-timeline-icon" style="background: <?php echo esc_attr( $icon_color ); ?>;">

                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none">

                            <?php echo $icon_html; ?>

                        </svg>

                    </div>

                    <div class="sensfrx-timeline-content">

                        <div class="sensfrx-timeline-header">

                            <div class="sensfrx-timeline-title">

                                <strong><?php echo esc_html($activity_type); ?></strong>

                                <?php if ($order_id): ?>

                                    <a href="<?php echo esc_url( admin_url( 'post.php?post=' . absint( $order_id ) . '&action=edit' ) ); ?>" class="sensfrx-order-link" >

                                        Order #<?php echo esc_html($order_id); ?>

                                    </a>

                                <?php endif; ?>

                            </div>

                            <div class="sensfrx-timeline-time">

                                <?php 

                                // created_at is stored as UTC, convert to local timezone

                                

                                // Get WordPress timezone

                                $wp_timezone = wp_timezone();

                                

                                // Try parsing as UTC first (NEW format)

                                $datetime_utc = new DateTime($activity['created_at'], new DateTimeZone('UTC'));

                                $datetime_utc->setTimezone($wp_timezone);

                                $timestamp_if_utc = $datetime_utc->getTimestamp();

                                

                                // Also try parsing as local time (OLD format)

                                $datetime_local = new DateTime($activity['created_at'], $wp_timezone);

                                $timestamp_if_local = $datetime_local->getTimestamp();

                                

                                // Get current time

                                $current_timestamp = time();

                                

                                // Smart detection: If UTC interpretation gives negative time or very far future, use local

                                $diff_utc = $current_timestamp - $timestamp_if_utc;

                                $diff_local = $current_timestamp - $timestamp_if_local;

                                

                                // Use local interpretation if UTC is clearly wrong (negative or > 1 hour in future)

                                if ($diff_utc < -3600) {

                                    // UTC interpretation gives future time - must be stored as local

                                    $timestamp = $timestamp_if_local;

                                    $diff_seconds = $diff_local;

                                    $datetime_final = $datetime_local;

                                } else {

                                    // UTC interpretation is reasonable - use it

                                    $timestamp = $timestamp_if_utc;

                                    $diff_seconds = $diff_utc;

                                    $datetime_final = $datetime_utc;

                                }

                                

                                // Format date for tooltip using DateTime object (already in local timezone)

                                // Use a simple format that works: "December 11, 2025 7:44 PM"

                                $formatted_date = $datetime_final->format('F j, Y g:i A');

                                

                                // Smart time display logic

                                if ($diff_seconds < 0) {

                                    // Handle negative differences (future timestamps - shouldn't happen)

                                    $display_time = 'Just now';

                                } elseif ($diff_seconds < 60) {

                                    // Less than 1 minute - show "Just now"

                                    $display_time = 'Just now';

                                } elseif ($diff_seconds < 3600) {

                                    // Less than 1 hour - show minutes

                                    $minutes = floor($diff_seconds / 60);

                                    $display_time = $minutes . ' ' . ($minutes == 1 ? 'minute' : 'minutes') . ' ago';

                                } elseif ($diff_seconds < 86400) {

                                    // Less than 24 hours - show hours

                                    $hours = floor($diff_seconds / 3600);

                                    $display_time = $hours . ' ' . ($hours == 1 ? 'hour' : 'hours') . ' ago';

                                } elseif ($diff_seconds < 172800) {

                                    // Between 24-48 hours - show "Yesterday"

                                    $display_time = 'Yesterday';

                                } else {

                                    // Greater than 48 hours - show full date (no "ago")

                                    $display_time = date_i18n(get_option('date_format'), $timestamp);

                                }

                                ?>

                                <span class="sensfrx-time-tooltip" title="<?php echo esc_attr($formatted_date); ?>">

                                    <?php echo esc_html($display_time); ?>

                                </span>

                            </div>

                        </div>

                        <div class="sensfrx-timeline-description">

                            <?php echo esc_html($activity['sensfrx_log1']); ?>

                        </div>

                        <div class="sensfrx-timeline-meta">

                            <span class="sensfrx-meta-item">

                                <svg width="16" height="16" viewBox="0 0 16 16" fill="none">

                                    <path d="M8 8a3 3 0 100-6 3 3 0 000 6zm0 2c-4 0-6 2-6 4v1h12v-1c0-2-2-4-6-4z" fill="currentColor"/>

                                </svg>

                                <?php echo esc_html($user_email); ?>

                            </span>

                            <?php if ($risk_badge): ?>

                                <?php echo wp_kses_post( $risk_badge ); ?>

                            <?php endif; ?>

                            <?php if ($action_badge): ?>

                                <?php echo wp_kses_post ( $action_badge ); ?>

                            <?php endif; ?>

                        </div>

                    </div>

                </div>

                <?php endforeach; ?>

            <?php endif; ?>

        </div>



        <!-- Pagination -->

        <?php if (!empty($activities)): ?>

        <div class="sensfrx-pagination-wrapper">

            <div class="sensfrx-pagination-info">

                <span class="sensfrx-results-count">

                    Showing <?php echo number_format(($offset + 1)); ?>-<?php echo number_format(min($offset + $per_page, $total_count)); ?>

                    of <?php echo number_format($total_count); ?> events

                </span>



                <div class="sensfrx-per-page-selector">

                    <label for="per-page-select">Show:</label>

                    <select id="per-page-select">

                        <option value="10" <?php selected($per_page, 10); ?>>10</option>

                        <option value="25" <?php selected($per_page, 25); ?>>25</option>

                        <option value="50" <?php selected($per_page, 50); ?>>50</option>

                        <option value="100" <?php selected($per_page, 100); ?>>100</option>

                    </select>

                    <span>per page</span>

                </div>

            </div>



            <?php if ($total_pages > 1): ?>

            <div class="sensfrx-pagination-controls">

                <?php

                $base_url = add_query_arg(array(

                    'page' => 'sensfrx_fpwoo',

                    'tab' => 'activity',

                    'activity_type' => $filter_type,

                    'search' => $search_query,

                    'per_page' => $per_page

                ), admin_url('admin.php'));



                // First page

                if ($current_page > 1):

                ?>

                    <a href="<?php echo esc_url(add_query_arg('paged', 1, $base_url)); ?>" class="sensfrx-page-btn sensfrx-page-first">

                        <svg width="16" height="16" viewBox="0 0 16 16" fill="none">

                            <path d="M11 13l-5-5 5-5M6 13V3" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                        </svg>

                    </a>

                    <a href="<?php echo esc_url(add_query_arg('paged', $current_page - 1, $base_url)); ?>" class="sensfrx-page-btn sensfrx-page-prev">

                        <svg width="16" height="16" viewBox="0 0 16 16" fill="none">

                            <path d="M10 13l-5-5 5-5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                        </svg>

                        Previous

                    </a>

                <?php endif; ?>



                <!-- Page numbers -->

                <div class="sensfrx-page-numbers">

                    <?php

                    $range = 2; // Show 2 pages before and after current

                    $start_page = max(1, $current_page - $range);

                    $end_page = min($total_pages, $current_page + $range);



                    if ($start_page > 1) {

                        echo '<a href="' . esc_url(add_query_arg('paged', 1, $base_url)) . '" class="sensfrx-page-num">1</a>';

                        if ($start_page > 2) {

                            echo '<span class="sensfrx-page-dots">...</span>';

                        }

                    }



                    for ($i = $start_page; $i <= $end_page; $i++) {

                        if ($i == $current_page) {

                            echo '<span class="sensfrx-page-num active">' . esc_html( $i ) . '</span>';

                        } else {

                            echo '<a href="' . esc_url(add_query_arg('paged', $i, $base_url)) . '" class="sensfrx-page-num">' . esc_html( $i ) . '</a>';

                        }

                    }



                    if ($end_page < $total_pages) {

                        if ($end_page < $total_pages - 1) {

                            echo '<span class="sensfrx-page-dots">...</span>';

                        }

                        echo '<a href="' . esc_url(add_query_arg('paged', $total_pages, $base_url)) . '" class="sensfrx-page-num">' . absint( $total_pages ) . '</a>';

                    }

                    ?>

                </div>



                <?php if ($current_page < $total_pages): ?>

                    <a href="<?php echo esc_url(add_query_arg('paged', $current_page + 1, $base_url)); ?>" class="sensfrx-page-btn sensfrx-page-next">

                        Next

                        <svg width="16" height="16" viewBox="0 0 16 16" fill="none">

                            <path d="M6 13l5-5-5-5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                        </svg>

                    </a>

                    <a href="<?php echo esc_url(add_query_arg('paged', $total_pages, $base_url)); ?>" class="sensfrx-page-btn sensfrx-page-last">

                        <svg width="16" height="16" viewBox="0 0 16 16" fill="none">

                            <path d="M5 13l5-5-5-5M10 13V3" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                        </svg>

                    </a>

                <?php endif; ?>

            </div>

            <?php endif; ?>

        </div>

        <?php endif; ?>

    </div>

</div>



<script>

    jQuery(document).ready(function($) {

        const restUrl = '<?php echo esc_url(rest_url('sensfrx-fraud-prevention-for-woocommerce/')); ?>';

        

        // Handle per-page dropdown change

        $('#per-page-select').on('change', function() {

            const perPage = $(this).val();

            const url = new URL(window.location.href);

            url.searchParams.set('per_page', perPage);

            url.searchParams.set('paged', '1'); // Reset to first page

            window.location.href = url.toString();

        });

        

        // Fetch review count for badge

        fetch(restUrl + 'get_sensfrx_review_count', {

            method: 'GET',

            headers: {

                'Content-Type': 'application/json'

            }

        })

        .then(response => response.json())

        .then(data => {

            if (data.status === 'success') {

                const badge = document.querySelector('.sensfrx-nav-badge');

                if (badge) {

                    badge.textContent = data.reviewCount || 0;

                }

            }

        })

        .catch(error => console.error('Error fetching review count:', error));



    });

    

</script>



<style>

/* Page Header */

.sensfrx-activity-header {

    display: flex;

    justify-content: space-between;

    align-items: flex-start;

    margin-bottom: 32px;

    padding-bottom: 24px;

    border-bottom: 2px solid #f3f4f6;

}



.sensfrx-header-actions {

    display: flex;

    gap: 12px;

}



.sensfrx-refresh-btn {

    display: flex;

    align-items: center;

    gap: 8px;

    padding: 10px 18px;

    background: white;

    border: 2px solid #e5e7eb;

    border-radius: 8px;

    font-size: 14px;

    font-weight: 600;

    color: #374151;

    cursor: pointer;

    transition: all 0.2s ease;

}



.sensfrx-refresh-btn:hover {

    background: #f9fafb;

    border-color: #d1d5db;

}



/* Stats Grid */

.sensfrx-stats-grid {

    display: grid;

    grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));

    gap: 20px;

    margin-bottom: 32px;

}



.sensfrx-stat-card {

    background: white;

    border-radius: 16px;

    padding: 24px;

    display: flex;

    gap: 16px;

    box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);

    transition: all 0.3s ease;

}



.sensfrx-stat-card:hover {

    box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);

    transform: translateY(-2px);

}



.sensfrx-stat-icon {

    width: 56px;

    height: 56px;

    border-radius: 12px;

    display: flex;

    align-items: center;

    justify-content: center;

    flex-shrink: 0;

}



.sensfrx-stat-content {

    flex: 1;

}



.sensfrx-stat-label {

    font-size: 13px;

    color: #6b7280;

    font-weight: 600;

    text-transform: uppercase;

    letter-spacing: 0.5px;

    margin-bottom: 4px;

}



.sensfrx-stat-value {

    font-size: 32px;

    font-weight: 700;

    color: #111827;

    line-height: 1;

    margin-bottom: 4px;

}



.sensfrx-stat-trend {

    font-size: 13px;

    color: #9ca3af;

}



/* Filters Section */

.sensfrx-filters-section {

    background: white;

    border-radius: 12px;

    padding: 20px;

    margin-bottom: 24px;

    box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);

}



.sensfrx-filters-form {

    display: flex;

    gap: 16px;

    align-items: center;

    flex-wrap: wrap;

}



.sensfrx-filter-search {

    position: relative;

    flex: 1;

    min-width: 300px;

}



.sensfrx-search-icon {

    position: absolute;

    left: 14px;

    top: 50%;

    transform: translateY(-50%);

    pointer-events: none;

}



/* Override WordPress default input styles */

input[type="text"].sensfrx-search-input {

    width: 100% !important;

    padding: 12px 16px 12px 44px !important;

    border: 2px solid #e5e7eb !important;

    border-radius: 8px !important;

    font-size: 14px !important;

    transition: all 0.2s ease !important;

    height: auto !important;

    line-height: normal !important;

    box-sizing: border-box !important;

}



input[type="text"].sensfrx-search-input:focus {

    outline: none !important;

    border-color: #0254ff !important;

    box-shadow: 0 0 0 3px rgba(2, 84, 255, 0.1) !important;

}



.sensfrx-filter-tabs {

    display: flex;

    gap: 8px;

    background: #f9fafb;

    padding: 4px;

    border-radius: 8px;

}



.sensfrx-filter-tab {

    padding: 8px 16px;

    border-radius: 6px;

    font-size: 14px;

    font-weight: 600;

    color: #6b7280;

    text-decoration: none;

    transition: all 0.2s ease;

    white-space: nowrap;

}



.sensfrx-filter-tab:hover {

    background: white;

    color: #374151;

}



.sensfrx-filter-tab.active {

    background: #0254ff;

    color: white;

    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);

}



.sensfrx-filter-submit {

    padding: 12px 24px;

    background: #047857;

    color: white;

    border: none;

    border-radius: 8px;

    font-size: 14px;

    font-weight: 600;

    cursor: pointer;

    transition: all 0.2s ease;

}



.sensfrx-filter-submit:hover {

    background: #065f46;

}



/* Activity Timeline */

.sensfrx-activity-timeline {

    background: white;

    border-radius: 12px;

    padding: 24px;

    box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);

}



.sensfrx-timeline-item {

    display: flex;

    gap: 20px;

    padding-bottom: 24px;

    margin-bottom: 24px;

    border-bottom: 1px solid #f3f4f6;

}



.sensfrx-timeline-item:last-child {

    border-bottom: none;

    margin-bottom: 0;

    padding-bottom: 0;

}



.sensfrx-timeline-icon {

    width: 48px;

    height: 48px;

    border-radius: 12px;

    display: flex;

    align-items: center;

    justify-content: center;

    flex-shrink: 0;

    color: white;

}



.sensfrx-timeline-content {

    flex: 1;

}



.sensfrx-timeline-header {

    display: flex;

    justify-content: space-between;

    align-items: flex-start;

    margin-bottom: 8px;

    gap: 16px;

}



.sensfrx-timeline-title {

    font-size: 16px;

    color: #111827;

    font-weight: 600;

    display: flex;

    align-items: center;

    gap: 12px;

    flex-wrap: wrap;

}



.sensfrx-order-link {

    color: #0254ff;

    text-decoration: none;

    font-weight: 600;

    font-size: 14px;

}



.sensfrx-order-link:hover {

    text-decoration: underline;

}



.sensfrx-timeline-time {

    font-size: 13px;

    color: #9ca3af;

    white-space: nowrap;

}



/* Tooltip styling for time display */

.sensfrx-time-tooltip {

    cursor: help;

    border-bottom: 1px dotted #9ca3af;

    position: relative;

}



.sensfrx-time-tooltip:hover {

    color: #047857;

    border-bottom-color: #047857;

}



.sensfrx-timeline-description {

    font-size: 14px;

    color: #6b7280;

    line-height: 1.6;

    margin-bottom: 12px;

}



.sensfrx-timeline-meta {

    display: flex;

    align-items: center;

    gap: 12px;

    flex-wrap: wrap;

}



.sensfrx-meta-item {

    display: flex;

    align-items: center;

    gap: 6px;

    font-size: 13px;

    color: #6b7280;

}



.sensfrx-meta-item svg {

    color: #9ca3af;

}



/* Risk Badges */

.sensfrx-risk-badge {

    display: inline-block;

    padding: 4px 10px;

    border-radius: 6px;

    font-size: 11px;

    font-weight: 600;

}



.sensfrx-risk-low {

    background: #d1fae5;

    color: #065f46;

}



.sensfrx-risk-medium {

    background: #fef3c7;

    color: #92400e;

}



.sensfrx-risk-high {

    background: #fee2e2;

    color: #991b1b;

}



/* Action Badges */

.sensfrx-action-badge {

    display: inline-block;

    padding: 4px 10px;

    border-radius: 6px;

    font-size: 11px;

    font-weight: 600;

}



.sensfrx-action-allowed {

    background: #d1fae5;

    color: #065f46;

}



.sensfrx-action-blocked {

    background: #fee2e2;

    color: #991b1b;

}



/* Empty State */

.sensfrx-empty-state {

    text-align: center;

    padding: 80px 20px;

}



.sensfrx-empty-state h3 {

    margin: 24px 0 8px;

    font-size: 20px;

    font-weight: 600;

    color: #111827;

}



.sensfrx-empty-state p {

    margin: 0;

    font-size: 14px;

    color: #6b7280;

}



/* Load More */

.sensfrx-load-more {

    text-align: center;

    padding: 20px;

    margin-top: 24px;

    background: #f9fafb;

    border-radius: 8px;

}



.sensfrx-load-more p {

    margin: 0;

    font-size: 14px;

    color: #6b7280;

}



/* Pagination */

.sensfrx-pagination-wrapper {

    background: white;

    border-radius: 12px;

    padding: 20px 24px;

    margin-top: 24px;

    box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);

}



.sensfrx-pagination-info {

    display: flex;

    justify-content: space-between;

    align-items: center;

    margin-bottom: 20px;

    padding-bottom: 16px;

    border-bottom: 1px solid #f3f4f6;

}



.sensfrx-results-count {

    font-size: 14px;

    color: #6b7280;

    font-weight: 600;

}



.sensfrx-per-page-selector {

    display: flex;

    align-items: center;

    gap: 8px;

    font-size: 14px;

    color: #6b7280;

}



.sensfrx-per-page-selector label {

    font-weight: 600;

}



.sensfrx-per-page-selector select {

    padding: 6px 32px 6px 12px;

    border: 2px solid #e5e7eb;

    border-radius: 6px;

    font-size: 14px;

    font-weight: 600;

    color: #374151;

    background: white;

    cursor: pointer;

    transition: all 0.2s ease;

}



.sensfrx-per-page-selector select:focus {

    outline: none;

    border-color: #0254ff;

    box-shadow: 0 0 0 3px rgba(2, 84, 255, 0.1);

}



.sensfrx-pagination-controls {

    display: flex;

    align-items: center;

    justify-content: center;

    gap: 8px;

}



.sensfrx-page-btn {

    display: flex;

    align-items: center;

    gap: 6px;

    padding: 8px 14px;

    background: white;

    border: 2px solid #e5e7eb;

    border-radius: 8px;

    font-size: 14px;

    font-weight: 600;

    color: #374151;

    text-decoration: none;

    transition: all 0.2s ease;

}



.sensfrx-page-btn:hover {

    background: #f9fafb;

    border-color: #0254ff;

    color: #0254ff;

}



.sensfrx-page-btn svg {

    flex-shrink: 0;

}



.sensfrx-page-first,

.sensfrx-page-last {

    padding: 8px 10px;

}



.sensfrx-page-numbers {

    display: flex;

    align-items: center;

    gap: 4px;

    margin: 0 8px;

}



.sensfrx-page-num {

    display: flex;

    align-items: center;

    justify-content: center;

    min-width: 40px;

    height: 40px;

    padding: 0 8px;

    background: white;

    border: 2px solid #e5e7eb;

    border-radius: 8px;

    font-size: 14px;

    font-weight: 600;

    color: #374151;

    text-decoration: none;

    transition: all 0.2s ease;

}



.sensfrx-page-num:hover {

    background: #f9fafb;

    border-color: #0254ff;

    color: #0254ff;

}



.sensfrx-page-num.active {

    background: #0254ff;

    border-color: #0254ff;

    color: white;

    cursor: default;

}



.sensfrx-page-dots {

    padding: 0 8px;

    color: #9ca3af;

    font-weight: 600;

}



/* Responsive */

@media (max-width: 768px) {

    .sensfrx-activity-header {

        flex-direction: column;

        gap: 16px;

    }



    .sensfrx-filters-form {

        flex-direction: column;

        align-items: stretch;

    }



    .sensfrx-filter-search {

        min-width: 100%;

    }



    .sensfrx-filter-tabs {

        overflow-x: auto;

        -webkit-overflow-scrolling: touch;

    }



    .sensfrx-timeline-header {

        flex-direction: column;

        align-items: flex-start;

        gap: 8px;

    }



    .sensfrx-pagination-info {

        flex-direction: column;

        align-items: flex-start;

        gap: 12px;

    }



    .sensfrx-pagination-controls {

        flex-wrap: wrap;

    }



    .sensfrx-page-numbers {

        overflow-x: auto;

        -webkit-overflow-scrolling: touch;

    }

}

</style>

