<?php
namespace PpPhp\Plugins;

use PpPhp\Core\ValidationPlugin;

class TimeValidRule implements ValidationPlugin
{
    public static function id(): string { return 'time'; }
    public static function label(): string { return 'Time / range'; }
    public static function group(): string { return 'Date & time'; }

    public static function paramsSchema(): array
    {
        return [
            ['key' => 'min', 'type' => 'text', 'label' => 'Earliest (HH:MM)', 'default' => '', 'placeholder' => '09:00'],
            ['key' => 'max', 'type' => 'text', 'label' => 'Latest (HH:MM)', 'default' => '', 'placeholder' => '17:00'],
        ];
    }

    public static function appliesTo(): array { return ['time', 'text']; }
    public static function defaultMessage(): string { return 'Enter a valid time.'; }

    /** Minutes since midnight, or null if not a valid HH:MM[:SS]. */
    private static function mins(string $s): ?int
    {
        if (!preg_match('/^(\d{1,2}):(\d{2})(?::\d{2})?$/', trim($s), $m)) return null;
        $h = (int) $m[1]; $mi = (int) $m[2];
        if ($h > 23 || $mi > 59) return null;
        return $h * 60 + $mi;
    }

    public static function serverCheck(mixed $value, array $params, array $record = []): bool
    {
        $t = self::mins((string) $value);
        if ($t === null) return false;
        if (($params['min'] ?? '') !== '' && ($lo = self::mins((string) $params['min'])) !== null && $t < $lo) return false;
        if (($params['max'] ?? '') !== '' && ($hi = self::mins((string) $params['max'])) !== null && $t > $hi) return false;
        return true;
    }

    public static function clientRule(array $params): array
    {
        $r = ['timeValid' => true];
        if (($params['min'] ?? '') !== '') $r['timeMin'] = (string) $params['min'];
        if (($params['max'] ?? '') !== '') $r['timeMax'] = (string) $params['max'];
        return $r;
    }
}
