<?php
/**
 * @author      Flycart (Alagesan)
 * @license     http://www.gnu.org/licenses/gpl-3.0.html
 * @link        https://www.flycart.org
 * */

namespace Wlpr\App\Helpers;

use Valitron\Validator;

if (!defined('ABSPATH')) exit;
class Validation {
    /**
     * Validate discount rules licence key input
     * @param $post_values
     * @return bool
     */
    static function validateLicenceKay($post_values)
    {
        $rules = [
            'alphaNum' => 'licence_key',
        ];
        $validate = new Validator(array('licence_key' => $post_values));
        $validate->rules($rules);
        return $validate->validate();
    }

    /**
     * validate input against the alpha numeric and spaces
     * @param $field
     * @param $value
     * @param array $params
     * @param array $fields
     * @return bool
     */
    static function validateColor($field, $value, array $params, array $fields)
    {
        return (bool)preg_match('/^#(([0-9a-fA-F]{2}){3}|([0-9a-fA-F]){3})$/', $value);
    }

    /**
     * validate Input Text Html Tags
     *
     * @param $field
     * @param $value
     * @param array $params
     * @param array $fields
     * @return bool
     */
    static function validateBasicHtmlTags($field, $value, array $params, array $fields)
    {
        $value = stripslashes($value);
        $value = html_entity_decode($value);
        $invalid_tags = array("script", "iframe", "style");
        foreach ($invalid_tags as $tag_name) {
            $pattern = "#<\s*?$tag_name\b[^>]*>(.*?)</$tag_name\b[^>]*>#s";;
            preg_match($pattern, $value, $matches);
            //script or iframe found
            if (!empty($matches)) {
                return false;
            }
        }
        return true;
    }

    /**
     * validate Plain Input Text
     *
     * @param $field
     * @param $value
     * @param array $params
     * @param array $fields
     * @return bool
     */
    static function validatePlainInputText($field, $value, array $params, array $fields)
    {
        if (!empty($value)) {
            $value = html_entity_decode($value);
            $html = Woocommerce::removeHtmlTags($value);
            return ($html === trim($value));
        } else {
            return true;
        }
    }

    static function validateAlphaNumWithSpace($field, $value, array $params, array $fields){
        return preg_match('/^([a-z0-9 ])+$/i', $value);
    }

    /**
     * validate Radio Button And Select Box
     *
     * @param $field
     * @param $value
     * @param array $params
     * @param array $fields
     * @return bool
     */
    static function validateRadioButtonAndSelectBox($field, $value, array $params, array $fields)
    {
        $acceptable = array('yes', 'no', 1, '1', true, 0, '0');
        return in_array($value, $acceptable, true);
    }

    /**
     * Check alphaNum values for selected array values (multi select box)
     *
     * @param $field
     * @param $value
     * @param array $params
     * @param array $fields
     * @return bool
     */
    static function validateSelectedArrayValues($field, $value, array $params, array $fields)
    {
        $result = false;
        if (is_array($value) && !empty($value)) {
            $result = true;
            foreach ($value as $val) {
                //Validate that a field contains only alpha-numeric characters, dashes, and underscores
                if (!preg_match('/^([-a-z0-9_-])+$/i', $val)) {
                    $result = false;
                }
            }
        }
        return $result;
    }

    /**
     * validate the conditional values
     * @param $field
     * @param $value
     * @param array $params
     * @param array $fields
     * @return bool
     */
    static function validateConditionFields($field, $value, array $params, array $fields)
    {
        if (is_array($value)) {
            foreach ($value as $input_key => $input_val) {
                if (!self::validateConditionFields($input_key, $input_val, $params, $fields)) {
                    return false;
                }
            }
        } else {
            if(in_array($field,array('rule_type','referral_type','earn_point_type'))){
                return preg_match('/^([a-z])+$/i', $value);
            }elseif(in_array($field,array('rule_min','rule_max','earn_point','wlpr_earn_point','wlpr_point_earn_price'))){
                return is_numeric($value);
            }
            return self::validatePlainInputText($field, $value, $params, $fields);
        }
        return true;
    }

    /**
     * validate the conditional values
     * @param $field
     * @param $value
     * @param array $params
     * @param array $fields
     * @return bool
     */
    static function validateCleanHtml($field, $value, array $params, array $fields)
    {
        $html = Woocommerce::getCleanHtml($value);
        if($html != $value){
            return false;
        }
        return true;
    }

