<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use Illuminate\Contracts\Validation\DataAwareRule;

class RegionLimitedRules implements Rule, DataAwareRule
{
    protected $data = [];
    
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        //
        if (substr($value, 0, 2)=='TP'||substr($value, 0, 2)=='HS') {
            
            if (is_null($this->data['registeredSession'])) {
                return false;
            }
            
            if (is_null($this->data['lunchOptions'])) {
                return false;
            }

            $pattern = '/09\d{2}-\d{3}-\d{3}/';
            $string = $this->data['phoneNumber'];
            if (!preg_match($pattern, $string, $matches)) {
                return false;
            }
            
        } elseif (substr($value, 0, 2)=='JP') {

            $pattern = '/^0[789]0-\d{4}-\d{4}/';
            $string = $this->data['phoneNumber'];
            if (!preg_match( $pattern, $string, $matches)) {
                return false;
            }
        } elseif (substr($value, 0, 2)=='KR') {

            $pattern = '/^01\d{1}-\d{4}-\d{4}/';
            $string = $this->data['phoneNumber'];
            if (!preg_match( $pattern, $string, $matches)) {
                return false;
            }
        }
        return true;
    }

    /**
     * Set the data under validation.
     *
     * @param  array  $data
     * @return $this
     */
    public function setData($data)
    {
        $this->data = $data;
 
        return $this;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The validation error message.';
    }
}
