<?php

declare(strict_types=1);

namespace OCA\GlxRadio\Controller;

use OCP\AppFramework\Controller;
use OCP\AppFramework\Http\Attribute\NoAdminRequired;
use OCP\AppFramework\Http\JSONResponse;
use OCP\IConfig;
use OCP\IRequest;
use OCP\IUserSession;

class SettingsController extends Controller {
    public function __construct(
        string $appName,
        IRequest $request,
        private IConfig $config,
        private IUserSession $userSession,
    ) {
        parent::__construct($appName, $request);
    }

    private function getUserId(): ?string {
        $user = $this->userSession->getUser();
        return $user ? $user->getUID() : null;
    }

    /**
     * @return string[]
     */
    private function loadFolders(string $uid): array {
        $raw = $this->config->getUserValue($uid, 'glxradio', 'station_folders', '[]');
        $decoded = json_decode($raw, true);
        return is_array($decoded) ? array_values(array_filter($decoded, 'is_string')) : [];
    }

    private function saveFolders(string $uid, array $folders): void {
        $this->config->setUserValue($uid, 'glxradio', 'station_folders', json_encode(array_values($folders)));
    }

    /**
     * Liefert die persoenlichen App-Einstellungen des angemeldeten Nutzers.
     */
    #[NoAdminRequired]
    public function get(): JSONResponse {
        $uid = $this->getUserId();
        if (!$uid) {
            return new JSONResponse(['logoFolder' => '/RadioLogos', 'showLogos' => true, 'folders' => []]);
        }
        $logoFolder = $this->config->getUserValue($uid, 'glxradio', 'logo_folder', '/RadioLogos');
        $showLogos = $this->config->getUserValue($uid, 'glxradio', 'show_logos', '1') === '1';
        return new JSONResponse([
            'logoFolder' => $logoFolder !== '' ? $logoFolder : '/RadioLogos',
            'showLogos' => $showLogos,
            'folders' => $this->loadFolders($uid),
        ]);
    }

    /**
     * Speichert die persoenlichen App-Einstellungen des angemeldeten Nutzers.
     */
    #[NoAdminRequired]
    public function save(string $logoFolder = '/RadioLogos', bool $showLogos = true): JSONResponse {
        $uid = $this->getUserId();
        if (!$uid) {
            return new JSONResponse(['error' => 'Nicht angemeldet.'], 401);
        }
        $logoFolder = trim($logoFolder);
        if ($logoFolder === '') {
            $logoFolder = '/RadioLogos';
        }
        if ($logoFolder[0] !== '/') {
            $logoFolder = '/' . $logoFolder;
        }
        $this->config->setUserValue($uid, 'glxradio', 'logo_folder', $logoFolder);
        $this->config->setUserValue($uid, 'glxradio', 'show_logos', $showLogos ? '1' : '0');
        return new JSONResponse(['status' => 'ok']);
    }

    /**
     * Legt einen neuen Sender-Ordner an (falls noch nicht vorhanden).
     */
    #[NoAdminRequired]
    public function addFolder(string $name): JSONResponse {
        $uid = $this->getUserId();
        if (!$uid) {
            return new JSONResponse(['error' => 'Nicht angemeldet.'], 401);
        }
        $name = trim($name);
        if ($name === '') {
            return new JSONResponse(['error' => 'Name darf nicht leer sein.'], 400);
        }
        $folders = $this->loadFolders($uid);
        if (!in_array($name, $folders, true)) {
            $folders[] = $name;
            $this->saveFolders($uid, $folders);
        }
        return new JSONResponse(['folders' => $folders]);
    }

    /**
     * Loescht einen Sender-Ordner wieder. Sender, die diesem Ordner
     * zugewiesen waren, bleiben als Favoriten erhalten - nur die
     * Ordner-Zuweisung selbst geht verloren (macht das Frontend beim
     * Speichern der Favoritenliste).
     */
    #[NoAdminRequired]
    public function deleteFolder(string $name): JSONResponse {
        $uid = $this->getUserId();
        if (!$uid) {
            return new JSONResponse(['error' => 'Nicht angemeldet.'], 401);
        }
        $folders = array_values(array_filter($this->loadFolders($uid), fn ($f) => $f !== $name));
        $this->saveFolders($uid, $folders);
        return new JSONResponse(['folders' => $folders]);
    }
}
