<?php
namespace PpPhp\Plugins;
use PpPhp\Core\EditPlugin;

class DatePicker implements EditPlugin
{
    public static function id(): string { return 'DatePicker'; }
    public static function label(): string { return 'Date Picker'; }
    public static function version(): string { return '1.0.0'; }
    public static function description(): string { return 'Themed calendar date/datetime picker (flatpickr) with format options.'; }
    /** Display date formats offered in the properties panel (mapped to flatpickr tokens at runtime). */
    private const FORMATS = ['YYYY-MM-DD', 'YYYY/MM/DD', 'YYYY.MM.DD', 'DD-MM-YYYY', 'DD/MM/YYYY', 'MM/DD/YYYY'];

    public static function render(string $fieldName, mixed $value, array $settings): string {
        // data-pp-picker: enhanced by the bundled flatpickr in generated apps
        // (modern themed calendar); shows a plain input where flatpickr is absent.
        $withTime = in_array(strtolower((string) ($settings['withTime'] ?? '')), ['1', 'yes', 'true', 'on'], true);
        $kind = $withTime ? 'datetime' : 'date';
        $fmt = (string) ($settings['dateFormat'] ?? '');
        $fmtAttr = in_array($fmt, self::FORMATS, true) ? ' data-pp-format="' . htmlspecialchars($fmt) . '"' : '';
        return '<input type="text" name="' . $fieldName . '" id="field_' . $fieldName . '" value="' . htmlspecialchars((string) ($value ?? '')) . '" class="form-control pp-input" data-pp-picker="' . $kind . '"' . $fmtAttr . ' autocomplete="off">';
    }
    public static function settingsSchema(): array {
        return [
            ['key' => 'dateFormat', 'label' => 'Date format', 'type' => 'select', 'options' => self::FORMATS, 'default' => 'YYYY-MM-DD', 'hint' => 'How the date is shown and stored.'],
            ['key' => 'withTime', 'label' => 'Include time', 'type' => 'bool', 'default' => 'no', 'hint' => 'Show a time selector alongside the date.'],
        ];
    }
    public static function assets(): array { return ['js'=>['assets/vendor/flatpickr/flatpickr.min.js'], 'css'=>['assets/vendor/flatpickr/flatpickr.min.css']]; }
}