<?php

namespace EIS\Component\EIS\Administrator\Helper;

\defined('_JEXEC') or die;

use Joomla\CMS\Factory;
use Joomla\Database\DatabaseDriver;

class TreeHelper
{
    /** Lädt #__eis_documents, gruppiert nach parent_id und sortiert */
    public static function getItems(): array
    {
        /** @var DatabaseDriver $db */
        $db = Factory::getDbo();

        $query = $db->getQuery(true)
            ->select('*')
            ->from($db->quoteName('#__eis_documents'))
            ->order($db->quoteName('ordering') . ' ASC');

        $rows = $db->setQuery($query)->loadAssocList();

        $grouped = [];
        foreach ($rows as $row) {
            $pid = $row['parent_id'] === null ? null : (int) $row['parent_id'];
            $grouped[$pid][] = $row;
        }

        // alphabetisch nach name
        foreach ($grouped as &$group) {
            usort($group, fn($a, $b) => strcasecmp($a['name'], $b['name']));
        }

        return $grouped;
    }

    /** Baum rendern (nutzt title als alternativen Anzeigenamen) */
    public static function renderTree(array $items, ?int $parentId = null): string
    {
        if (!isset($items[$parentId])) {
            return '';
        }

        $html = '<ul class="pdf-tree">';

        foreach ($items[$parentId] as $item) {
            $isFolder = (bool) $item['is_folder'];
            $rawName  = $item['title'] ?: $item['name'];
            $display  = preg_replace('/\.pdf$/i', '', (string) $rawName);
            $display  = htmlspecialchars($display, ENT_QUOTES, 'UTF-8');
            $id       = (int) $item['id'];
            if ($isFolder) {
                $fileCount = self::countFilesRecursive($items, $id);

                $html .= '<li class="folder"'
                    .  ' data-id="' . $id . '"'
                    .  ' data-title="' . htmlspecialchars((string)($item['title'] ?? ''), ENT_QUOTES, 'UTF-8') . '"'
                    .  ' data-name="'  . htmlspecialchars((string)$item['name'], ENT_QUOTES, 'UTF-8') . '"'
                    .  '>';
                $html .= '<span class="toggle" role="button" aria-label="Ordner umschalten" tabindex="0">▶</span> ';
                $html .= '<span class="folder-label">📁 ' . $display . ' <small class="count">(' . (int)$fileCount . ')</small></span>';
                $html .= self::renderTree($items, $id);
                $html .= '</li>';
            } else {
                $sizeStr = '';
                if (!empty($item['path']) && is_file($item['path'])) {
                    $size = @filesize($item['path']);
                    if ($size !== false) {
                        $sizeStr = ' <small class="meta">(' . self::formatFileSize((int) $size) . ')</small>';
                    }
                }

                $html .= '<li class="file"'
                    .  ' data-id="' . $id . '"'
                    .  ' data-title="' . htmlspecialchars((string)($item['title'] ?? ''), ENT_QUOTES, 'UTF-8') . '"'
                    .  ' data-name="'  . htmlspecialchars((string)$item['name'], ENT_QUOTES, 'UTF-8') . '"'
                    .  '>';
                $html .= '<span class="file-label">📄 ' . $display . $sizeStr . '</span>';
                $html .= '</li>';
            }
        }

        $html .= '</ul>';
        return $html;
    }

    private static function countFilesRecursive(array $items, int $parentId): int
    {
        $count = 0;
        if (!isset($items[$parentId])) {
            return 0;
        }
        foreach ($items[$parentId] as $item) {
            if ((bool) $item['is_folder']) {
                $count += self::countFilesRecursive($items, (int)$item['id']);
            } else {
                $count++;
            }
        }
        return $count;
    }

    private static function formatFileSize(int $bytes): string
    {
        if ($bytes >= 1073741824) return number_format($bytes / 1073741824, 2) . ' GB';
        if ($bytes >= 1048576)    return number_format($bytes / 1048576, 1) . ' MB';
        if ($bytes >= 1024)       return number_format($bytes / 1024, 0) . ' KB';
        return $bytes . ' B';
    }
}