    static function validateNewCustomer($post){
        $settings_validator = new Validator($post);
        $settings_validator->stopOnFirstFail(false);
        $settings_validator->rule('slug',
            array(
                'refer_code'
            )
        );
        $settings_validator->rule('numeric',
            array(
                'points'
            )
        );
        $settings_validator->rule('email',
            array(
                'user_email'
            )
        );
        if ($settings_validator->validate()) {
            return true;
        } else {
            return $settings_validator->errors();
        }
    }

    static function validateReferralTab($post){
        $settings_validator = new Validator($post);
        $settings_validator->stopOnFirstFail(false);
        Validator::addRule('basicHtmlTags', array(__CLASS__, 'validateBasicHtmlTags'), __('Invalid characters', WLPR_TEXT_DOMAIN));
        Validator::addRule('cleanHtml', array(__CLASS__, 'validateCleanHtml'), __('Invalid characters', WLPR_TEXT_DOMAIN));
        Validator::addRule('plainInputText', array(__CLASS__, 'validatePlainInputText'), __('Should not contain any tags', WLPR_TEXT_DOMAIN));
        Validator::addRule('alphaNumWithSpace', array(__CLASS__, 'validateAlphaNumWithSpace'), __('must contain only letters a-z and/or numbers 0-9', WLPR_TEXT_DOMAIN));
        Validator::addRule('radioButtonAndSelectBox', array(__CLASS__, 'validateRadioButtonAndSelectBox'), __('must contain following any one yes,no,1,0', WLPR_TEXT_DOMAIN));
        Validator::addRule('selectedArrayValues', array(__CLASS__, 'validateSelectedArrayValues'), __('Should not contain any tags and special characters', WLPR_TEXT_DOMAIN));
        Validator::addRule('conditionValues', array(__CLASS__, 'validateConditionFields'), __('Invalid characters', WLPR_TEXT_DOMAIN));

        $settings_validator->rule('conditionValues',
            array(
                'wlpr_rules',
            )
        );

        $settings_validator->rule('slug',
            array(
                'wlpr_referral_prefix'
            )
        );

        $settings_validator->rule('basicHtmlTags',
            array(
                'wlpr_cart_referee_reward_message',
                'wlpr_before_referral_message',
                'wlpr_referrer_message',
                'wlpr_referee_message',
                'wlpr_referee_discount_message',
                'wlpr_share_subject',
                'wlpr_share_content'
            )
        );

        $settings_validator->rule('cleanHtml',
            array(
                'wlpr_cart_referee_reward_message',
                'wlpr_before_referral_message',
                'wlpr_referrer_message',
                'wlpr_referee_message',
                'wlpr_referee_discount_message',
                'wlpr_share_subject',
                'wlpr_share_content'
            )
        );

        $settings_validator->rule('alphaNumWithSpace',
            array(
                'wlpr_cart_referal_coupon_name',
            )
        );

        $settings_validator->rule('radioButtonAndSelectBox',
            array(
                'wlpr_enable_referral',
                'wlpr_referral_discount',
                'wlpr_enable_facebook_share_point',
                'wlpr_enable_twitter_share_point',
                'wlpr_enable_email_share_point',
                'wlpr_enable_whatsapp_share_point'
            )
        );
        $settings_validator->rule('numeric',
            array(
                'wlpr_referring_person',
                'wlpr_referred_person',
                'wlpr_referral_coupon_percent',
                'wlpr_facebook_share_point',
                'wlpr_twitter_share_point',
                'wlpr_email_share_point',
                'wlpr_whatsapp_share_point'
            )
        );
        $settings_validator->rule('alpha',
            array(
                'wlpr_cart_referral_message_display',
                'wlpr_referral_coupon_percent_type'
            )
        );
        $settings_validator->rule('alphaNum',
            array(
                'wlpr_fb_app_id'
            )
        );

        if ($settings_validator->validate()) {
            return true;
        } else {
            return $settings_validator->errors();
        }
    }

