<?php
class AuthService {
    private static function base64url_encode($data) {
        return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
    }
    public static function verifyJWT($jwt) {
        if (!$jwt) return null;
        $parts = explode('.', $jwt);
        if (count($parts) !== 3) return null;
        list($header, $payload, $signature) = $parts;
        $valid = self::base64url_encode(hash_hmac('sha256', "$header.$payload", self::$jwtSecret, true));
        if (!hash_equals($valid, $signature)) return null;
        $data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
        if (!$data || ($data['exp'] ?? 0) < time()) return null;
        // User-Infos je nach Rolle ergänzen
        if ($data['role'] === 'admin') {
            return [
                'username' => $data['id'],
                'role' => 'admin'
            ];
        } elseif ($data['role'] === 'client') {
            return [
                'client' => $data['dir'],
                'role' => 'client',
                'dir' => $data['dir']
            ];
        }
        return null;
    }
    private static $adminFile = __DIR__ . '/../../storage/data/admins.json';
    private static $clientFile = __DIR__ . '/../../storage/data/clients.json';
    private static $jwtSecret = 'adspreview_secret_2025';

    public static function authenticate($username, $password) {
        if ($username) {
            // Admin-Login
            $admins = json_decode(file_get_contents(self::$adminFile), true);
            foreach ($admins as $admin) {
                if ($admin['username'] === $username && password_verify($password, $admin['password'])) {
                    $token = self::generateJWT($admin['username'], '', 'admin');
                    return ['success' => true, 'token' => $token, 'role' => 'admin'];
                }
            }
            return ['success' => false, 'message' => 'Falscher Benutzername oder Passwort.'];
        } else {
            // Client-Login (nur Passwort)
            $clients = json_decode(file_get_contents(self::$clientFile), true);
            foreach ($clients as $key => $client) {
                if ($client['pass'] === md5($password)) {
                    $token = self::generateJWT($key, $client['dir'], 'client');
                    return ['success' => true, 'token' => $token, 'role' => 'client'];
                }
            }
            return ['success' => false, 'message' => 'Falsches Passwort.'];
        }
    }

    private static function generateJWT($id, $dir, $role) {
        $header = self::base64url_encode(json_encode(['alg' => 'HS256', 'typ' => 'JWT']));
        $payload = self::base64url_encode(json_encode([
            'id' => $id,
            'dir' => $dir,
            'role' => $role,
            'exp' => time() + 60 * 60 * 12 // 12 Stunden
        ]));
        $signature = hash_hmac('sha256', "$header.$payload", self::$jwtSecret, true);
        $signature = self::base64url_encode($signature);
        return "$header.$payload.$signature";
    }
}
