<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Validator;

class ValidaRutServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Validator::extend('rut', function($attribute, $value, $parameters, $validator) {
            $rut = str_replace('.', '', $value);

            if(preg_match('/^[0-9]{7,9}-[0-9Kk]{1}$/', $rut) == 0)
            {
                return false;
            }
            $rut = preg_replace('/-/','',$rut);
            $sub_rut = substr($rut,0,strlen($rut)-1);
            $sub_dv = substr($rut,-1);
            $x = 2;
            $s = 0;
            for ( $i = strlen($sub_rut)-1;$i >= 0;$i-- )
            {
                if ( $x > 7 )
                {
                    $x = 2;
                }
                $s += $sub_rut[$i]*$x;
                $x++;
            }
            $dv=11 - ($s%11);
            if ( $dv == 10 )
            {
                $dv='K';
            }
            if ( $dv == 11 )
            {
                $dv = '0';
            }
            if ( $dv == strtoupper($sub_dv) )
            {
                return true;
            }
            else
            {
                return false;
            }
        });
    }
}
