<?php
namespace EIS\Component\EIS\Administrator\View\Main;

\defined('_JEXEC') or die;

use Joomla\CMS\Factory;
use Joomla\CMS\MVC\View\HtmlView as BaseHtmlView;
use Joomla\Database\DatabaseDriver;
use EIS\Component\EIS\Administrator\Helper\TreeHelper;

class HtmlView extends BaseHtmlView
{
    /** HTML des Baums (inkl. virtuellem Ordner „Neue Dokumente“, falls vorhanden) */
    protected string $treeHtml = '';

    /** Liste aller Viewlevels: [ ['id'=>int, 'title'=>string], ... ] */
    protected array $viewLevels = [];

    /**
     * Map der gesetzten ACLs für Top-Level-Ordner:
     * [ folder_id (int) => viewlevel_id (int), ... ]
     */
    protected array $folderAccess = [];

    public function display($tpl = null): void
    {
        $app = Factory::getApplication();
        /** @var DatabaseDriver $db */
        $db  = Factory::getDbo();

        // 1) Baum-Daten
        $items  = TreeHelper::getItems();

        // neu hinzugekommene IDs aus letztem Scan (können leer sein)
        $newIds = (array) $app->getUserState('com_eis.new_ids', []);

        // Baum rendern (virtueller Ordner „Neue Dokumente“ + regulärer Baum)
        $this->treeHtml = TreeHelper::renderTreeWithNew($items, $newIds);

        // 2) Viewlevels laden
        $this->viewLevels = $this->loadViewLevels($db);

        // 3) gesetzte ACLs für Top-Level-Ordner laden
        $this->folderAccess = $this->loadFolderAccess($db);

        // Template ausgeben
        parent::display($tpl);

        // „Neue Dokumente“ einmalig zeigen → State leeren
        $app->setUserState('com_eis.new_ids', []);
    }

    /** Für Template: HTML des Baums */
    public function getTreeHtml(): string
    {
        return $this->treeHtml;
    }

    /** Für Template: Liste der Viewlevels */
    public function getViewLevels(): array
    {
        return $this->viewLevels;
    }

    /**
     * Für Template/JS: Map folder_id => viewlevel_id (nur Top-Level-Ordner)
     * Beispiel: [ 12 => 3, 15 => 5 ]
     */
    public function getFolderAccess(): array
    {
        return $this->folderAccess;
    }

    /** Lädt alle Viewlevels sortiert nach Titel */
    private function loadViewLevels(DatabaseDriver $db): array
    {
        $q = $db->getQuery(true)
            ->select($db->quoteName(['id', 'title']))
            ->from($db->quoteName('#__viewlevels'))
            ->order($db->quoteName('title') . ' ASC');

        $db->setQuery($q);
        $rows = (array) $db->loadAssocList();

        // Safety: Normalisieren der Typen
        foreach ($rows as &$r) {
            $r['id']    = (int) ($r['id'] ?? 0);
            $r['title'] = (string) ($r['title'] ?? '');
        }

        return $rows;
    }

    /**
     * Lädt ACL-Zuweisungen aus #__eis_folder_access.
     * Es werden nur Top-Level-Ordner-IDs erwartet (per Controller validiert).
     */
    private function loadFolderAccess(DatabaseDriver $db): array
    {
        $q = $db->getQuery(true)
            ->select($db->quoteName(['folder_id', 'viewlevel_id']))
            ->from($db->quoteName('#__eis_folder_access'));

        $db->setQuery($q);
        $rows = (array) $db->loadAssocList();

        $map = [];
        foreach ($rows as $r) {
            $fid = (int) ($r['folder_id'] ?? 0);
            $vid = (int) ($r['viewlevel_id'] ?? 0);
            if ($fid > 0 && $vid > 0) {
                $map[$fid] = $vid;
            }
        }
        return $map;
    }
}
