<?php
$admin_user = 'admin';
$admin_pass = 'Cyber@Panel@2026';

// FastCGI / PHP-FPM Admin Lockout Fix
if (!isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['HTTP_AUTHORIZATION'])) {
    if (preg_match('/Basic\s+(.*)$/i', $_SERVER['HTTP_AUTHORIZATION'], $matches)) {
        $credentials = explode(':', base64_decode($matches[1]), 2);
        if (count($credentials) === 2) {
            list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = $credentials;
        }
    }
}

if (!isset($_SERVER['PHP_AUTH_USER']) || $_SERVER['PHP_AUTH_USER'] !== $admin_user || $_SERVER['PHP_AUTH_PW'] !== $admin_pass) {
    header('HTTP/1.0 401 Unauthorized');
    die(json_encode(['error' => 'Unauthorized']));
}

require_once 'fingerprint_wrapper.php';
header('Content-Type: application/json');

$pdo = get_db_connection();
if (!$pdo) die(json_encode(['error' => 'Database connection failed']));

// --- ANTI-BLOAT PROTOCOL: Auto-Cleanup Old Logs ---
$retention_days = (int)($config['log_retention_days'] ?? 30);
try {
    $pdo->exec("DELETE FROM traffic_logs WHERE created_at < DATE_SUB(NOW(), INTERVAL {$retention_days} DAY)");
    $pdo->exec("DELETE FROM ip_limits WHERE last_seen < DATE_SUB(NOW(), INTERVAL {$retention_days} DAY)");
} catch (Exception $e) { /* Fail silently */ }

// --- UNBAN ENDPOINT (Releases IP from MySQL & Redis) ---
if (isset($_GET['action']) && $_GET['action'] === 'unban' && !empty($_GET['ip'])) {
    $ip = filter_var($_GET['ip'], FILTER_VALIDATE_IP);
    if ($ip) {
        try {
            // 1. Remove from MySQL
            $stmt = $pdo->prepare("DELETE FROM honeypot_bans WHERE ip_address = ?");
            $stmt->execute([$ip]);
            
            // 2. Remove from Redis RAM
            $redis = get_redis_connection();
            if ($redis) {
                $redis->del("gatekeeper:honeypot:" . $ip);
            }
            
            die(json_encode(['status' => 'success']));
        } catch (Exception $e) {
            die(json_encode(['status' => 'fail', 'message' => 'Database error']));
        }
    }
    die(json_encode(['status' => 'fail', 'message' => 'Invalid IP']));
}

// --- DEEP IP FORENSICS ENDPOINT ---
if (isset($_GET['action']) && $_GET['action'] === 'investigate' && !empty($_GET['ip'])) {
    $ip = filter_var($_GET['ip'], FILTER_VALIDATE_IP);
    if ($ip) {
        $options = ["http" => ["method" => "GET", "timeout" => 3]];
        $context = stream_context_create($options);
        $res = @file_get_contents("http://ip-api.com/json/{$ip}?fields=status,country,regionName,city,zip,lat,lon,isp,org,as,mobile,proxy,hosting", false, $context);
        if ($res) die($res); 
    }
    die(json_encode(['status' => 'fail', 'message' => 'Forensic lookup failed']));
}

// --- TIME-FRAME FILTER LOGIC ---
$period = $_GET['period'] ?? '7days';
$where_clause = "";
$and_clause = "";

if ($period === 'today') {
    $where_clause = "WHERE DATE(created_at) = CURDATE()";
    $and_clause   = "AND DATE(created_at) = CURDATE()";
} elseif ($period === 'yesterday') {
    $where_clause = "WHERE DATE(created_at) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)";
    $and_clause   = "AND DATE(created_at) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)";
} elseif ($period === '7days') {
    $where_clause = "WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)";
    $and_clause   = "AND created_at >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)";
}

$logs = []; $counts = []; $proxy_count = 0;
$top_countries = []; $devices = []; $oses = []; $browsers = []; $threats = []; $timeline = [];
$honeypot_bans = []; 

try {
    $logs = $pdo->query("SELECT * FROM traffic_logs {$where_clause} ORDER BY created_at DESC LIMIT 100")->fetchAll();
    $counts = $pdo->query("SELECT destination, COUNT(*) as total FROM traffic_logs {$where_clause} GROUP BY destination")->fetchAll(PDO::FETCH_KEY_PAIR);
    $proxy_count = $pdo->query("SELECT COUNT(*) FROM traffic_logs WHERE is_proxy = 1 {$and_clause}")->fetchColumn();

    $top_countries = $pdo->query("SELECT country_code, COUNT(*) as count FROM traffic_logs {$where_clause} GROUP BY country_code ORDER BY count DESC LIMIT 5")->fetchAll();
    $devices = $pdo->query("SELECT device_type, COUNT(*) as count FROM traffic_logs {$where_clause} GROUP BY device_type ORDER BY count DESC")->fetchAll();
    $oses = $pdo->query("SELECT os, COUNT(*) as count FROM traffic_logs {$where_clause} GROUP BY os ORDER BY count DESC")->fetchAll();
    $browsers = $pdo->query("SELECT browser, COUNT(*) as count FROM traffic_logs {$where_clause} GROUP BY browser ORDER BY count DESC")->fetchAll();
    $threats = $pdo->query("SELECT block_reason, COUNT(*) as count FROM traffic_logs WHERE destination = 'safe' {$and_clause} GROUP BY block_reason ORDER BY count DESC")->fetchAll();

    $time_format = ($period === 'today' || $period === 'yesterday') ? '%H:00' : '%b %d';
    $timeline = $pdo->query("
        SELECT DATE_FORMAT(created_at, '{$time_format}') as label, 
               SUM(CASE WHEN destination = 'payload' THEN 1 ELSE 0 END) as payload_count,
               SUM(CASE WHEN destination = 'safe' THEN 1 ELSE 0 END) as safe_count
        FROM traffic_logs 
        {$where_clause}
        GROUP BY label
        ORDER BY MIN(created_at) ASC
    ")->fetchAll();
    
    // Fetch permanent honeypot bans
    $honeypot_bans = $pdo->query("SELECT ip_address, user_agent, DATE_FORMAT(caught_at, '%b %d %H:%i') as caught_time FROM honeypot_bans ORDER BY caught_at DESC LIMIT 50")->fetchAll();
    
} catch (PDOException $e) {}

echo json_encode([
    'logs' => $logs,
    'stats' => [
        'payload' => (int)($counts['payload'] ?? 0),
        'safe' => (int)($counts['safe'] ?? 0),
        'proxies' => (int)$proxy_count
    ],
    'top_countries' => $top_countries,
    'threats' => $threats,
    'intelligence' => [
        'devices' => $devices,
        'oses' => $oses,
        'browsers' => $browsers
    ],
    'timeline' => $timeline,
    'honeypot' => $honeypot_bans 
]);
?>