<?php

if ( !defined( 'ABSPATH' ) ) {

    exit;
}

if ( !class_exists( 'Pricely_Condition_Type_Cart' ) ) {

    class Pricely_Condition_Type_Cart {

        private $items_in_cart_key = 'items_in_cart';
        private $validation_util;

        public function can_validate( $condition_type, $args ) {

            $condition_types = array(
                'cart_line_count'
            );

            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();
            }

            $condition_type = $condition[ 'condition_type' ];

            if ( 'cart_line_count' == $condition_type ) {

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

            return false;
        }

        private function validate_line_count( $condition, $data ) {

            $line_count = $this->get_line_count( $data );

            $rule_compare = $condition[ 'compare' ];

            if ( '--' == $rule_compare ) {

                $rule_from_line_count = 0;

                if ( is_numeric( $condition[ 'from_line_count' ] ) ) {

                    $rule_from_line_count = $condition[ 'from_line_count' ];
                }

                $rule_to_line_count = 0;

                if ( is_numeric( $condition[ 'to_line_count' ] ) ) {

                    $rule_to_line_count = $condition[ 'to_line_count' ];
                }

                $from_is_valid = $this->validation_util->validate_value( '>=', $line_count, $rule_from_line_count, 'no' );

                $to_is_valid = $this->validation_util->validate_value( '<=', $line_count, $rule_to_line_count, 'no' );

                return (true == $from_is_valid && true == $to_is_valid);
            }

            $rule_line_count = 0;

            if ( is_numeric( $condition[ 'line_count' ] ) ) {

                $rule_line_count = $condition[ 'line_count' ];
            }

            return $this->validation_util->validate_value( $rule_compare, $line_count, $rule_line_count, 'no' );
        }

        private function get_line_count( $data ) {

            if ( !isset( $data[ $this->items_in_cart_key ] ) ) {

                return 0;
            }

            return count( $data[ $this->items_in_cart_key ] );
        }

    }

}
