<?php
/**
 * Kontroler logów (admin)
 */

require_once __DIR__ . '/BaseController.php';

class LogController extends BaseController
{
    /**
     * Lista logów aplikacji
     */
    public function index(): void
    {
        $page = max(1, (int)get('page', 1));
        $userId = get('user_id') ? (int)get('user_id') : null;
        
        $total = $this->logger->countLogs($userId);
        $pagination = paginate($total, ITEMS_PER_PAGE, $page);
        
        $logs = $this->logger->getLogs(ITEMS_PER_PAGE, $pagination['offset'], $userId);
        
        // Dodaj badge class do logów
        foreach ($logs as &$log) {
            $log['badge_class'] = $this->getBadgeClass($log['action']);
        }

        // Lista użytkowników do filtrowania
        $userModel = new User();
        $users = $userModel->getAll(100);

        $this->render('logs/list.tpl', [
            'pageTitle' => 'Logi aplikacji',
            'logs' => $logs,
            'pagination' => $pagination,
            'filterUserId' => $userId,
            'users' => $users,
            'logType' => 'app'
        ]);
    }

    /**
     * Lista logów API
     */
    public function api(): void
    {
        $page = max(1, (int)get('page', 1));
        
        $total = $this->logger->countApiLogs();
        $pagination = paginate($total, ITEMS_PER_PAGE, $page);
        
        $logs = $this->logger->getApiLogs(ITEMS_PER_PAGE, $pagination['offset']);

        $this->render('logs/api.tpl', [
            'pageTitle' => 'Logi API',
            'logs' => $logs,
            'pagination' => $pagination,
            'logType' => 'api'
        ]);
    }

    /**
     * Wyczyść stare logi
     */
    public function clear(): void
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            $this->redirect('admin/logs');
            return;
        }

        if (!$this->verifyCsrf()) {
            return;
        }

        $days = (int)post('days', 30);
        $days = max(1, min(365, $days));

        $deleted = $this->logger->clearOldLogs($days);

        $this->logger->log('logs_cleared', "Usunięto {$deleted} starych logów (starszych niż {$days} dni)", $this->currentUser['id']);

        if (isAjax()) {
            $this->json(['success' => true, 'deleted' => $deleted]);
        } else {
            $this->redirect('admin/logs', 'success', "Usunięto {$deleted} starych logów.");
        }
    }
    
    /**
     * Określ klasę badge na podstawie akcji
     */
    private function getBadgeClass(string $action): string
    {
        if (strpos($action, 'failed') !== false || strpos($action, 'error') !== false) {
            return 'danger';
        }
        if (strpos($action, 'deleted') !== false || strpos($action, 'block') !== false) {
            return 'warning';
        }
        if (strpos($action, 'created') !== false || strpos($action, 'success') !== false) {
            return 'success';
        }
        if (strpos($action, 'login') !== false) {
            return 'primary';
        }
        return 'info';
    }
}
