<?php
/**
 * API für eigene Icons: Liste, Upload, Löschen. Speicherung in storage/icons/
 */
require __DIR__ . '/../config.php';
require FUNCTIONS_ROOT . '/functions_common.php';

header('Content-Type: application/json; charset=utf-8');

$iconsDir = rtrim(STORAGE_ROOT, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . 'icons';
$allowed = ['icon.svg', 'theme-sun.svg', 'theme-moon.svg'];

if (!is_dir($iconsDir)) {
    @mkdir($iconsDir, 0755, true);
}

function icons_safe_name(string $name): ?string {
    global $allowed;
    $name = basename($name);
    return in_array($name, $allowed, true) ? $name : null;
}

$action = $_GET['action'] ?? $_POST['action'] ?? '';

if ($action === 'list') {
    $custom = [];
    foreach ($allowed as $name) {
        $path = $iconsDir . DIRECTORY_SEPARATOR . $name;
        $custom[$name] = is_file($path) && is_readable($path);
    }
    function_json_antwort(true, ['icons' => $custom]);
    exit;
}

if ($action === 'upload') {
    $name = icons_safe_name($_POST['name'] ?? '');
    if ($name === null) {
        function_json_antwort(false, [], 'Ungültiger Icon-Name');
        exit;
    }
    if (empty($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
        $err = $_FILES['file']['error'] ?? 'Keine Datei';
        if ($err === UPLOAD_ERR_INI_SIZE || $err === UPLOAD_ERR_FORM_SIZE) $err = 'Datei zu groß';
        elseif ($err === UPLOAD_ERR_NO_FILE) $err = 'Keine Datei gewählt';
        else $err = 'Upload-Fehler';
        function_json_antwort(false, [], $err);
        exit;
    }
    $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
    $allowedExt = ['svg', 'png', 'ico'];
    if (!in_array($ext, $allowedExt, true)) {
        function_json_antwort(false, [], 'Nur SVG, PNG oder ICO erlaubt');
        exit;
    }
    $path = $iconsDir . DIRECTORY_SEPARATOR . $name;
    if (move_uploaded_file($_FILES['file']['tmp_name'], $path)) {
        function_json_antwort(true, ['name' => $name]);
    } else {
        function_json_antwort(false, [], 'Speichern fehlgeschlagen');
    }
    exit;
}

if ($action === 'delete') {
    $name = icons_safe_name($_POST['name'] ?? $_GET['name'] ?? '');
    if ($name === null) {
        function_json_antwort(false, [], 'Ungültiger Icon-Name');
        exit;
    }
    $path = $iconsDir . DIRECTORY_SEPARATOR . $name;
    if (is_file($path)) {
        @unlink($path);
    }
    function_json_antwort(true, ['message' => 'Entfernt']);
    exit;
}

function_json_antwort(false, [], 'Unbekannte Aktion');