    static function validateSimpleProduct($post){
        $settings_validator = new Validator($post);
        $settings_validator->stopOnFirstFail(false);
        Validator::addRule('conditionValues', array(__CLASS__, 'validateConditionFields'), __('Invalid characters', WLPR_TEXT_DOMAIN));
        Validator::addRule('radioButtonAndSelectBox', array(__CLASS__, 'validateRadioButtonAndSelectBox'), __('must contain following any one yes,no,1,0', WLPR_TEXT_DOMAIN));
        $settings_validator->rule('conditionValues',
            array(
                '_wlpr_product_points_earned',
                '_wlpr_renewal_product_points_earned'
            )
        );
        $settings_validator->rule('alpha',
            array(
                '_wlpr_product_enable_earn_point',
                '_wlpr_product_points_max_discount_type'
            )
        );
        $settings_validator->rule('radioButtonAndSelectBox',
            array(
                '_wlpr_product_max_discount_enabled'
            )
        );
        $settings_validator->rule('numeric',
            array(
                '_wlpr_product_points_max_discount'
            )
        );
        if ($settings_validator->validate()) {
            return true;
        } else {
            return $settings_validator->errors();
        }
    }

    static function validateCategorySetting($post){
        $settings_validator = new Validator($post);
        $settings_validator->stopOnFirstFail(false);
        Validator::addRule('conditionValues', array(__CLASS__, 'validateConditionFields'), __('Invalid characters', WLPR_TEXT_DOMAIN));
        Validator::addRule('radioButtonAndSelectBox', array(__CLASS__, 'validateRadioButtonAndSelectBox'), __('must contain following any one yes,no,1,0', WLPR_TEXT_DOMAIN));
        $settings_validator->rule('conditionValues',
            array(
                '_wlpr_category_points_earned',
                '_wlpr_category_points_renewal_points'
            )
        );
        $settings_validator->rule('alpha',
            array(
                '_wlpr_category_enable_earn_point',
                '_wlpr_category_points_max_discount_type'
            )
        );
        $settings_validator->rule('radioButtonAndSelectBox',
            array(
                '_wlpr_category_max_discount_enabled'
            )
        );
        $settings_validator->rule('numeric',
            array(
                '_wlpr_category_points_max_discount'
            )
        );
        if ($settings_validator->validate()) {
            return true;
        } else {
            return $settings_validator->errors();
        }
    }

    static function validateVariableSetting($post){
        $settings_validator = new Validator($post);
        $settings_validator->stopOnFirstFail(false);
        Validator::addRule('conditionValues', array(__CLASS__, 'validateConditionFields'), __('Invalid characters', WLPR_TEXT_DOMAIN));
        Validator::addRule('radioButtonAndSelectBox', array(__CLASS__, 'validateRadioButtonAndSelectBox'), __('must contain following any one yes,no,1,0', WLPR_TEXT_DOMAIN));
        $settings_validator->rule('conditionValues',
            array(
                '_wlpr_category_points_earned',
                '_wlpr_category_points_renewal_points'
            )
        );
        $settings_validator->rule('alpha',
            array(
                '_wlpr_variable_product_enable_earn_point',
                '_wlpr_category_points_max_discount_type'
            )
        );
        $settings_validator->rule('radioButtonAndSelectBox',
            array(
                '_wlpr_category_max_discount_enabled'
            )
        );
        $settings_validator->rule('numeric',
            array(
                '_wlpr_category_points_max_discount'
            )
        );
        if ($settings_validator->validate()) {
            return true;
        } else {
            return $settings_validator->errors();
        }
    }

