<?php

namespace EIS\Component\EIS\Administrator\Controller;

\defined('_JEXEC') or die;

use Joomla\CMS\Factory;
use Joomla\CMS\MVC\Controller\BaseController;
use Joomla\Database\DatabaseDriver;

class DisplayController extends BaseController
{
    protected $default_view = 'main';

    /**
     * Button-Aktion: PDF-Verzeichnis scannen und in Datenbank speichern
     */
    public function scan(): void
    {
        $db = Factory::getDbo();

        // Pfad aus Tabelle laden
        $query = $db->getQuery(true)
            ->select($db->quoteName('pdf_path'))
            ->from($db->quoteName('#__eis_settings'))
            ->order('id ASC')
            ->setLimit(1);

        $db->setQuery($query);
        $path = $db->loadResult();

        if (!$path || !is_dir($path)) {
            Factory::getApplication()->enqueueMessage('Pfad ungültig oder nicht gesetzt: ' . $path, 'error');
            $this->setRedirect('index.php?option=com_eis&view=main');
            return;
        }

        // Verzeichnis rekursiv scannen
        $data = $this->scanFolder($path);

        // Alte Einträge löschen
        $db->truncateTable('#__eis_documents');

        // In Datenbank speichern
        $this->saveToDb($data, null, $db);

        // Erfolgsmeldung
        Factory::getApplication()->enqueueMessage('PDF-Struktur erfolgreich gespeichert.', 'message');
        $this->setRedirect('index.php?option=com_eis&view=main');
    }

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

        foreach (scandir($dir) as $file) {
            if ($file === '.' || $file === '..') {
                continue;
            }
            $fullPath = $dir . DIRECTORY_SEPARATOR . $file;

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

        return $result;
    }

    /**
     * Struktur rekursiv in die Datenbank schreiben
     */
    private function saveToDb(array $items, ?int $parentId, DatabaseDriver $db): void
    {
        foreach ($items as $item) {
            $name     = $db->quote($item['name']);
            $path     = $db->quote($item['path'] ?? '');  // Leerer String statt NULL
            $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);
            $db->execute();

            $insertedId = $db->insertid();

            if ($isFolder && !empty($item['children'])) {
                $this->saveToDb($item['children'], $insertedId, $db);
            }
        }
    }
    public function rename(): void
    {
        // CSRF prüfen
        \Joomla\CMS\Session\Session::checkToken() or jexit(\JText::_('JINVALID_TOKEN'));

        $app = \Joomla\CMS\Factory::getApplication();
        $id = (int) $app->input->get('id');
        $title = trim((string) $app->input->get('title', '', 'STRING'));

        if ($id <= 0) {
            $app->enqueueMessage('Ungültige ID', 'error');
            $this->setRedirect('index.php?option=com_eis&view=main');
            return;
        }

        /** @var \Joomla\Database\DatabaseDriver $db */
        $db = \Joomla\CMS\Factory::getDbo();
        $query = $db->getQuery(true)
            ->update($db->quoteName('#__eis_documents'))
            ->set($db->quoteName('title') . ' = ' . ($title === '' ? 'NULL' : $db->quote($title)))
            ->where($db->quoteName('id') . ' = ' . (int) $id);

        try {
            $db->setQuery($query)->execute();
            $app->enqueueMessage('Anzeigename gespeichert', 'message');
        } catch (\Throwable $e) {
            $app->enqueueMessage('Fehler beim Speichern: ' . $e->getMessage(), 'error');
        }

        $this->setRedirect('index.php?option=com_eis&view=main');
    }
}
