<?php

/**
 * Страница кастоматизации темы
 */

function admin_theme_customization_page()
{
    // Получаем настройки кастоматизации из активной темы
    $customizationSettings = [];
    if (function_exists('apply_filters')) {
        $customizationSettings = apply_filters('theme_customization_settings', $customizationSettings);
    }

    if (!is_array($customizationSettings)) {
        $customizationSettings = [];
    }

    // Обработка сохранения настроек
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['save_customization'])) {
        // Здесь будет логика сохранения настроек кастоматизации
        // Пока просто показываем сообщение
        $content = '<div class="alert alert-success">
            <i class="fas fa-check-circle"></i> Настройки кастоматизации сохранены (функционал будет реализован позже).
        </div>';
    } else {
        $content = '';
    }

    $content .= '<div class="container-fluid">
        <h1 class="mb-4">Кастоматизация темы</h1>
        <p class="text-muted mb-3">
            Здесь вы можете настроить внешний вид активной темы: цвета, шрифты, размеры и другие параметры.
        </p>';

    if (empty($customizationSettings)) {
        $content .= '<div class="alert alert-warning">
            <i class="fas fa-exclamation-triangle"></i> Активная тема не предоставила настройки кастоматизации.
        </div>';
    } else {
        $content .= '<form method="POST" action="' . admin_url('theme-customization') . '">
            <div class="card">
                <div class="card-header">
                    <i class="fas fa-paint-brush"></i> Настройки кастоматизации
                </div>
                <div class="card-body">';

        // Генерируем форму на основе настроек темы
        foreach ($customizationSettings as $sectionId => $section) {
            if (!is_array($section)) {
                continue;
            }

            $sectionTitle = $section['title'] ?? ucfirst(str_replace('_', ' ', $sectionId));
            $sectionDescription = $section['description'] ?? '';
            $fields = $section['fields'] ?? [];

            $content .= '<div class="mb-4">
                <h4 class="mb-3">' . htmlspecialchars((string)$sectionTitle, ENT_QUOTES, 'UTF-8') . '</h4>';

            if (!empty($sectionDescription)) {
                $content .= '<p class="text-muted mb-3">' . htmlspecialchars((string)$sectionDescription, ENT_QUOTES, 'UTF-8') . '</p>';
            }

            foreach ($fields as $fieldId => $field) {
                if (!is_array($field)) {
                    continue;
                }

                $fieldType = $field['type'] ?? 'text';
                $fieldLabel = $field['label'] ?? ucfirst(str_replace('_', ' ', $fieldId));
                $fieldDescription = $field['description'] ?? '';
                $fieldDefault = $field['default'] ?? '';
                $fieldValue = $field['value'] ?? $fieldDefault;
                $fieldName = 'customization[' . htmlspecialchars((string)$sectionId, ENT_QUOTES, 'UTF-8') . '][' . htmlspecialchars((string)$fieldId, ENT_QUOTES, 'UTF-8') . ']';

                $content .= '<div class="mb-3">
                    <label for="' . htmlspecialchars((string)$fieldId, ENT_QUOTES, 'UTF-8') . '" class="form-label">
                        ' . htmlspecialchars((string)$fieldLabel, ENT_QUOTES, 'UTF-8') . '
                    </label>';

                if (!empty($fieldDescription)) {
                    $content .= '<small class="form-text text-muted d-block mb-2">' . htmlspecialchars((string)$fieldDescription, ENT_QUOTES, 'UTF-8') . '</small>';
                }

                switch ($fieldType) {
                    case 'color':
                        $content .= '<input type="color" class="form-control form-control-color" id="' . htmlspecialchars((string)$fieldId, ENT_QUOTES, 'UTF-8') . '" name="' . $fieldName . '" value="' . htmlspecialchars((string)$fieldValue, ENT_QUOTES, 'UTF-8') . '">';
                        break;
                    case 'textarea':
                        $content .= '<textarea class="form-control" id="' . htmlspecialchars((string)$fieldId, ENT_QUOTES, 'UTF-8') . '" name="' . $fieldName . '" rows="3">' . htmlspecialchars((string)$fieldValue, ENT_QUOTES, 'UTF-8') . '</textarea>';
                        break;
                    case 'select':
                        $options = $field['options'] ?? [];
                        $content .= '<select class="form-select" id="' . htmlspecialchars((string)$fieldId, ENT_QUOTES, 'UTF-8') . '" name="' . $fieldName . '">';
                        foreach ($options as $optionValue => $optionLabel) {
                            $selected = ($optionValue == $fieldValue) ? ' selected' : '';
                            $content .= '<option value="' . htmlspecialchars((string)$optionValue, ENT_QUOTES, 'UTF-8') . '"' . $selected . '>' . htmlspecialchars((string)$optionLabel, ENT_QUOTES, 'UTF-8') . '</option>';
                        }
                        $content .= '</select>';
                        break;
                    case 'number':
                        $min = $field['min'] ?? '';
                        $max = $field['max'] ?? '';
                        $step = $field['step'] ?? '1';
                        $content .= '<input type="number" class="form-control" id="' . htmlspecialchars((string)$fieldId, ENT_QUOTES, 'UTF-8') . '" name="' . $fieldName . '" value="' . htmlspecialchars((string)$fieldValue, ENT_QUOTES, 'UTF-8') . '"' .
                            (!empty($min) ? ' min="' . htmlspecialchars((string)$min, ENT_QUOTES, 'UTF-8') . '"' : '') .
                            (!empty($max) ? ' max="' . htmlspecialchars((string)$max, ENT_QUOTES, 'UTF-8') . '"' : '') .
                            ' step="' . htmlspecialchars((string)$step, ENT_QUOTES, 'UTF-8') . '">';
                        break;
                    default: // text
                        $content .= '<input type="text" class="form-control" id="' . htmlspecialchars((string)$fieldId, ENT_QUOTES, 'UTF-8') . '" name="' . $fieldName . '" value="' . htmlspecialchars((string)$fieldValue, ENT_QUOTES, 'UTF-8') . '">';
                        break;
                }

                $content .= '</div>';
            }

            $content .= '</div>';
        }

        $content .= '    </div>
                <div class="card-footer">
                    <button type="submit" name="save_customization" class="btn btn-primary">
                        <i class="fas fa-save"></i> Сохранить настройки
                    </button>
                    <button type="reset" class="btn btn-secondary">
                        <i class="fas fa-undo"></i> Сбросить
                    </button>
                </div>
            </div>
        </form>';
    }

    $content .= '</div>';

    if (function_exists('render_admin_layout')) {
        return render_admin_layout([
            'title' => 'Кастоматизация темы - Flowaxy CMS',
            'content' => $content,
            'pageHeaderIcon' => 'fas fa-paint-brush',
            'pageBreadcrumbs' => [
                ['title' => 'Головна', 'url' => admin_url('dashboard'), 'page' => 'dashboard'],
                ['title' => 'Кастоматизация темы', 'page' => 'theme-customization'],
            ],
        ]);
    }

    echo $content;
}
