<?php

if ( !defined( 'ABSPATH' ) ) {

    exit;
}

if ( !class_exists( 'Pricely_Condition_Type_Customer' ) ) {

    class Pricely_Condition_Type_Customer {

        private $validation_util;
        private $customer_util;

        public function can_validate( $condition_type, $args ) {

            $condition_types = array(
                'logged_in_user',
                'users',
                'user_roles',
            );

            return in_array( $condition_type, $condition_types );
        }

        public function validate( $condition, $data, $items ) {

            if ( is_null( $this->validation_util ) ) {

                $this->validation_util = Pricely_Validation_Util::get_instance();
            }

            if ( is_null( $this->customer_util ) ) {

                $this->customer_util = Pricely_Customer_Util::get_instance();
            }

            $condition_type = $condition[ 'condition_type' ];

            if ( 'logged_in_user' == $condition_type ) {

                return $this->validate_logged_in_user( $condition, $data );
            }

            if ( 'users' == $condition_type ) {

                return $this->validate_users( $condition, $data );
            }

            if ( 'user_roles' == $condition_type ) {

                return $this->validate_user_roles( $condition, $data );
            }

            return false;
        }

        private function validate_logged_in_user( $condition, $data ) {

            $rule_is_logged_in = $condition[ 'is_logged_in' ];

            $is_logged_in = $this->customer_util->get_is_logged_in( $data );

            return $this->validation_util->validate_yes_no( $is_logged_in, $rule_is_logged_in );
        }

        private function validate_users( $condition, $data ) {

            if ( !isset( $condition[ 'user_emails' ] ) ) {

                return false;
            }

            $rule_user_emails = $condition[ 'user_emails' ];

            if ( !count( $rule_user_emails ) ) {

                return false;
            }

            $user_email = $this->customer_util->get_user_email( $data );

            $rule_compare = $condition[ 'compare' ];

            return $this->validation_util->validate_value_list( $user_email, $rule_user_emails, $rule_compare );
        }

        private function validate_user_roles( $condition, $data ) {

            if ( !isset( $condition[ 'user_roles' ] ) ) {

                return false;
            }

            $rule_user_roles = $condition[ 'user_roles' ];

            if ( !count( $rule_user_roles ) ) {

                return false;
            }


            $user_roles = $this->customer_util->get_user_roles( $data );

            $rule_compare = $condition[ 'compare' ];

            return $this->validation_util->validate_list_list( $user_roles, $rule_user_roles, $rule_compare );
        }

    }

}