<?php
/**
 * BookiFlex
 *
 * @package   BookiFlex
 * @author    BookiFlex
 * @copyright Copyright (c) 2025 BookiFlex
 * @license   GPL-2.0-or-later
 *
 * @link      https://bookiflex.com
 */

declare(strict_types=1);

namespace BookiFlex\Core\Admin\Field;

use Carbon_Fields\Field;

defined( 'ABSPATH' ) || exit;

class RadioCard
{
    /**
     * Create radio card fields (html + hidden).
     *
     * Usage:
     *   $fields = array_merge($fields, RadioCard::make('field_name', 'Label', $options, 'default'));
     *
     * @param string $name    Field name (used for the hidden field storing the value)
     * @param string $label   Field label displayed above the cards
     * @param array  $options Associative array: value => ['title' => '...', 'description' => '...']
     * @param string $default Default selected value
     * @return array<\Carbon_Fields\Field\Field>
     */
    public static function make(
        string $name,
        string $label,
        array $options,
        string $default = '',
        bool $vertical = false
    ): array {
        $cardsHtml = self::renderCardsHtml($name, $options, $vertical);

        return [
            Field::make('html', $name . '_radio_card_html')
                ->set_html(
                    sprintf('<label class="cf-field__label">%s</label>', esc_html($label))
                    . $cardsHtml
                ),
            Field::make('hidden', $name)
                ->set_default_value($default),
        ];
    }

    private static function renderCardsHtml(string $fieldName, array $options, bool $vertical = false): string
    {
        $classes = 'bflex-radio-cards' . ($vertical ? ' bflex-radio-cards--vertical' : '');

        $html = sprintf(
            '<div class="%s" data-field="%s">',
            esc_attr($classes),
            esc_attr($fieldName)
        );

        foreach ($options as $value => $option) {
            $title = is_array($option) ? ($option['title'] ?? '') : (string) $option;
            $description = is_array($option) ? ($option['description'] ?? '') : '';
            $descriptionHtml = $description
                ? sprintf('<div class="bflex-radio-card__description">%s</div>', wp_kses_post($description))
                : '';

            $html .= sprintf(
                '<div class="bflex-radio-card" data-value="%s">'
                . '<div class="bflex-radio-card__indicator"></div>'
                . '<div class="bflex-radio-card__content">'
                . '<div class="bflex-radio-card__title">%s</div>'
                . '%s'
                . '</div>'
                . '</div>',
                esc_attr((string) $value),
                esc_html($title),
                $descriptionHtml
            );
        }

        $html .= '</div>';
        return $html;
    }
}
