<?php

namespace App\Controllers;

use App\Config\Database;
use App\Utils\View;

class LogController
{
    public function index()
    {
        $conn = Database::getInstance()->getConnection();

        // Pagination
        $page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
        $limit = 50;
        $offset = ($page - 1) * $limit;

        // Count total
        $totalStmt = $conn->query("SELECT COUNT(*) FROM api_logs");
        $total = $totalStmt->fetchColumn();
        $totalPages = ceil($total / $limit);

        // Fetch logs with server info
        $sql = "SELECT l.*, s.name as server_name, s.ip_v4 
                FROM api_logs l 
                LEFT JOIN servers s ON l.server_id = s.id 
                ORDER BY l.created_at DESC 
                LIMIT :limit OFFSET :offset";

        $stmt = $conn->prepare($sql);
        $stmt->bindValue(':limit', $limit, \PDO::PARAM_INT);
        $stmt->bindValue(':offset', $offset, \PDO::PARAM_INT);
        $stmt->execute();
        $logs = $stmt->fetchAll();

        View::render('layouts.admin', [
            'title' => 'Logs do Sistema',
            'content' => __DIR__ . '/../../resources/views/admin/logs/index.php',
            'logs' => $logs,
            'page' => $page,
            'totalPages' => $totalPages
        ]);
    }
}
