<?php
namespace App\Validation;

use Config\Services;

class CustomRules{


    public function json_valid_fields($arg = null, string $fields = null)
    {
        $data = json_decode($arg, $assoc = true, $depth = 15);
        if (json_last_error() !== JSON_ERROR_NONE)
        {
            log_message('error', 'json_valid_fields: invalid json string');
            return false;
        }

        $validator = Services::validation();

        // separate field names with rules
        foreach (explode(',', $fields) as $field)
        {
            $config = explode(':', $field);
            $key = $config[0];

            // separate rules for a field
            $rules = explode('|', $config[1]);
            if (isset($data[$key]))
            {
                // run the checks, break at first failure
                foreach ($rules as $rule)
                {
                    $result = $validator->check($data[$key], $rule);

                    if (! $result)
                        return false;
                }
            }
            elseif (in_array('required', $rules))
            {
                log_message('notice', 'json_valid_fields: key ' .$key. ' is required');
                return false;
            }
        }   

        return true;
    } 

  // Rule is to validate mobile number digits
  public function mobileValidation(string $str, string $fields, array $data){
    
    /*Checking: Number must start from 5-9{Rest Numbers}*/
    if(preg_match( '/^[5-9]{1}[0-9]+/', $data['mobile'])){
      
      /*Checking: Mobile number must be of 10 digits*/
      $bool = preg_match('/^[0-9]{10}+$/', $data['mobile']);
      return $bool == 0 ? false : true; 
      
    }else{
      
      return false;
    }
  }
}