<?php
/**
 * Sentinel Admin Page View
 * 
 * Main admin interface for viewing logs.
 */

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

global $wpdb;
$table = $wpdb->prefix . 'sentinel_logs';

// Get today's date range
$today_start = date('Y-m-d 00:00:00');
$today_end = date('Y-m-d 23:59:59');

// Role-based filtering for editors (only if enabled in settings)
$is_editor = current_user_can('edit_published_posts') && !current_user_can('manage_options');
$category_filter = '';

// Check if role-based log access is enabled in settings
$settings = get_option('sentinel_log_management', array());
// Remove IP whitelist enforcement logic
$role_based_access_enabled = !empty($settings['role_based_access']);

if ($is_editor && $role_based_access_enabled) {
    $category_filter = "AND category IN ('user', 'content', 'authentication')";
}

// Get today's stats
$today_logs = $wpdb->get_var($wpdb->prepare(
    "SELECT COUNT(*) FROM $table WHERE created_at BETWEEN %s AND %s $category_filter",
    $today_start, $today_end
));

$today_users = $wpdb->get_var($wpdb->prepare(
    "SELECT COUNT(DISTINCT user_id) FROM $table WHERE created_at BETWEEN %s AND %s AND user_id > 0 $category_filter",
    $today_start, $today_end
));

$top_event_today = $wpdb->get_row($wpdb->prepare(
    "SELECT event_key, COUNT(*) as count FROM $table 
     WHERE created_at BETWEEN %s AND %s $category_filter
     GROUP BY event_key 
     ORDER BY count DESC 
     LIMIT 1",
    $today_start, $today_end
));

// Get system info
$db_size = $wpdb->get_var("SELECT ROUND(((data_length + index_length) / 1024 / 1024), 2) AS 'DB Size in MB' FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = '$table'");

// Get last 7 days activity for chart
$last_7_days = array();
for ($i = 6; $i >= 0; $i--) {
    $date = date('Y-m-d', strtotime("-$i days"));
    $start = $date . ' 00:00:00';
    $end = $date . ' 23:59:59';
    $count = $wpdb->get_var($wpdb->prepare(
        "SELECT COUNT(*) FROM $table WHERE created_at BETWEEN %s AND %s $category_filter",
        $start, $end
    ));
    $last_7_days[] = array(
        'date' => date('M j', strtotime($date)),
        'count' => intval($count)
    );
}

// Get event distribution (last 7 days)
$event_distribution_raw = $wpdb->get_results(
    "SELECT event_key, COUNT(*) as count FROM $table 
     WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) $category_filter
     GROUP BY event_key 
     ORDER BY count DESC 
     LIMIT 10"
);
$event_distribution = array();
foreach ($event_distribution_raw as $row) {
    $event_distribution[] = array(
        'event_key' => $row->event_key,
        'count' => intval($row->count)
    );
}

// Get error event distribution (last 7 days) - Only for admins
$error_distribution_raw = array();
if (!$is_editor) {
    $error_distribution_raw = $wpdb->get_results(
        "SELECT event_key, COUNT(*) as count FROM $table 
         WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
         AND (event_key LIKE '%error%' OR event_key LIKE '%failed%' OR event_key IN (
             'php_fatal_error', 'php_warning', 'php_notice', 'php_deprecated',
             'wp_database_error', 'wp_memory_error', 'wp_permission_error', 'wp_config_error',
             'login_failed', 'auth_cookie_bad', 'nonce_verification_failed', 'permission_denied',
             'http_404_error', 'http_500_error', 'wp_remote_error', 'wp_cron_error',
             'plugin_error', 'theme_error', 'plugin_activation_error',
             'file_upload_error', 'file_permission_error'
         ))
         GROUP BY event_key 
         ORDER BY count DESC 
         LIMIT 10"
    );
}
$error_distribution = array();
foreach ($error_distribution_raw as $row) {
    $error_distribution[] = array(
        'event_key' => $row->event_key,
        'count' => intval($row->count)
    );
}

