<?php

namespace EIS\Component\EIS\Administrator\Controller;

\defined('_JEXEC') or die;

use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\MVC\Controller\BaseController;
use Joomla\CMS\Router\Route;
use Joomla\CMS\Session\Session;
use Joomla\Database\DatabaseDriver;
use EIS\Component\EIS\Administrator\Helper\SettingsHelper;
use EIS\Component\EIS\Administrator\Service\DocumentScanner;

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

    /**
     * Button-Aktion: PDF-Verzeichnis scannen und in Datenbank speichern
     */

    public function scan(): void
{
    // CSRF prüfen (Form hat Token)
    if (!Session::checkToken('post')) {
        throw new \RuntimeException(Text::_('JINVALID_TOKEN'), 403);
    }

    $app = Factory::getApplication();

    try {
        $newIds = DocumentScanner::run();

        // Wie bisher: New IDs für die View (virtueller Ordner "Neue Dokumente")
        $app->setUserState('com_eis.new_ids', $newIds);

        $app->enqueueMessage(Text::_('COM_EIS_MSG_SCAN_DONE') ?: 'PDF-Struktur erfolgreich gespeichert.', 'message');
    } catch (\Throwable $e) {
        $app->enqueueMessage($e->getMessage(), 'error');
    }

    $this->setRedirect(Route::_('index.php?option=com_eis&view=main', false));
}
    /**
     * Rekursive Verzeichnisanalyse
     */
    private 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' => $this->scanFolder($fullPath)
                ];
            } elseif (is_file($fullPath) && strtolower(pathinfo($file, PATHINFO_EXTENSION)) === 'pdf') {
                $result[] = [
                    'name' => $file,
                    'path' => $fullPath
                ];
            }
        }

        // Alphabetisch stabil sortieren
        usort($result, static function ($a, $b) {
            return strcasecmp((string)$a['name'], (string)$b['name']);
        });

        return $result;
    }

    /**
     * Struktur rekursiv in die Datenbank schreiben
     * @return int[] Insert-IDs aller neu eingefügten Dateien (für „Neue Dokumente“)
     */
    private function saveToDb(array $items, ?int $parentId, DatabaseDriver $db): array
    {
        $insertedFileIds = [];

        foreach ($items as $item) {
            $name     = $db->quote($item['name']);
            $path     = $db->quote($item['path'] ?? ''); // leer 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)->execute();

            $insertedId = (int)$db->insertid();

            if ($isFolder && !empty($item['children'])) {
                // Kinder speichern
                $childIds = $this->saveToDb($item['children'], $insertedId, $db);
                // Nur Datei-IDs sammeln
                $insertedFileIds = array_merge($insertedFileIds, $childIds);
            } else {
                // Datei -> ID merken
                $insertedFileIds[] = $insertedId;
            }
        }

        return $insertedFileIds;
    }

    public function rename(): void
    {
        // CSRF prüfen
        if (!Session::checkToken('post')) {
            throw new \RuntimeException(Text::_('JINVALID_TOKEN'), 403);
        }

        $app   = Factory::getApplication();
        $id    = (int) $app->input->post->get('id', 0);
        $title = trim((string) $app->input->post->get('title', '', 'string'));

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

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

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

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

    public function saveAccess(): void
{
    if (!\Joomla\CMS\Session\Session::checkToken('post')) {
        throw new \RuntimeException(\JText::_('JINVALID_TOKEN'), 403);
    }

    $app = \Joomla\CMS\Factory::getApplication();
    $db  = \Joomla\CMS\Factory::getDbo();

    $folderId    = (int) $app->input->post->get('folder_id', 0);
    $viewlevelId = (int) $app->input->post->get('viewlevel_id', 0);

    // Validierung: folderId muss Top-Level-Ordner sein
    if ($folderId <= 0) {
        $app->enqueueMessage('Ungültiger Ordner.', 'error');
        $this->setRedirect(\Joomla\CMS\Router\Route::_('index.php?option=com_eis&view=main', false));
        return;
    }

    // prüfen, ob Top-Level-Ordner
    $q = $db->getQuery(true)
        ->select($db->quoteName(['id','is_folder','parent_id']))
        ->from($db->quoteName('#__eis_documents'))
        ->where($db->quoteName('id') . ' = ' . (int)$folderId);
    $db->setQuery($q);
    $row = $db->loadAssoc();

    if (!$row || (int)$row['is_folder'] !== 1 || $row['parent_id'] !== null) {
        $app->enqueueMessage('Nur Top-Level-Ordner können berechtigt werden.', 'warning');
        $this->setRedirect(\Joomla\CMS\Router\Route::_('index.php?option=com_eis&view=main', false));
        return;
    }

    // Viewlevel validieren
    if ($viewlevelId <= 0) {
        // löschen (öffentlich)
        $db->setQuery(
            $db->getQuery(true)
               ->delete($db->quoteName('#__eis_folder_access'))
               ->where($db->quoteName('folder_id') . ' = ' . (int)$folderId)
        )->execute();

        $app->enqueueMessage('Berechtigung entfernt (öffentlich).', 'message');
        $this->setRedirect(\Joomla\CMS\Router\Route::_('index.php?option=com_eis&view=main', false));
        return;
    }

    // upsert
    $sql = 'INSERT INTO ' . $db->quoteName('#__eis_folder_access')
         . ' (' . $db->quoteName('folder_id') . ', ' . $db->quoteName('viewlevel_id') . ') VALUES ('
         . (int)$folderId . ', ' . (int)$viewlevelId . ')'
         . ' ON DUPLICATE KEY UPDATE ' . $db->quoteName('viewlevel_id') . ' = VALUES(' . $db->quoteName('viewlevel_id') . ')';
    $db->setQuery($sql)->execute();

    $app->enqueueMessage('Berechtigung gespeichert.', 'message');
    $this->setRedirect(\Joomla\CMS\Router\Route::_('index.php?option=com_eis&view=main', false));
}

}
