<?php
/**
 * Kontroler Bezpieczeństwa - zarządzanie IP
 */

require_once __DIR__ . '/BaseController.php';

class SecurityController extends BaseController
{
    private LoginSecurity $loginSecurity;
    
    public function __construct()
    {
        parent::__construct();
        
        if (!$this->auth->isAdmin()) {
            $this->redirect('dashboard', 'danger', 'Brak dostępu.');
            exit;
        }
        
        $this->loginSecurity = new LoginSecurity();
    }
    
    /**
     * Lista reguł IP
     */
    public function ipRules(): void
    {
        $type = get('type') ?: null;
        
        $rules = $this->loginSecurity->getIpRules($type);
        $blockedIps = $this->loginSecurity->getBlockedIps();
        $stats = $this->loginSecurity->getSecurityStats(30);
        
        $this->render('security/ip_rules.tpl', [
            'pageTitle' => 'Reguły IP',
            'rules' => $rules,
            'blockedIps' => $blockedIps,
            'stats' => $stats,
            'filterType' => $type
        ]);
    }
    
    /**
     * Dodaj regułę IP
     */
    public function addIpRule(): void
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            $this->redirect('security/ip-rules');
            return;
        }
        
        if (!$this->verifyCsrf()) {
            return;
        }
        
        $ip = trim(post('ip_address', ''));
        $type = post('rule_type', 'blacklist');
        $reason = trim(post('reason', ''));
        $expiresAt = post('expires_at') ?: null;
        
        // Walidacja IP
        if (!filter_var($ip, FILTER_VALIDATE_IP)) {
            $this->redirect('security/ip-rules', 'danger', 'Nieprawidłowy adres IP.');
            return;
        }
        
        // Walidacja typu
        if (!in_array($type, ['whitelist', 'blacklist'])) {
            $type = 'blacklist';
        }
        
        $this->loginSecurity->addIpRule(
            $ip, 
            $type, 
            null, 
            $reason,
            $expiresAt,
            $this->currentUser['id']
        );
        
        $this->logger->log('ip_rule_added', "Dodano regułę IP: {$ip} ({$type})", $this->currentUser['id']);
        $this->redirect('security/ip-rules', 'success', 'Reguła IP została dodana.');
    }
    
    /**
     * Usuń regułę IP
     */
    public function deleteIpRule(): void
    {
        if (!$this->verifyCsrf()) {
            return;
        }
        
        $id = (int)post('id');
        
        if ($this->loginSecurity->removeIpRule($id)) {
            $this->logger->log('ip_rule_deleted', "Usunięto regułę IP (ID: {$id})", $this->currentUser['id']);
            $this->redirect('security/ip-rules', 'success', 'Reguła IP została usunięta.');
        } else {
            $this->redirect('security/ip-rules', 'danger', 'Nie udało się usunąć reguły.');
        }
    }
    
    /**
     * Odblokuj IP (z login_attempts)
     */
    public function unblockIp(): void
    {
        if (!$this->verifyCsrf()) {
            return;
        }
        
        $ip = post('ip');
        
        if ($ip && $this->loginSecurity->unblockIp($ip)) {
            $this->logger->log('ip_unblocked', "Odblokowano IP: {$ip}", $this->currentUser['id']);
            $this->redirect('security/ip-rules', 'success', "IP {$ip} zostało odblokowane.");
        } else {
            $this->redirect('security/ip-rules', 'danger', 'Nie udało się odblokować IP.');
        }
    }
    
    /**
     * Dashboard bezpieczeństwa
     */
    public function dashboard(): void
    {
        $stats = $this->loginSecurity->getSecurityStats(30);
        $blockedIps = $this->loginSecurity->getBlockedIps();
        
        // Ostatnie nieudane logowania
        $recentFailed = $this->loginSecurity->getAllLogins(10, 0, ['success' => false]);
        
        $this->render('security/dashboard.tpl', [
            'pageTitle' => 'Bezpieczeństwo',
            'stats' => $stats,
            'blockedIps' => $blockedIps,
            'recentFailed' => $recentFailed
        ]);
    }
}