// Get recent activity (last 10 events)
$recent_activity = $wpdb->get_results(
    "SELECT * FROM $table 
     WHERE 1=1 $category_filter
     ORDER BY created_at DESC 
     LIMIT 10"
);
// Get usernames for display
$user_ids = array();
foreach ($recent_activity as $activity) {
    if ($activity->user_id > 0) {
        $user_ids[] = $activity->user_id;
    }
}
$user_ids = array_unique($user_ids);
$usernames = array();
if ($user_ids) {
    $placeholders = implode(',', array_fill(0, count($user_ids), '%d'));
    $users_data = $wpdb->get_results($wpdb->prepare(
        "SELECT ID, user_login, display_name FROM {$wpdb->users} WHERE ID IN ($placeholders)",
        $user_ids
    ));
    foreach ($users_data as $u) {
        $usernames[$u->ID] = $u->display_name ?: $u->user_login;
    }
}
$usernames[0] = 'Guest/Anonymous';

// Get hourly activity for the last 7 days (for heatmap)
$heatmap_data = array();
for ($i = 6; $i >= 0; $i--) {
    $date = date('Y-m-d', strtotime("-$i days"));
    $row = array('date' => $date, 'hours' => array_fill(0, 24, 0));
    $results = $wpdb->get_results($wpdb->prepare(
        "SELECT HOUR(created_at) as hour, COUNT(*) as count FROM $table WHERE created_at BETWEEN %s AND %s $category_filter GROUP BY hour",
        $date . ' 00:00:00', $date . ' 23:59:59'
    ));
    foreach ($results as $result) {
        $row['hours'][intval($result->hour)] = intval($result->count);
    }
    $heatmap_data[] = $row;
}
?>

