<?php
// _Core/Validator.php
// Centralized input validator for AtulyaSolar ERP-CRM

class Validator
{
    public static function str($value, $min = 1, $max = 255)
    {
        if (!isset($value)) return false;
        $value = trim($value);

        if ($value === "" || strlen($value) < $min || strlen($value) > $max) {
            return false;
        }
        return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
    }

    public static function optionalStr($value, $max = 255)
    {
        if (!isset($value) || trim($value) === "") return null;
        return htmlspecialchars(substr(trim($value), 0, $max), ENT_QUOTES, 'UTF-8');
    }

    public static function mobile($value)
    {
        if (!preg_match('/^[0-9]{10}$/', $value)) return false;
        return $value;
    }

    public static function email($value)
    {
        if (!filter_var($value, FILTER_VALIDATE_EMAIL)) return false;
        return strtolower($value);
    }

    public static function id($value)
    {
        $v = (int)$value;
        return $v > 0 ? $v : false;
    }

    public static function required($value)
    {
        return isset($value) && trim($value) !== "";
    }

    public static function date($value)
    {
        if (!$value) return false;
        return date('Y-m-d', strtotime($value));
    }

    public static function datetime($value)
    {
        if (!$value) return false;
        return date('Y-m-d H:i:s', strtotime($value));
    }

    public static function sanitizeArray($arr)
    {
        if (!is_array($arr)) return [];
        return array_map(function($v){
            return is_string($v)
                ? htmlspecialchars(trim($v), ENT_QUOTES, 'UTF-8')
                : $v;
        }, $arr);
    }
}
