<?php
require_once __DIR__ . '/../Services/AuthService.php';

class UserController {
    
    public static function currentUser() {
        $headers = getallheaders();
        $auth = $headers['Authorization'] ?? $headers['authorization'] ?? '';
        $token = str_replace('Bearer ', '', $auth);
        $user = AuthService::verifyJWT($token);
        if ($user) {
            http_response_code(200);
            echo json_encode([
                'success' => true,
                'user' => $user
            ]);
        } else {
            http_response_code(401);
            echo json_encode([
                'success' => false,
                'error' => [
                    'code' => 'INVALID_TOKEN',
                    'message' => 'Token ungültig oder abgelaufen.'
                ]
            ]);
        }
    }

    // Gibt alle Benutzer als Array zurück (z.B. aus storage/data/admins.json)
    public static function listAll() {
        $file = __DIR__ . '/../../storage/data/admins.json';
        if (!file_exists($file)) {
            http_response_code(200);
            echo json_encode([
                'success' => true,
                'users' => []
            ]);
            return;
        }
        $json = file_get_contents($file);
        $users = json_decode($json, true);
        if (!is_array($users)) $users = [];
        http_response_code(200);
        echo json_encode([
            'success' => true,
            'users' => $users
        ]);
    }

    // Legt einen neuen Benutzer an
    public static function create() {
        $file = __DIR__ . '/../../storage/data/admins.json';
        $input = json_decode(file_get_contents('php://input'), true);
        if (!is_array($input) || empty($input['username']) || empty($input['role'])) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'error' => [
                    'code' => 'INVALID_INPUT',
                    'message' => 'Ungültige Eingabedaten.'
                ]
            ]);
            return;
        }
        // Bestehende Benutzer laden
        $users = [];
        if (file_exists($file)) {
            $json = file_get_contents($file);
            $users = json_decode($json, true);
            if (!is_array($users)) $users = [];
        }
        // Neue ID generieren
        $newId = 1;
        if (!empty($users)) {
            $ids = array_column($users, 'id');
            $newId = max($ids) + 1;
        }
        $newUser = [
            'id' => $newId,
            'username' => $input['username'],
            'role' => $input['role'],
            'email' => $input['email'] ?? '',
            // Optional: Passwort-Hash, weitere Felder
        ];
        $users[] = $newUser;
        // Speichern
        file_put_contents($file, json_encode($users, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
        http_response_code(201);
        echo json_encode([
            'success' => true,
            'user' => $newUser
        ]);
    }

    // Bearbeitet einen bestehenden Benutzer
    public static function update($id) {
        $file = __DIR__ . '/../../storage/data/admins.json';
        $input = json_decode(file_get_contents('php://input'), true);
        if (!is_array($input) || empty($input['username']) || empty($input['role'])) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'error' => [
                    'code' => 'INVALID_INPUT',
                    'message' => 'Ungültige Eingabedaten.'
                ]
            ]);
            return;
        }
        // Bestehende Benutzer laden
        $users = [];
        if (file_exists($file)) {
            $json = file_get_contents($file);
            $users = json_decode($json, true);
            if (!is_array($users)) $users = [];
        }
        $found = false;
        foreach ($users as &$user) {
            if ($user['id'] == $id) {
                $user['username'] = $input['username'];
                $user['role'] = $input['role'];
                $user['email'] = $input['email'] ?? '';
                // Optional: weitere Felder wie Passwort etc.
                $found = true;
                break;
            }
        }
        if (!$found) {
            http_response_code(404);
            echo json_encode([
                'success' => false,
                'error' => [
                    'code' => 'NOT_FOUND',
                    'message' => 'Benutzer nicht gefunden.'
                ]
            ]);
            return;
        }
        // Speichern
        file_put_contents($file, json_encode($users, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
        http_response_code(200);
        echo json_encode([
            'success' => true,
            'user' => $user
        ]);
    }

    // Löscht einen bestehenden Benutzer
    public static function delete($id) {
        $file = __DIR__ . '/../../storage/data/admins.json';
        $users = [];
        if (file_exists($file)) {
            $json = file_get_contents($file);
            $users = json_decode($json, true);
            if (!is_array($users)) $users = [];
        }
        $found = false;
        $newUsers = [];
        foreach ($users as $user) {
            if ($user['id'] == $id) {
                $found = true;
                continue; // Benutzer überspringen (löschen)
            }
            $newUsers[] = $user;
        }
        if (!$found) {
            http_response_code(404);
            echo json_encode([
                'success' => false,
                'error' => [
                    'code' => 'NOT_FOUND',
                    'message' => 'Benutzer nicht gefunden.'
                ]
            ]);
            return;
        }
        // Speichern
        file_put_contents($file, json_encode($newUsers, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
        http_response_code(200);
        echo json_encode([
            'success' => true
        ]);
    }
}
