<?php
/**
 * Format Generator - converts image URLs to various posting formats
 * Compatible with PHP 7.2+
 */

class FormatGenerator
{
    /**
     * Predefined format templates
     */
    private $formats = [
        'bbcode' => [
            'name' => 'BBCode',
            'description' => 'Standard forum BBCode',
            'template' => '[img]{url}[/img]',
            'separator' => "\n",
        ],
        'bbcode_linked' => [
            'name' => 'BBCode (clickable)',
            'description' => 'BBCode with link to original',
            'template' => '[url={original}][img]{url}[/img][/url]',
            'separator' => "\n",
        ],
        'html' => [
            'name' => 'HTML',
            'description' => 'HTML img tag',
            'template' => '<img src="{url}" alt="{title}">',
            'separator' => "\n",
        ],
        'html_linked' => [
            'name' => 'HTML (clickable)',
            'description' => 'HTML img with link to original',
            'template' => '<a href="{original}" target="_blank"><img src="{url}" alt="{title}"></a>',
            'separator' => "\n",
        ],
        'html_figure' => [
            'name' => 'HTML Figure',
            'description' => 'HTML5 figure with caption',
            'template' => "<figure>\n  <a href=\"{original}\" target=\"_blank\"><img src=\"{url}\" alt=\"{title}\"></a>\n  <figcaption>{title}</figcaption>\n</figure>",
            'separator' => "\n\n",
        ],
        'markdown' => [
            'name' => 'Markdown',
            'description' => 'Markdown image syntax',
            'template' => '![{title}]({url})',
            'separator' => "\n",
        ],
        'markdown_linked' => [
            'name' => 'Markdown (clickable)',
            'description' => 'Markdown with link to original',
            'template' => '[![{title}]({url})]({original})',
            'separator' => "\n",
        ],
        'url_only' => [
            'name' => 'URL only',
            'description' => 'Just the image URL',
            'template' => '{url}',
            'separator' => "\n",
        ],
        'url_list' => [
            'name' => 'URL list (comma)',
            'description' => 'Comma-separated URLs',
            'template' => '{url}',
            'separator' => ', ',
        ],

        // ============ FORUM PRESETS ============

        'bjdclub' => [
            'name' => 'BJDClub.ru',
            'description' => 'Оптимизировано для BJDClub (phpBB)',
            'template' => '[url={original}][img]{url}[/img][/url]',
            'separator' => "\n\n",
            'category' => 'forum',
        ],
        'babiki' => [
            'name' => 'Babiki.ru',
            'description' => 'Оптимизировано для Бэбиков',
            'template' => '<a href="{original}" target="_blank"><img src="{url}" alt="{title}"></a>',
            'separator' => "\n\n",
            'category' => 'forum',
        ],
        'babiki_simple' => [
            'name' => 'Babiki.ru (простой)',
            'description' => 'Только картинки для Бэбиков',
            'template' => '<img src="{url}" alt="{title}">',
            'separator' => "\n",
            'category' => 'forum',
        ],
        'doll_forum' => [
            'name' => 'Кукольный форум',
            'description' => 'Универсальный BBCode для кукольных форумов',
            'template' => '[url={original}][img]{url}[/img][/url]',
            'separator' => "\n",
            'category' => 'forum',
        ],
    ];

    /**
     * Add a custom format
     *
     * @param string $key Format key
     * @param string $name Display name
     * @param string $template Template with placeholders
     * @param string $separator Separator between multiple images
     * @param string $description Format description
     */
    public function addFormat($key, $name, $template, $separator = "\n", $description = '')
    {
        $this->formats[$key] = [
            'name' => $name,
            'description' => $description,
            'template' => $template,
            'separator' => $separator,
        ];
    }

    /**
     * Get all available formats
     *
     * @return array Format definitions
     */
    public function getFormats()
    {
        return $this->formats;
    }

    /**
     * Generate formatted output for a single image
     *
     * @param string $formatKey Format key
     * @param array $imageData Image data with url, original, title
     * @return string Formatted output
     */
    public function generate($formatKey, $imageData)
    {
        if (!isset($this->formats[$formatKey])) {
            throw new InvalidArgumentException("Unknown format: {$formatKey}");
        }

        $template = $this->formats[$formatKey]['template'];

        $replacements = [
            '{url}' => isset($imageData['url']) ? $imageData['url'] : '',
            '{original}' => isset($imageData['original']) ? $imageData['original'] : (isset($imageData['url']) ? $imageData['url'] : ''),
            '{title}' => htmlspecialchars(isset($imageData['title']) ? $imageData['title'] : 'Image', ENT_QUOTES),
            '{description}' => htmlspecialchars(isset($imageData['description']) ? $imageData['description'] : '', ENT_QUOTES),
            '{photo_id}' => isset($imageData['photo_id']) ? $imageData['photo_id'] : '',
            '{width}' => isset($imageData['width']) ? $imageData['width'] : '',
            '{height}' => isset($imageData['height']) ? $imageData['height'] : '',
        ];

        return str_replace(array_keys($replacements), array_values($replacements), $template);
    }

    /**
     * Generate formatted output for multiple images
     *
     * @param string $formatKey Format key
     * @param array $images Array of image data
     * @return string Formatted output
     */
    public function generateMultiple($formatKey, $images)
    {
        if (!isset($this->formats[$formatKey])) {
            throw new InvalidArgumentException("Unknown format: {$formatKey}");
        }

        $separator = $this->formats[$formatKey]['separator'];
        $outputs = [];

        foreach ($images as $imageData) {
            $outputs[] = $this->generate($formatKey, $imageData);
        }

        return implode($separator, $outputs);
    }

    /**
     * Generate output in all formats at once
     *
     * @param array $images Array of image data
     * @return array Keyed by format key
     */
    public function generateAll($images)
    {
        $result = [];

        foreach (array_keys($this->formats) as $formatKey) {
            $result[$formatKey] = [
                'name' => $this->formats[$formatKey]['name'],
                'description' => $this->formats[$formatKey]['description'],
                'output' => $this->generateMultiple($formatKey, $images),
            ];
        }

        return $result;
    }
}
