<?php

/**
 * @package         Tassos Code Snippets
 * @version         1.0.1-RC2 Free
 *
 * @author          Tassos Marinos <info@tassos.gr>
 * @link            https://www.tassos.gr
 * @copyright       Copyright © 2026 Tassos Marinos All Rights Reserved
 * @license         GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> or later
 */

namespace Tassos\CodeSnippets\Administrator\View\Logs;

defined('_JEXEC') or die;

use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\MVC\View\HtmlView as BaseHtmlView;
use Joomla\CMS\Toolbar\ToolbarHelper;

/**
 * View class for the Error Logs page.
 */
class HtmlView extends BaseHtmlView
{
    /**
     * Full paths to all discovered log files, sorted by modified date (newest first).
     *
     * @var array
     */
    public $logFiles = [];

    /**
     * The filename (basename) of the currently selected log file.
     *
     * @var string
     */
    public $selectedFile = '';

    /**
     * Content of the selected log file (reversed so newest entries appear first).
     *
     * @var string
     */
    public $logContent = '';

    /**
     * Display the view.
     *
     * @param   string|null  $tpl  Template name
     *
     * @return  void
     */
    public function display($tpl = null)
    {
        $app     = Factory::getApplication();
        $logPath = $app->get('log_path') . '/tassos_code_snippets';

        // Discover all snippet log files
        $pattern        = $logPath . '/snippet_*.log';
        $this->logFiles = glob($pattern) ?: [];

        // Sort by modification time, newest first
        usort($this->logFiles, static function ($a, $b)
        {
            return filemtime($b) - filemtime($a);
        });

        // Resolve the file to display
        $requestedFile = $app->input->getString('logfile', '');

        if ($requestedFile && preg_match('/^snippet_[a-z0-9\-_]+_\d+\.log$/', $requestedFile))
        {
            $fullPath = $logPath . '/' . $requestedFile;

            if (is_file($fullPath) && in_array($fullPath, $this->logFiles, true))
            {
                $this->selectedFile = $requestedFile;
                $this->logContent   = $this->readReversed($fullPath);
            }
        }
        elseif (!empty($this->logFiles))
        {
            // Auto-select the newest file
            $this->selectedFile = basename($this->logFiles[0]);
            $this->logContent   = $this->readReversed($this->logFiles[0]);
        }

        $this->addToolbar();

        parent::display($tpl);
    }

    /**
     * Read a file and return its contents with lines reversed so the newest
     * entries (written at the end) appear at the top.
     *
     * @param   string  $path  Full file path
     *
     * @return  string
     */
    private function readReversed(string $path): string
    {
        $content = file_get_contents($path);

        if ($content === false || $content === '')
        {
            return '';
        }

        $lines = explode("\n", $content);

        return implode("\n", array_reverse($lines));
    }

    /**
     * Add the page title and toolbar.
     *
     * @return  void
     */
    protected function addToolbar(): void
    {
        ToolbarHelper::title(Text::_('COM_TASSOSCODESNIPPETS_LOGS_TITLE'), 'file-alt');
        ToolbarHelper::back('JTOOLBAR_BACK', 'index.php?option=com_tassoscodesnippets');
    }
}
