<?php
namespace PpPhp\Plugins;

use PpPhp\Core\ValidationPlugin;

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

    public static function paramsSchema(): array
    {
        return [
            ['key' => 'min', 'type' => 'text', 'label' => 'Earliest (YYYY-MM-DD)', 'default' => '', 'placeholder' => '2000-01-01'],
            ['key' => 'max', 'type' => 'text', 'label' => 'Latest (YYYY-MM-DD)', 'default' => '', 'placeholder' => '2030-12-31'],
            ['key' => 'notFuture', 'type' => 'bool', 'label' => 'Not in the future', 'default' => false],
            ['key' => 'notPast', 'type' => 'bool', 'label' => 'Not in the past', 'default' => false],
            ['key' => 'minAge', 'type' => 'number', 'label' => 'Minimum age (years)', 'default' => ''],
        ];
    }

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

    private static function flag(mixed $v): bool { return in_array(strtolower((string) $v), ['1', 'yes', 'true', 'on'], true); }

    public static function serverCheck(mixed $value, array $params, array $record = []): bool
    {
        $ts = strtotime((string) $value);
        if ($ts === false) return false;
        $day = strtotime(date('Y-m-d', $ts)); // normalise to midnight
        $today = strtotime(date('Y-m-d'));

        if (($params['min'] ?? '') !== '' && ($m = strtotime((string) $params['min'])) !== false && $day < strtotime(date('Y-m-d', $m))) return false;
        if (($params['max'] ?? '') !== '' && ($m = strtotime((string) $params['max'])) !== false && $day > strtotime(date('Y-m-d', $m))) return false;
        if (self::flag($params['notFuture'] ?? false) && $day > $today) return false;
        if (self::flag($params['notPast'] ?? false) && $day < $today) return false;
        if (($params['minAge'] ?? '') !== '' && is_numeric($params['minAge'])) {
            $cut = strtotime('-' . (int) $params['minAge'] . ' years', $today);
            if ($day > $cut) return false;
        }
        return true;
    }

    public static function clientRule(array $params): array
    {
        $r = ['dateValid' => true];
        if (($params['min'] ?? '') !== '') $r['dateMin'] = (string) $params['min'];
        if (($params['max'] ?? '') !== '') $r['dateMax'] = (string) $params['max'];
        if (self::flag($params['notFuture'] ?? false)) $r['notFuture'] = true;
        if (self::flag($params['notPast'] ?? false)) $r['notPast'] = true;
        if (($params['minAge'] ?? '') !== '' && is_numeric($params['minAge'])) $r['minAge'] = (int) $params['minAge'];
        return $r;
    }
}
