<?php
namespace EIS\Component\EIS\Administrator\Service;

\defined('_JEXEC') or die;

use Joomla\CMS\Factory;
use Joomla\Database\DatabaseDriver;
use EIS\Component\EIS\Administrator\Helper\SettingsHelper;

class DocumentScanner
{
    /**
     * Führt den Scan aus.
     * @return int[] IDs der eingefügten Dateien
     */
    public static function run(?string $path = null, ?DatabaseDriver $db = null): array
    {
        $db  = $db ?: Factory::getDbo();
        $app = Factory::getApplication();

        // Pfad laden, wenn nicht übergeben
        $path = $path ?: SettingsHelper::getSetting('document_root', '/var/www/pdf');

        if (!$path || !is_dir($path)) {
            // Kein enqueueMessage, damit es auch im Task sauber läuft
            throw new \RuntimeException('Pfad ungültig oder nicht gesetzt: ' . (string)$path);
        }

        $data = self::scanFolder($path);

        // Achtung: du löscht aktuell immer alles -> danach ist alles "neu"
        $db->truncateTable('#__eis_documents');

        $newIds = self::saveToDb($data, null, $db);

        // Dauerhaft speichern (Frontend-Modul nutzt das ja schon)
        SettingsHelper::setSetting('last_new_ids', json_encode($newIds, JSON_UNESCAPED_SLASHES));
        SettingsHelper::setSetting('last_scan_at', date('Y-m-d H:i:s'));

        return $newIds;
    }

    private static function scanFolder(string $dir): array
    {
        $result = [];
        if (!is_dir($dir)) {
            return $result;
        }

        $entries = @scandir($dir);
        if ($entries === false) {
            return $result;
        }

        foreach ($entries as $file) {
            if ($file === '.' || $file === '..') {
                continue;
            }

            $fullPath = $dir . DIRECTORY_SEPARATOR . $file;

            if (is_dir($fullPath)) {
                $result[] = [
                    'name'     => $file,
                    'children' => self::scanFolder($fullPath)
                ];
            } elseif (is_file($fullPath) && strtolower(pathinfo($file, PATHINFO_EXTENSION)) === 'pdf') {
                $result[] = [
                    'name' => $file,
                    'path' => $fullPath
                ];
            }
        }

        usort($result, static fn($a, $b) => strcasecmp((string)$a['name'], (string)$b['name']));
        return $result;
    }

    private static function saveToDb(array $items, ?int $parentId, DatabaseDriver $db): array
    {
        $insertedFileIds = [];

        foreach ($items as $item) {
            $name     = $db->quote($item['name']);
            $path     = $db->quote($item['path'] ?? '');
            $parent   = $parentId !== null ? (int)$parentId : 'NULL';
            $isFolder = isset($item['children']) ? 1 : 0;

            $query = $db->getQuery(true)
                ->insert($db->quoteName('#__eis_documents'))
                ->columns(['name', 'path', 'parent_id', 'is_folder'])
                ->values("$name, $path, $parent, $isFolder");

            $db->setQuery($query)->execute();
            $insertedId = (int) $db->insertid();

            if ($isFolder && !empty($item['children'])) {
                $childIds = self::saveToDb($item['children'], $insertedId, $db);
                $insertedFileIds = array_merge($insertedFileIds, $childIds);
            } else {
                $insertedFileIds[] = $insertedId;
            }
        }

        return $insertedFileIds;
    }
}
