<?php
class Auth {
    public static function login(string $username, string $password): bool {
        $db   = Database::get();
        $stmt = $db->prepare('SELECT id, password_hash, is_active, role FROM app_users WHERE username = ?');
        $stmt->execute([$username]);
        $user = $stmt->fetch();

        if (!$user || !$user['is_active'] || !password_verify($password, $user['password_hash'])) {
            return false;
        }

        $db->prepare('UPDATE app_users SET last_login = NOW() WHERE id = ?')->execute([$user['id']]);

        session_regenerate_id(true);
        $_SESSION['user_id']   = $user['id'];
        $_SESSION['username']  = $username;
        $_SESSION['role']      = $user['role'];
        $_SESSION['logged_in'] = true;
        return true;
    }

    public static function logout(): void {
        $_SESSION = [];
        if (ini_get('session.use_cookies')) {
            $p = session_get_cookie_params();
            setcookie(session_name(), '', time() - 42000,
                $p['path'], $p['domain'], $p['secure'], $p['httponly']);
        }
        session_destroy();
    }

    public static function isLoggedIn(): bool {
        return !empty($_SESSION['logged_in']);
    }

    public static function requireLogin(): void {
        if (!self::isLoggedIn()) {
            header('Location: index.php');
            exit;
        }
    }

    public static function currentUserId(): ?int {
        return $_SESSION['user_id'] ?? null;
    }

    public static function currentUsername(): string {
        return $_SESSION['username'] ?? '';
    }

    public static function currentUserRole(): string {
        return $_SESSION['role'] ?? 'viewer';
    }

    /**
     * Redirige vers le tableau de bord si le rôle courant ne fait pas partie
     * des rôles autorisés. Passer un ou plusieurs rôles en argument.
     */
    public static function requireRole(string ...$roles): void {
        if (!in_array(self::currentUserRole(), $roles, true)) {
            $_SESSION['flash'] = [
                'type'    => 'danger',
                'message' => 'Accès refusé : droits insuffisants.',
            ];
            header('Location: dashboard.php');
            exit;
        }
    }

    public static function setRole(int $userId, string $role): void {
        if (!in_array($role, ['admin', 'tech', 'viewer'], true)) return;
        Database::get()->prepare('UPDATE app_users SET role = ? WHERE id = ?')
            ->execute([$role, $userId]);
        // Mettre à jour la session si c'est l'utilisateur courant
        if ($userId === self::currentUserId()) {
            $_SESSION['role'] = $role;
        }
    }

    public static function createUser(string $username, string $password, string $role = 'tech'): int {
        if (!in_array($role, ['admin', 'tech', 'viewer'], true)) $role = 'tech';
        $db   = Database::get();
        $hash = password_hash($password, PASSWORD_BCRYPT);
        $stmt = $db->prepare('INSERT INTO app_users (username, password_hash, role) VALUES (?, ?, ?)');
        $stmt->execute([$username, $hash, $role]);
        return (int)$db->lastInsertId();
    }

    public static function countUsers(): int {
        return (int)Database::get()->query('SELECT COUNT(*) FROM app_users')->fetchColumn();
    }

    public static function getAllUsers(): array {
        return Database::get()->query(
            'SELECT id, username, is_active, role, created_at, last_login FROM app_users ORDER BY username'
        )->fetchAll();
    }

    public static function changePassword(int $userId, string $newPassword): void {
        $hash = password_hash($newPassword, PASSWORD_BCRYPT);
        Database::get()->prepare('UPDATE app_users SET password_hash = ? WHERE id = ?')
            ->execute([$hash, $userId]);
    }

    public static function toggleActive(int $userId, bool $active): void {
        Database::get()->prepare('UPDATE app_users SET is_active = ? WHERE id = ?')
            ->execute([$active ? 1 : 0, $userId]);
    }
}