    static function validateSettingsTab($post)
    {
        /*
         * 1. wlpr_enable_launcher
         * 2. wlpr_launcher_icon
         * 3. wlpr_launcher_text
         * 4. wlpr_launcher_button_width
         * */
        $settings_validator = new Validator($post);
        $settings_validator->stopOnFirstFail(false);
        Validator::addRule('basicHtmlTags', array(__CLASS__, 'validateBasicHtmlTags'), __('Invalid characters', WLPR_TEXT_DOMAIN));
        Validator::addRule('cleanHtml', array(__CLASS__, 'validateCleanHtml'), __('Invalid characters', WLPR_TEXT_DOMAIN));
        Validator::addRule('plainInputText', array(__CLASS__, 'validatePlainInputText'), __('Should not contain any tags', WLPR_TEXT_DOMAIN));
        Validator::addRule('alphaNumWithSpace', array(__CLASS__, 'validateAlphaNumWithSpace'), __('must contain only letters a-z and/or numbers 0-9', WLPR_TEXT_DOMAIN));
        Validator::addRule('radioButtonAndSelectBox', array(__CLASS__, 'validateRadioButtonAndSelectBox'), __('must contain following any one yes,no,1,0', WLPR_TEXT_DOMAIN));
        Validator::addRule('selectedArrayValues', array(__CLASS__, 'validateSelectedArrayValues'), __('Should not contain any tags and special characters', WLPR_TEXT_DOMAIN));
        Validator::addRule('color', array(__CLASS__, 'validateColor'), __('Invalid color value', WLPR_TEXT_DOMAIN));


        $settings_validator->rule('alphaNum',
            array(
                'licence_key',
            )
        );

        $settings_validator->rule('color',
            array(
                'wlpr_launcher_icon_background_color',
                'wlpr_launcher_icon_text_color'
            )
        );

        $settings_validator->rule('slug',
            array(
                'display_product_display_position',
                'wlpr_referral_prefix'
            )
        );

        $settings_validator->rule('basicHtmlTags',
            array(
                'wlpr_account_signup_message',
                'wlpr_write_review_message',
                'wlpr_single_product_message',
                'wlpr_variable_product_message',
                'wlpr_cart_earn_points_message',
                'wlpr_cart_redeem_points_message',
                'wlpr_thank_you_message',
                'wlpr_earn_point_order_summary_text'
            )
        );
        $settings_validator->rule('cleanHtml',
            array(
                'wlpr_account_signup_message',
                'wlpr_write_review_message',
                'wlpr_single_product_message',
                'wlpr_variable_product_message',
                'wlpr_cart_earn_points_message',
                'wlpr_cart_redeem_points_message',
                'wlpr_thank_you_message',
                'wlpr_earn_point_order_summary_text'
            )
        );

        $settings_validator->rule('alphaNumWithSpace',
            array(
                'wlpr_launcher_text',
                'wlpr_point_label',
                'wlpr_cart_point_name',
                'wlpr_cart_referal_coupon_name'
            )
        );
        $settings_validator->rule('radioButtonAndSelectBox',
            array(
                'wlpr_enable_launcher',
                'wlpr_enable_earn_point',
                'wlpr_my_account_label_icon_position',
                'wlpr_enable_signup_reward',
                'wlpr_enable_review_reward',
                'wlpr_partial_redemption_enabled',
                'wlpr_max_discount_enabled',
                'wlpr_enable_referral',
                'wlpr_referral_discount',
                'wlpr_enable_birth_date_point'
            )
        );
        $settings_validator->rule('numeric',
            array(
                'wlpr_launcher_button_width',
                'wlpr_earn_point',
                'wlpr_point_earn_price',
                'wlpr_expired_after',
                'wlpr_expired_email_after',
                'wlpr_account_signup_points',
                'wlpr_write_review_points',
                'wlpr_redeem_point',
                'wlpr_point_redeem_price',
                'wlpr_min_cart_discount',
                'wlpr_max_cart_discount',
                'wlpr_max_product_discount',
                'wlpr_referring_person',
                'wlpr_referred_person',
                'wlpr_referral_coupon_percent',
                'wlpr_birth_date_point'
            )
        );
        $settings_validator->rule('alpha',
            array(
                'wlpr_launcher_icon_position',
                'wlpr_launcher_display_device',
                'wlpr_point_rounding_type',
                'wlpr_expired_period',
                'wlpr_expired_email_period',
                'wlpr_points_tax_application',
                'wlpr_redeem_when_other_coupon_apply',
                'wlpr_max_cart_discount_type',
                'wlpr_max_product_discount_type',
                'display_product_message_page',
                'wlpr_cart_earn_point_display',
                'wlpr_thank_you_position',
                'wlpr_cart_redeem_point_display',
                'wlpr_cart_referral_message_display',
                'wlpr_referral_coupon_percent_type'
            )
        );
        $settings_validator->rule('selectedArrayValues',
            array(
                'wlpr_point_earning_status',
                'wlpr_exclude_point_earning_roles',
                'wlpr_point_redeem_status'
            )
        );
        if ($settings_validator->validate()) {
            return true;
        } else {
            return $settings_validator->errors();
        }
    }

