<?php
 
namespace App\Rules;
 
use Illuminate\Contracts\Validation\Rule;

class PartialTimestamp implements Rule
{

    public function passes($attribute, $value)
    {
        if (!is_string($value)) {
            return false;
        }

        $patterns = [
            // Full or partial date/datetime starting with year
            '/^\d{2,4}(-\d{0,2}(-\d{0,2}(\s+\d{0,2}(:\d{0,2}(:\d{0,2})?)?)?)?)?$/',
            // Date without year
            '/^-\d{1,2}(-\d{0,2}(\s+\d{0,2}(:\d{0,2}(:\d{0,2})?)?)?)?$/',
            // Time only
            '/^\d{1,2}(:\d{0,2}(:\d{0,2})?)?$/'
        ];

        $matchesPattern = false;
        foreach ($patterns as $pattern) {
            if (preg_match($pattern, $value)) {
                $matchesPattern = true;
                break;
            }
        }

        return is_numeric($value) || (
            $matchesPattern && 
            strlen($value) < 40 &&
            !preg_match('/-([2-9]\d|1[3-9])-/', $value) && // No month > 12
            !preg_match('/(^|[\s:])([3-9]\d|2[4-9]):/', $value) && // No hour > 23
            !preg_match('/\d{5,}:/', $value) // No excessive digits before colon
        );
    }
 
    public function message()
    {
        return 'The :attribute must be a valid partial snippet of a Y-M-D H:I:S timestamp.';
    }
}