<?php

declare(strict_types=1);

namespace PpPhp\Plugins;

use PpPhp\Core\EditPlugin;
use PpPhp\Core\PluginSupport;

class TimePicker implements EditPlugin
{
    use PluginSupport;

    public static function id(): string { return 'TimePicker'; }
    public static function label(): string { return 'Time Picker'; }
    public static function version(): string { return '1.1.0'; }
    public static function description(): string { return 'A themed time picker (flatpickr) with 12/24-hour, minute step and optional seconds.'; }

    public static function render(string $fieldName, mixed $value, array $settings): string
    {
        $name = self::e($fieldName);
        // Options read by the flatpickr enhancer in generated apps + the Designer.
        $attrs = '';
        if (in_array(strtolower((string) ($settings['hour24'] ?? 'yes')), ['0', 'no', 'false', 'off'], true)) {
            $attrs .= ' data-pp-time24="0"';   // 12-hour (AM/PM)
        }
        $step = (int) ($settings['step'] ?? 0);
        if ($step > 0) $attrs .= ' data-pp-step="' . $step . '"';
        if (in_array(strtolower((string) ($settings['seconds'] ?? 'no')), ['1', 'yes', 'true', 'on'], true)) {
            $attrs .= ' data-pp-seconds="1"';
        }
        return '<input type="text" name="' . $name . '" id="field_' . $name . '" value="' . self::e($value)
            . '" class="form-control pp-input" data-pp-picker="time"' . $attrs . ' autocomplete="off">';
    }

    public static function settingsSchema(): array
    {
        return [
            ['key' => 'hour24',  'type' => 'bool',   'label' => '24-hour clock', 'default' => 'yes', 'hint' => 'Off = 12-hour with AM/PM.'],
            ['key' => 'step',    'type' => 'number', 'label' => 'Minute step', 'default' => 0, 'hint' => 'e.g. 15 for quarter-hours; 0 = default.'],
            ['key' => 'seconds', 'type' => 'bool',   'label' => 'Include seconds', 'default' => 'no'],
        ];
    }

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