<?php

namespace App\Services;

class SecurityService 
{
    protected $db;
    
    public function __construct()
    {
        $this->db = \Config\Database::connect();
    }
    
    /**
     * Güvenlik logu ekle
     */
    public function logSecurityEvent($userId, $action, $status, $details = [], $riskLevel = 'low')
    {
        $data = [
            'user_id' => $userId,
            'action' => $action,
            'status' => $status,
            'ip_address' => $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0',
            'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
            'details' => json_encode($details),
            'risk_level' => $riskLevel,
            'created_at' => date('Y-m-d H:i:s')
        ];
        
        $builder = $this->db->table('security_logs');
        return $builder->insert($data);
    }
    
    /**
     * Şüpheli aktivite kontrolü
     */
    public function checkSuspiciousActivity($userId, $ipAddress)
    {
        $builder = $this->db->table('security_logs');
        
        // Son 1 saat içinde aynı IP'den çok fazla başarısız deneme
        $recentFailures = $builder->where('ip_address', $ipAddress)
                                 ->where('status', 'failed')
                                 ->where('created_at >', date('Y-m-d H:i:s', strtotime('-1 hour')))
                                 ->countAllResults();
        
        if ($recentFailures >= 5) {
            return [
                'suspicious' => true,
                'reason' => 'Too many failed attempts from same IP',
                'action' => 'block_ip'
            ];
        }
        
        return ['suspicious' => false];
    }
    
    /**
     * Hesap kilitleme
     */
    public function lockAccount($userId, $reason, $durationMinutes = 30)
    {
        $userModel = model('App\Models\UserModel');
        
        $lockUntil = date('Y-m-d H:i:s', strtotime("+{$durationMinutes} minutes"));
        
        $userModel->update($userId, [
            'account_locked_until' => $lockUntil,
            'failed_login_attempts' => 0
        ]);
        
        $this->logSecurityEvent($userId, 'account_locked', 'success', [
            'reason' => $reason,
            'duration_minutes' => $durationMinutes
        ], 'high');
        
        return true;
    }
    
    /**
     * Hesap kilidi kontrolü
     */
    public function isAccountLocked($userId)
    {
        $userModel = model('App\Models\UserModel');
        $user = $userModel->find($userId);
        
        if (!$user || empty($user['account_locked_until'])) {
            return false;
        }
        
        $lockUntil = strtotime($user['account_locked_until']);
        $now = time();
        
        if ($lockUntil > $now) {
            return [
                'locked' => true,
                'remaining_minutes' => ceil(($lockUntil - $now) / 60)
            ];
        }
        
        // Kilit süresi dolmuş, temizle
        $userModel->update($userId, [
            'account_locked_until' => null,
            'failed_login_attempts' => 0
        ]);
        
        return false;
    }
    
    /**
     * Başarısız giriş denemesi kaydet
     */
    public function recordFailedLogin($userId, $email)
    {
        $userModel = model('App\Models\UserModel');
        
        if ($userId) {
            $user = $userModel->find($userId);
            $attempts = ($user['failed_login_attempts'] ?? 0) + 1;
            
            $userModel->update($userId, [
                'failed_login_attempts' => $attempts
            ]);
            
            // 5 başarısız denemeden sonra hesabı kilitle
            if ($attempts >= 5) {
                $this->lockAccount($userId, 'Too many failed login attempts', 60);
            }
        }
        
        $this->logSecurityEvent($userId, 'login_attempt', 'failed', [
            'email' => $email,
            'attempts' => $attempts ?? 1
        ], 'medium');
    }
    
    /**
     * Başarılı giriş sonrası temizlik
     */
    public function recordSuccessfulLogin($userId)
    {
        $userModel = model('App\Models\UserModel');
        
        $userModel->update($userId, [
            'failed_login_attempts' => 0,
            'account_locked_until' => null,
            'last_login' => date('Y-m-d H:i:s')
        ]);
        
        $this->logSecurityEvent($userId, 'login_attempt', 'success', [], 'low');
    }
}