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

class EntityController {
    private static function authorize(string $requiredRole) {
        $headers = getallheaders();
        $auth = $headers['Authorization'] ?? $headers['authorization'] ?? '';
        $token = str_replace('Bearer ', '', $auth);
        $user = AuthService::verifyJWT($token);
        if (!$user || strtolower($user['role']) !== strtolower($requiredRole)) {
            http_response_code(403);
            echo json_encode(['success' => false, 'error' => ['code'=>'FORBIDDEN','message'=>'Nicht berechtigt.']]);
            exit;
        }
        return $user;
    }

    public static function list(string $type) {
        $user = self::authorize('admin');
        
        // Datei-Namen-Mapping: 'users' speichert in admins.json
        $storageType = $type === 'users' ? 'admins' : $type;
        $items = JsonStorageService::read($storageType);
        
        // Für Client-Listen: Prüfe disallowedClients des aktuellen Admins
        if ($type === 'clients') {
            $adminData = self::getAdminData($user['username']);
            $disallowedClients = $adminData['disallowedClients'] ?? [];
            
            // Filtere nicht erlaubte Clients aus
            $filteredItems = [];
            foreach ($items as $clientKey => $clientData) {
                if (!in_array($clientKey, $disallowedClients)) {
                    $filteredItems[$clientKey] = $clientData;
                }
            }
            $items = $filteredItems;
        }
        
        // Für User-Listen: Entferne Passwörter aus der Response
        if ($type === 'users') {
            foreach ($items as &$item) {
                unset($item['password']); // Passwörter nie an Frontend senden
            }
        }
        
        http_response_code(200);
        echo json_encode(['success'=>true, strtolower($type)=>$items]);
    }

    // Hilfsfunktion: Admin-Daten laden
    private static function getAdminData($username) {
        $adminFile = __DIR__ . '/../../storage/data/admins.json';
        if (file_exists($adminFile)) {
            $admins = json_decode(file_get_contents($adminFile), true);
            foreach ($admins as $admin) {
                if ($admin['username'] === $username) {
                    return $admin;
                }
            }
        }
        return [];
    }

    public static function create(string $type) {
        self::authorize('admin');
        $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;
        }
        $storageType = $type === 'users' ? 'admins' : $type;
        $items = JsonStorageService::read($storageType);
        $newId = empty($items) ? 1 : max(array_column($items,'id'))+1;
        $new = [
            'id'=>$newId,
            'username'=>$input['username'],
            'role'=>$input['role'],
            'email'=>$input['email']??''
        ];
        
        // Passwort hashen falls angegeben
        if (!empty($input['password'])) {
            $new['password'] = password_hash($input['password'], PASSWORD_BCRYPT);
        }
        
        // disallowedClients für Admin-Benutzer hinzufügen
        if ($input['role'] === 'admin' && isset($input['disallowedClients'])) {
            $new['disallowedClients'] = is_array($input['disallowedClients']) ? $input['disallowedClients'] : [];
        }
        
        $items[] = $new;
        JsonStorageService::write($storageType, $items);
        http_response_code(201);
        echo json_encode(['success'=>true, strtolower($type)=>$new]);
    }

    public static function update(string $type, int $id) {
        self::authorize('admin');
        $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;
        }
        $storageType = $type === 'users' ? 'admins' : $type;
        $items = JsonStorageService::read($storageType);
        $found = false;
        foreach ($items as &$item) {
            if ($item['id']==$id) {
                $item['username']=$input['username'];
                $item['role']=$input['role'];
                $item['email']=$input['email']??'';
                
                // Passwort aktualisieren falls angegeben
                if (!empty($input['password'])) {
                    $item['password'] = password_hash($input['password'], PASSWORD_BCRYPT);
                }
                
                // disallowedClients für Admin-Benutzer aktualisieren
                if ($input['role'] === 'admin' && isset($input['disallowedClients'])) {
                    $item['disallowedClients'] = is_array($input['disallowedClients']) ? $input['disallowedClients'] : [];
                } elseif ($input['role'] !== 'admin') {
                    // Entferne disallowedClients wenn User kein Admin mehr ist
                    unset($item['disallowedClients']);
                }
                
                $found = true;
                break;
            }
        }
        if (!$found) {
            http_response_code(404);
            echo json_encode(['success'=>false,'error'=>['code'=>'NOT_FOUND','message'=>'Eintrag nicht gefunden.']]);
            return;
        }
        JsonStorageService::write($storageType, $items);
        http_response_code(200);
        echo json_encode(['success'=>true,strtolower($type)=>$item]);
    }

    public static function delete(string $type, int $id) {
        self::authorize('admin');
        $storageType = $type === 'users' ? 'admins' : $type;
        $items = JsonStorageService::read($storageType);
        $found = false;
        $out = [];
        foreach ($items as $item) {
            if ($item['id']==$id) { $found=true; continue; }
            $out[]=$item;
        }
        if (!$found) {
            http_response_code(404);
            echo json_encode(['success'=>false,'error'=>['code'=>'NOT_FOUND','message'=>'Eintrag nicht gefunden.']]);
            return;
        }
        JsonStorageService::write($storageType, $out);
        http_response_code(200);
        echo json_encode(['success'=>true]);
    }

    public static function updatePassword(string $type, int $id) {
        self::authorize('admin');
        $input = json_decode(file_get_contents('php://input'), true);
        
        if (!is_array($input) || empty($input['password'])) {
            http_response_code(400);
            echo json_encode(['success'=>false,'error'=>['code'=>'INVALID_INPUT','message'=>'Passwort ist erforderlich.']]);
            return;
        }
        
        $storageType = $type === 'users' ? 'admins' : $type;
        $items = JsonStorageService::read($storageType);
        $found = false;
        
        foreach ($items as &$item) {
            if ($item['id']==$id) {
                $item['password'] = password_hash($input['password'], PASSWORD_BCRYPT);
                $found = true;
                break;
            }
        }
        
        if (!$found) {
            http_response_code(404);
            echo json_encode(['success'=>false,'error'=>['code'=>'NOT_FOUND','message'=>'Benutzer nicht gefunden.']]);
            return;
        }
        
        JsonStorageService::write($storageType, $items);
        http_response_code(200);
        echo json_encode(['success'=>true, 'message'=>'Passwort erfolgreich aktualisiert.']);
    }
}
