<?php
class Security {
    // Generate CSRF token
    public static function generateCSRFToken() {
        if (!isset($_SESSION['csrf_token'])) {
            if (function_exists('random_bytes')) {
                $token = bin2hex(random_bytes(32));
            } elseif (function_exists('openssl_random_pseudo_bytes')) {
                $token = bin2hex(openssl_random_pseudo_bytes(32));
            } else {
                // Fallback (less secure but avoids crash)
                $token = bin2hex(substr(str_shuffle(md5(microtime())), 0, 32));
            }
            $_SESSION['csrf_token'] = $token;
        }
        return $_SESSION['csrf_token'];
    }

    // public static function generateCSRFToken() {
    //     if (!isset($_SESSION['csrf_token'])) {
    //         $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    //     }
    //     return $_SESSION['csrf_token'];
    // }
    
    // Validate CSRF token
    public static function validateCSRFToken($token) {
        return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
    }
    
    // Sanitize input
    public static function sanitizeInput($input) {
        return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
    }
    
    // Validate email
    public static function validateEmail($email) {
        return filter_var($email, FILTER_VALIDATE_EMAIL);
    }
    
    // Hash password
    public static function hashPassword($password) {
        return password_hash($password, PASSWORD_ARGON2ID);
    }
    
    // Verify password
    public static function verifyPassword($password, $hash) {
        return password_verify($password, $hash);
    }
    
    // Generate random token
    public static function generateToken($length = 32) {
        return bin2hex(random_bytes($length));
    }
    
    // Rate limiting
    public static function checkRateLimit($identifier, $maxAttempts = 5, $timeWindow = 300) {
        $key = 'rate_limit_' . $identifier;
        $attempts = isset($_SESSION[$key]) ? $_SESSION[$key] : [];
        $now = time();
        
        // Remove old attempts
        $attempts = array_filter($attempts, function($timestamp) use ($now, $timeWindow) {
            return ($now - $timestamp) < $timeWindow;
        });
        
        if (count($attempts) >= $maxAttempts) {
            return false;
        }
        
        $attempts[] = $now;
        $_SESSION[$key] = $attempts;
        return true;
    }
    
    // Validate file upload
    public static function validateFileUpload($file, $allowedTypes = ['jpg', 'jpeg', 'png', 'pdf']) {
        if ($file['error'] !== UPLOAD_ERR_OK) {
            return ['success' => false, 'message' => 'File upload error'];
        }
        
        if ($file['size'] > MAX_FILE_SIZE) {
            return ['success' => false, 'message' => 'File size too large'];
        }
        
        $extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if (!in_array($extension, $allowedTypes)) {
            return ['success' => false, 'message' => 'Invalid file type'];
        }
        
        // Check MIME type
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mimeType = finfo_file($finfo, $file['tmp_name']);
        finfo_close($finfo);
        
        $allowedMimes = [
            'jpg' => 'image/jpeg',
            'jpeg' => 'image/jpeg',
            'png' => 'image/png',
            'pdf' => 'application/pdf'
        ];
        
        if (!isset($allowedMimes[$extension]) || $mimeType !== $allowedMimes[$extension]) {
            return ['success' => false, 'message' => 'Invalid file format'];
        }
        
        return ['success' => true];
    }
    
    // Log security events
    public static function logSecurityEvent($event, $details = '', $userId = null) {
        try {
            $db = new Database();
            $db->query("INSERT INTO activity_logs (user_id, action, details, ip_address, user_agent) 
                       VALUES (:user_id, :action, :details, :ip, :agent)");
            $db->bind(':user_id', $userId);
            $db->bind(':action', $event);
            $db->bind(':details', $details);
            $db->bind(':ip', isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : 'unknown');
            $db->bind(':agent', isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'unknown');
            $db->execute();
        } catch (Exception $e) {
            error_log('Security log error: ' . $e->getMessage());
        }
    }
    
    // Check if user is authenticated
    public static function isAuthenticated() {
        return isset($_SESSION['user_id']) && isset($_SESSION['user_authenticated']);
    }
    
    // Check if user is admin
    public static function isAdmin() {
        return self::isAuthenticated() && isset($_SESSION['is_admin']) && $_SESSION['is_admin'];
    }
    
    // Require authentication
    public static function requireAuth() {
        if (!self::isAuthenticated()) {
            header('Location: login.php');
            exit;
        }
    }
    
    // Require admin
    public static function requireAdmin() {
        self::requireAuth();
        if (!self::isAdmin()) {
            header('Location: index.php');
            exit;
        }
    }
}
?>