    /**
     *validate Report Fields
     *
     * @param $field
     * @param $value
     * @param array $params
     * @param array $fields
     * @return bool
     */
    static function validateReportFields($field, $value, array $params, array $fields)
    {
        return (bool)preg_match('/^[a-zA-Z0-9 :_-]+$/', $value);
    }
    static function validateAlphaNumWithUnderscore($field, $value, array $params, array $fields)
    {
        return (bool)preg_match('/^[a-zA-Z0-9_-]+$/', $value);
    }
    static function validateDashboard($post){
        $settings_validator = new Validator($post);
        $settings_validator->stopOnFirstFail(false);
        //Validator::addRule('reportFields', array(__CLASS__, 'validateReportFields'), __('Validation error', WLPR_TEXT_DOMAIN));
        Validator::addRule('alphaNumWithUnderscore', array(__CLASS__, 'validateAlphaNumWithUnderscore'), __('Validation error', WLPR_TEXT_DOMAIN));
        $settings_validator->rule('alphaNumWithUnderscore',
            array(
                'filter_date'
            )
        );
        $filter_date = (isset($post['filter_date']) && $post['filter_date']) ? $post['filter_date'] : '90_days';
        if($filter_date == 'custom'){
            $settings_validator->rule('date',
                array(
                    'from_date',
                    'to_date'
                )
            );
        }
        if ($settings_validator->validate()) {
            return true;
        } else {
            return $settings_validator->errors();
        }
    }
    static function validateSearchField($post){
        $settings_validator = new Validator($post);
        $settings_validator->stopOnFirstFail(false);
        Validator::addRule('search', array(__CLASS__, 'validateSearch'), __('Validation error', WLPR_TEXT_DOMAIN));

        $settings_validator->rule('search',
            array(
                'search'
            )
        );
        if ($settings_validator->validate()) {
            return true;
        } else {
            return $settings_validator->errors();
        }
    }
    static function validateSearch($field, $value, array $params, array $fields){
        return preg_match('/^([@_.a-z0-9- ])+$/i', $value);
    }

    static function validateCommonFields($post){
        $settings_validator = new Validator($post);
        $settings_validator->stopOnFirstFail(false);
        Validator::addRule('search', array(__CLASS__, 'validateSearch'), __('Validation error', WLPR_TEXT_DOMAIN));
        Validator::addRule('alphaNumWithUnderscore', array(__CLASS__, 'validateAlphaNumWithUnderscore'), __('Validation error', WLPR_TEXT_DOMAIN));
        $settings_validator->rule('search',
            array(
                'search'
            )
        );
        $settings_validator->rule('alphaNumWithUnderscore',
            array(
                'filter_order'
            )
        );
        $settings_validator->rule('numeric',
            array(
                'per_page',
                'page_number',
            )
        );
        $settings_validator->rule('alpha',
            array(
                'filter_order_dir'
            )
        );

        if ($settings_validator->validate()) {
            return true;
        } else {
            return $settings_validator->errors();
        }
    }

    static function validateCustomerHistory($post){
        $settings_validator = new Validator($post);
        $settings_validator->stopOnFirstFail(false);
        Validator::addRule('search', array(__CLASS__, 'validateSearch'), __('Validation error', WLPR_TEXT_DOMAIN));
        Validator::addRule('alphaNumWithUnderscore', array(__CLASS__, 'validateAlphaNumWithUnderscore'), __('Validation error', WLPR_TEXT_DOMAIN));
        $settings_validator->rule('search',
            array(
                't_search',
                'e_search'
            )
        );
        $settings_validator->rule('alphaNumWithUnderscore',
            array(
                't_filter_order',
                'e_filter_order'
            )
        );
        $settings_validator->rule('numeric',
            array(
                'per_page',
                'transaction_page_number',
                'action_page_number',
                'activity_page_number'
            )
        );
        $settings_validator->rule('alpha',
            array(
                'e_filter_order_dir',
                't_filter_order_dir'
            )
        );

        if ($settings_validator->validate()) {
            return true;
        } else {
            return $settings_validator->errors();
        }
    }

    static function validateInputAlpha($input){
        return preg_replace('/[^A-Za-z0-9_\-]/', '', $input);
    }

    static function validateBirthday($post){
        $settings_validator = new Validator($post);
        $settings_validator->stopOnFirstFail(false);
        $settings_validator->rule('date',
            array(
                'birth_date'
            )
        );
        $settings_validator->rule('required',array('birth_date'));
        if ($settings_validator->validate()) {
            return true;
        } else {
            return $settings_validator->errors();
        }
    }
}