<?php
namespace PpPhp\Plugins;
use PpPhp\Core\EditPlugin;
use PpPhp\Core\Designer\FieldControl\LookupOptions;

/**
 * Styled checkbox — two modes:
 *   single — one on/off checkbox with configurable stored values (1/0, Y/N…)
 *   group  — multiple checkboxes from a manual list or a database-table
 *            lookup (with WHERE condition); selections stored as a
 *            comma-separated list in the field.
 * Size, color, layout and disabled state configurable from the Designer.
 */
class Checkbox implements EditPlugin
{
    public static function id(): string { return 'Checkbox'; }
    public static function label(): string { return 'Checkbox'; }
    public static function version(): string { return '1.0.0'; }
    public static function description(): string { return 'A single checkbox storing a yes/no value.'; }

    public static function render(string $fieldName, mixed $value, array $settings): string
    {
        $size = (string) ($settings['size'] ?? 'md');
        if (!in_array($size, ['sm', 'md', 'lg'], true)) $size = 'md';
        $colors = ['primary', 'info', 'success', 'danger', 'secondary', 'warning', 'dark'];
        $color = (string) ($settings['color'] ?? 'primary');
        if (!in_array($color, $colors, true)) $color = 'primary';
        $disabled = ($settings['state'] ?? '') === 'disabled';

        if (($settings['mode'] ?? 'single') === 'group') {
            return self::group($fieldName, $value, $settings, $size, $color, $disabled);
        }

        // ── single on/off checkbox ──
        $text = trim((string) ($settings['text'] ?? ''));
        $on = trim((string) ($settings['onValue'] ?? '1'));
        if ($on === '') $on = '1';
        $off = trim((string) ($settings['offValue'] ?? '0'));
        $checked = (string) $value === $on
            || ($on === '1' && in_array(strtolower((string) $value), ['1', 'true', 'yes', 'on'], true));

        return '<label class="pp-ctl pp-checkbox pp-sz-' . $size . ' pp-c-' . $color . ($disabled ? ' pp-disabled' : '') . '">'
            . '<input type="hidden" name="' . $fieldName . '" value="' . htmlspecialchars($off) . '">'
            . '<input type="checkbox" name="' . $fieldName . '" id="field_' . $fieldName . '" value="' . htmlspecialchars($on) . '"'
            . ($checked ? ' checked' : '') . ($disabled ? ' disabled' : '') . '>'
            . '<span class="pp-ctl-box"><i class="bi bi-check-lg"></i></span>'
            . ($text !== '' ? '<span class="pp-ctl-txt">' . htmlspecialchars($text) . '</span>' : '')
            . '</label>';
    }

    /** Multi-checkbox group — selections submitted as field[] and stored CSV. */
    private static function group(string $fieldName, mixed $value, array $settings, string $size, string $color, bool $disabled): string
    {
        $stack = ($settings['layout'] ?? 'inline') === 'stacked';
        $options = LookupOptions::resolve($settings);
        if ($options === []) $options = ['Option A' => 'Option A', 'Option B' => 'Option B'];
        $selected = array_filter(array_map('trim', explode(',', (string) $value)), 'strlen');

        $html = '<div class="pp-ctl-group pp-sz-' . $size . ' pp-c-' . $color . ($stack ? ' pp-stack' : '') . '">'
            . '<input type="hidden" name="' . $fieldName . '" value="">';
        $i = 0;
        foreach ($options as $val => $label) {
            $valEsc = htmlspecialchars((string) $val);
            $checked = in_array((string) $val, $selected, true);
            $html .= '<label class="pp-ctl pp-checkbox' . ($disabled ? ' pp-disabled' : '') . '">'
                . '<input type="checkbox" name="' . $fieldName . '[]"' . ($i === 0 ? ' id="field_' . $fieldName . '"' : '')
                . ' value="' . $valEsc . '"' . ($checked ? ' checked' : '') . ($disabled ? ' disabled' : '') . '>'
                . '<span class="pp-ctl-box"><i class="bi bi-check-lg"></i></span>'
                . '<span class="pp-ctl-txt">' . htmlspecialchars((string) $label) . '</span></label>';
            $i++;
        }

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

    public static function settingsSchema(): array
    {
        return array_merge([
            ['key' => 'mode', 'label' => 'Mode', 'type' => 'select', 'options' => ['single', 'group'], 'default' => 'single', 'hint' => 'single: one on/off box. group: many options, stored comma-separated.'],
            ['key' => 'text', 'label' => 'Inline text (single)', 'type' => 'text', 'default' => ''],
            ['key' => 'onValue', 'label' => 'Checked value (single)', 'type' => 'text', 'default' => '1', 'hint' => 'Stored when checked. Examples: 1 · Y · active'],
            ['key' => 'offValue', 'label' => 'Unchecked value (single)', 'type' => 'text', 'default' => '0', 'hint' => 'Stored when unchecked. Examples: 0 · N · inactive'],
        ], LookupOptions::schema(), [
            ['key' => 'layout', 'label' => 'Layout (group)', 'type' => 'select', 'options' => ['inline', 'stacked'], 'default' => 'inline'],
            ['key' => 'size', 'label' => 'Size', 'type' => 'select', 'options' => ['sm', 'md', 'lg'], 'default' => 'md'],
            ['key' => 'color', 'label' => 'Color', 'type' => 'select', 'options' => ['primary', 'info', 'success', 'danger', 'secondary', 'warning', 'dark'], 'default' => 'primary'],
            ['key' => 'state', 'label' => 'State', 'type' => 'select', 'options' => ['normal', 'disabled'], 'default' => 'normal'],
        ]);
    }

    public static function assets(): array { return ['js' => [], 'css' => []]; }
}