<?php
/**
 * Authentication Helper
 */
class Auth {
    
    public static function check(): bool {
        return isset($_SESSION['user_id']) && $_SESSION['user_id'] > 0;
    }
    
    public static function user(): ?array {
        if (!self::check()) return null;
        
        if (!isset($_SESSION['user_data']) || (time() - ($_SESSION['user_cache_time'] ?? 0)) > 300) {
            $db = Database::getInstance();
            $user = $db->fetch(
                "SELECT u.*, r.name as role_name, r.slug as role_slug, c.name as company_name
                 FROM users u
                 LEFT JOIN roles r ON u.role_id = r.id
                 LEFT JOIN companies c ON u.company_id = c.id
                 WHERE u.id = ? AND u.status = 'active' AND u.deleted_at IS NULL",
                [$_SESSION['user_id']]
            );
            
            if (!$user) {
                self::logout();
                return null;
            }
            
            $_SESSION['user_data'] = $user;
            $_SESSION['user_cache_time'] = time();
        }
        
        return $_SESSION['user_data'];
    }
    
    public static function id(): ?int {
        return $_SESSION['user_id'] ?? null;
    }
    
    public static function companyId(): ?int {
        $user = self::user();
        return $user['company_id'] ?? null;
    }
    
    public static function role(): ?string {
        $user = self::user();
        return $user['role_slug'] ?? null;
    }
    
    public static function isSuperAdmin(): bool {
        return self::role() === 'super_admin';
    }
    
    public static function isAdmin(): bool {
        return in_array(self::role(), ['super_admin', 'company_admin']);
    }
    
    public static function hasPermission(string $permission): bool {
        if (self::isSuperAdmin()) return true;
        
        $db = Database::getInstance();
        $user = self::user();
        if (!$user) return false;
        
        $result = $db->fetch(
            "SELECT 1 FROM role_permissions rp
             JOIN permissions p ON rp.permission_id = p.id
             WHERE rp.role_id = ? AND p.slug = ?",
            [$user['role_id'], $permission]
        );
        
        return $result !== null;
    }
    
    public static function attempt(string $email, string $password): bool {
        $db = Database::getInstance();
        
        $user = $db->fetch(
            "SELECT * FROM users WHERE email = ? AND deleted_at IS NULL",
            [$email]
        );
        
        if (!$user) return false;
        
        // Check lockout
        if ($user['locked_until'] && strtotime($user['locked_until']) > time()) {
            return false;
        }
        
        if (!password_verify($password, $user['password'])) {
            // Increment login attempts
            $attempts = $user['login_attempts'] + 1;
            $lockUntil = null;
            
            if ($attempts >= MAX_LOGIN_ATTEMPTS) {
                $lockUntil = date('Y-m-d H:i:s', time() + LOCKOUT_DURATION);
                $attempts = 0;
            }
            
            $db->update('users', [
                'login_attempts' => $attempts,
                'locked_until' => $lockUntil
            ], 'id = ?', [$user['id']]);
            
            return false;
        }
        
        if ($user['status'] !== 'active') return false;
        
        // Successful login
        $db->update('users', [
            'login_attempts' => 0,
            'locked_until' => null,
            'last_login_at' => date('Y-m-d H:i:s'),
            'last_login_ip' => $_SERVER['REMOTE_ADDR'] ?? null
        ], 'id = ?', [$user['id']]);
        
        $_SESSION['user_id'] = $user['id'];
        unset($_SESSION['user_data'], $_SESSION['user_cache_time']);
        
        session_regenerate_id(true);
        
        auditLog('login', 'user', $user['id']);
        
        return true;
    }
    
    public static function logout(): void {
        if (self::check()) {
            auditLog('logout', 'user', self::id());
        }
        
        $_SESSION = [];
        if (ini_get("session.use_cookies")) {
            $params = session_get_cookie_params();
            setcookie(session_name(), '', time() - 42000,
                $params["path"], $params["domain"],
                $params["secure"], $params["httponly"]
            );
        }
        session_destroy();
    }
}
