<?php

declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';

function handle_config_post(array $groups, string $returnFile): void
{
    if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') {
        return;
    }
    verify_csrf();
    foreach ($groups as $section => $meta) {
        save_config_section($section, array_keys($meta['fields']), $_POST);
    }
    flash('success', 'Configurações atualizadas e disponíveis para o aplicativo.');
    redirect($returnFile);
}

function render_config_page(array $groups): void
{
    foreach ($groups as $section => $meta) {
        $values = get_config($section);
        echo '<div class="card bg-primary text-white mb-4 omnimax-config-card">';
        echo '<div class="card-header card-header-warning">';
        echo '<div class="max-card-title"><div class="max-card-title-icon"><i class="fa-solid ' . e($meta['icon']) . '"></i></div><div><h2>' . e($meta['title']) . '</h2><p>' . e($meta['description']) . '</p></div></div>';
        echo '</div><div class="card-body"><div class="row">';
        foreach ($meta['fields'] as $key => $field) {
            render_config_field($key, $values[$key] ?? '', $field);
        }
        echo '</div></div></div>';
    }
}

function render_config_field(string $key, string $value, array $field): void
{
    $type = (string)($field['type'] ?? 'text');
    $label = (string)($field['label'] ?? $key);
    $help = (string)($field['help'] ?? '');
    $placeholder = (string)($field['placeholder'] ?? '');
    $columnClass = $type === 'textarea' ? 'col-12' : 'col-lg-6';

    echo '<div class="' . $columnClass . '"><div class="form-group">';
    echo '<label for="' . e($key) . '">' . e($label) . '</label>';

    if ($type === 'select') {
        echo '<select class="form-control" id="' . e($key) . '" name="' . e($key) . '">';
        foreach (($field['options'] ?? []) as $optionValue => $optionLabel) {
            $selected = (string)$optionValue === $value ? ' selected' : '';
            echo '<option value="' . e($optionValue) . '"' . $selected . '>' . e($optionLabel) . '</option>';
        }
        echo '</select>';
    } elseif ($type === 'textarea') {
        $rows = (int)($field['rows'] ?? 4);
        echo '<textarea class="form-control" id="' . e($key) . '" name="' . e($key) . '" rows="' . $rows . '" placeholder="' . e($placeholder) . '">' . e($value) . '</textarea>';
    } else {
        $attrs = '';
        foreach (['min', 'max', 'step'] as $attr) {
            if (isset($field[$attr])) {
                $attrs .= ' ' . $attr . '="' . e($field[$attr]) . '"';
            }
        }
        echo '<input class="form-control" id="' . e($key) . '" name="' . e($key) . '" type="' . e($type) . '" value="' . e($value) . '" placeholder="' . e($placeholder) . '"' . $attrs . '>';
    }

    if ($help !== '') {
        echo '<small class="form-text text-muted">' . e($help) . '</small>';
    }
    echo '</div></div>';
}
