<?php

namespace NewsletterBridge\Admin\Tabs;

use NewsletterBridge\Config\FeaturedConfig;

class InEvidenzaTab {

    public static function render(): void {
        $enabled = FeaturedConfig::getEnabledPostTypes();
        $post_types = get_post_types(['public' => true], 'objects');
        ?>
        <h2>In Evidenza</h2>
        <p>Seleziona i post type su cui mostrare i campi <strong>In evidenza newsletter</strong> e <strong>Oggetto newsletter</strong> nell&apos;editor degli articoli.</p>
        <p class="description">Se usi già gli stessi campi via ACF, evita di abilitare lo stesso post type qui per non avere duplicati.</p>

        <table class="form-table">
            <tr>
                <th scope="row">Post type abilitati</th>
                <td>
                    <fieldset>
                        <?php foreach ($post_types as $slug => $object): ?>
                            <label style="display:block;margin-bottom:6px;">
                                <input type="checkbox" name="newsletter_featured_post_types[]" value="<?php echo esc_attr($slug); ?>" <?php checked(in_array($slug, $enabled, true)); ?> />
                                <?php echo esc_html($object->labels->singular_name ?? $slug); ?>
                                <code style="margin-left:4px;"><?php echo esc_html($slug); ?></code>
                            </label>
                        <?php endforeach; ?>
                    </fieldset>
                </td>
            </tr>
        </table>
        <?php
    }

    public static function save(array $data): void {
        $selected = [];
        if (!empty($data['newsletter_featured_post_types']) && is_array($data['newsletter_featured_post_types'])) {
            $selected = array_map('sanitize_key', $data['newsletter_featured_post_types']);
        }
        FeaturedConfig::saveEnabledPostTypes($selected);
    }
}