<div class="wrap">
    <div class="sentinel-dashboard">
        <div class="sentinel-logo">
            <div class="sentinel-logo-card">
                <img src="<?php echo plugins_url('assets/img/Logo.png', dirname(__FILE__, 2)); ?>" alt="Sentinel Logo"
                    height="80" />
            </div>
        </div>
        <h1 class="sentinel-dashboard-title">Sentinel Dashboard</h1>



        <?php if (isset($_GET['logs_cleared'])): ?>
        <div class="notice notice-success is-dismissible">
            <p><?php echo intval($_GET['logs_cleared']); ?> old log entries have been cleared successfully.</p>
        </div>
        <?php endif; ?>

        <?php if (isset($_GET['test_data_generated'])): ?>
        <div class="notice notice-success is-dismissible">
            <p><?php echo intval($_GET['test_data_generated']); ?> test log entries have been generated successfully.
            </p>
        </div>
        <?php endif; ?>

        <!-- Overview Stats -->
        <div class="sentinel-stats-grid">
            <div class="sentinel-stat-card">
                <div class="sentinel-stat-icon">
                    <i class="dashicons dashicons-chart-line"></i>
                </div>
                <div class="sentinel-stat-content">
                    <div class="sentinel-stat-value"><?php echo number_format($today_logs); ?></div>
                    <div class="sentinel-stat-label">Logs Today</div>
                </div>
            </div>
            <div class="sentinel-stat-card">
                <div class="sentinel-stat-icon">
                    <i class="dashicons dashicons-groups"></i>
                </div>
                <div class="sentinel-stat-content">
                    <div class="sentinel-stat-value"><?php echo number_format($today_users); ?></div>
                    <div class="sentinel-stat-label">Active Users Today</div>
                </div>
            </div>
            <div class="sentinel-stat-card">
                <div class="sentinel-stat-icon">
                    <i class="dashicons dashicons-star-filled"></i>
                </div>
                <div class="sentinel-stat-content">
                    <div class="sentinel-stat-value">
                        <?php echo $top_event_today ? esc_html($top_event_today->event_key) : 'None'; ?></div>
                    <div class="sentinel-stat-label">Top Event Today</div>
                </div>
            </div>
            <div class="sentinel-stat-card">
                <div class="sentinel-stat-icon">
                    <i class="dashicons dashicons-database"></i>
                </div>
                <div class="sentinel-stat-content">
                    <div class="sentinel-stat-value"><?php echo $db_size ? $db_size . 'MB' : 'N/A'; ?></div>
                    <div class="sentinel-stat-label">Database Size</div>
                </div>
            </div>
            <div class="sentinel-stat-card">
                <div class="sentinel-stat-icon">
                    <i class="dashicons dashicons-backup"></i>
                </div>
                <div class="sentinel-stat-content">
                    <div class="sentinel-stat-value">30 days</div>
                    <div class="sentinel-stat-label">Retention Policy</div>
                </div>
            </div>
            <div class="sentinel-stat-card sentinel-card--premium">
                <div class="sentinel-stat-icon">
                    <i class="dashicons dashicons-lock"></i>
                </div>
                <div class="sentinel-stat-content">
                    <div class="sentinel-stat-value sentinel-premium-blur">--/--/----</div>
                    <div class="sentinel-stat-label">Oldest Log Date <span class="sentinel-premium-label">Premium</span>
                    </div>
                </div>
                <div class="sentinel-premium-overlay">
                    <span class="dashicons dashicons-lock"></span>
                </div>
            </div>
        </div>
        <!-- Charts Section -->
        <div class="sentinel-charts-section">
            <div class="sentinel-chart-container">
                <h3>Activity Timeline (Last 7 Days)</h3>
                <canvas id="activityChart" width="400" height="200"></canvas>
            </div>
            <div class="sentinel-chart-container">
                <h3>Event Distribution</h3>
                <canvas id="eventChart" width="400" height="200"></canvas>
            </div>
            <?php if (!$is_editor || !$role_based_access_enabled): ?>
            <div class="sentinel-chart-container">
                <h3>Error Distribution (Last 7 Days)</h3>
                <canvas id="errorChart" width="400" height="200"></canvas>
            </div>
            <?php endif; ?>
            <div class="sentinel-chart-container">
                <h3>Hourly Activity Heatmap</h3>
                <canvas id="activityHeatmap" width="400" height="200"></canvas>
            </div>
        </div>
        <!-- Recent Activity Feed -->
        <div class="sentinel-activity-feed">
            <h3>Recent Activity</h3>
            <div class="sentinel-activity-list">
                <?php if ($recent_activity): ?>
                <?php foreach ($recent_activity as $activity): ?>
                <div class="sentinel-activity-item">
                    <div class="sentinel-activity-icon">
                        <i
                            class="dashicons dashicons-<?php echo sentinel_get_activity_icon($activity->event_key); ?>"></i>
                    </div>
                    <div class="sentinel-activity-content">
                        <div class="sentinel-activity-text">
                            <?php echo sentinel_format_activity_message($activity, $usernames); ?>
                        </div>
                        <div class="sentinel-activity-meta">
                            <span class="sentinel-activity-time">
                                <?php echo human_time_diff(strtotime($activity->created_at), current_time('timestamp')); ?>
                                ago
                            </span>
                            <span class="sentinel-activity-user">
                                <?php echo esc_html(isset($usernames[$activity->user_id]) ? $usernames[$activity->user_id] : 'Unknown'); ?>
                            </span>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
                <?php else: ?>
                <div class="sentinel-activity-item">No recent activity found.</div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>
<!-- Chart.js is now enqueued via WordPress -->
<script>
// Pass data to JavaScript
window.sentinelDashboardData = {
    activityData: <?php echo json_encode($last_7_days); ?>,
    eventData: <?php echo json_encode($event_distribution); ?>,
    errorData: <?php echo json_encode($error_distribution); ?>,
    heatmapData: <?php echo json_encode($heatmap_data); ?>
};
</script>