<?php

//The heart of the magic
final class SOFT79_Rule_Controller_PRO extends SOFT79_Rule_Controller {
        
    public function __construct( $options = null ) {
        
        parent::__construct();        
        $this->create_post_type();
        
    }    
    
    function create_post_type() {
        register_post_type( 'j79_wc_price_rule',
            array(
                'labels' => array(
                    'name'               => _x( 'Pricing rules', 'post type general name', 'soft79-wc-pricing-rules' ),
                    'singular_name'      => _x( 'Pricing rule', 'post type singular name', 'soft79-wc-pricing-rules' ),
                    'menu_name'          => _x( 'Pricing rules', 'admin menu', 'soft79-wc-pricing-rules' ),
                    'name_admin_bar'     => _x( 'Pricing rule', 'add new on admin bar', 'soft79-wc-pricing-rules' ),
                    'add_new'            => _x( 'Add New', 'pricing rule', 'soft79-wc-pricing-rules' ),
                    'add_new_item'       => __( 'Add New Pricing rule', 'soft79-wc-pricing-rules' ),
                    'new_item'           => __( 'New Pricing rule', 'soft79-wc-pricing-rules' ),
                    'edit_item'          => __( 'Edit Pricing rule', 'soft79-wc-pricing-rules' ),
                    'view_item'          => __( 'View Pricing rule', 'soft79-wc-pricing-rules' ),
                    'all_items'          => __( 'All Pricing rules', 'soft79-wc-pricing-rules' ),
                    'search_items'       => __( 'Search Pricing rules', 'soft79-wc-pricing-rules' ),
                    'not_found'          => __( 'No Pricing rules found.', 'soft79-wc-pricing-rules' ),
                    'not_found_in_trash' => __( 'No Pricing rules found in Trash.', 'soft79-wc-pricing-rules' )
                ),
                'public' => false,
                'show_ui' => true,
                'show_in_menu' => 'woocommerce',
                'supports' => array('title', 'editor'),
                'has_archive' => false,
            )
        );

    } 
    
    protected $_rules = null;
    /**
     *  Returns all rules that are allowed for the user
     *  if is_admin() we return all the rules
     */
    protected function get_rules() {    
        //Remember the values, don't query again if already known
        if ($this->_rules === null) {
            $this->_rules = array();
            
            $args = array(
                'posts_per_page'   => -1,
                'orderby'          => 'date',
                'order'            => 'DESC',
                'post_type'        => 'j79_wc_price_rule',
                'post_status'      => 'publish',
            );
            $posts_array = get_posts( $args ); 
            foreach ($posts_array as $post ) {
                $rule_type = get_post_meta( $post->ID, '_j79_rule_type', true );

                if ( $rule_type == SOFT79_Bulk_Rule::rule_type() ) {
                    $rule = new SOFT79_Bulk_Rule( $post );
                    if ( $rule->is_valid_for_user() || is_admin() ) {
                        $this->_rules[] = $rule;
                    }
                } else {
                    error_log ( sprintf( "SOFT79_Rule_Controller_PRO::get_rules() Unknown rule type: %s", $rule_type ) );
                }
                
            }
        }
        return $this->_rules;
    }
    
    public function get_valid_rules_for( $product ) {    
        $valid_rules = array();
        foreach ( $this->get_rules() as $rule ) {
            if ( $rule->is_valid_for_product( $product ) ) {
                $valid_rules[] = $rule;
            }
        }
        
        //Also add the local product rule
        $valid_rules[] = new SOFT79_Bulk_Rule( $product->post );
        if ( is_a( $product, 'WC_Product_Variation') ) {
            $valid_rules[] = new SOFT79_Bulk_Rule( $product->variation_id );
        }
        return $valid_rules;
    }

    //We cheat by setting the product price to bulk price 
    public function execute() {
        
        //error_log('action_woocommerce_before_calculate_totals');
        $cart = WC()->cart;
        //Acquaint the cart
        foreach ( $this->get_rules( ) as $rule ) {
            $rule->discover_cart( $cart->get_cart() );
        }
        
        foreach ( $cart->get_cart() as $cart_item_key => $values ) {
            $product = $values['data'];
            $qty = $values['quantity'];
            
            
            //Find best-value rule for this cart item
            $bestrule_total_discount = null; 
            $bestrule_data = null ; 
            foreach ( $this->get_valid_rules_for( $product ) as $rule ) {
                $total_discount = $rule->get_discount_for_product($product, $qty, $data);
                if ( $total_discount !== false && ( $total_discount < $bestrule_total_discount || $bestrule_total_discount === null ) ) {
                    $bestrule_total_discount = $total_discount;
                    $bestrule_data = $data;
                    if ( $this->options['rule_choice'] == 'first' ) { //first or best
                        break; //We apply the first rule, so immediately escape from this loop!
                    }
                }
            }
            
            //Apply the best one, if found
            if ( $bestrule_data !== null ) {
                //error_log("So the best price is $bestrule_avg_price " );
                $this->set_temp_data( $product, 'stack_min_price', $bestrule_data['min'] );
                $this->set_temp_data( $product, 'stack_max_price', $bestrule_data['max'] );
                $this->set_product_bulk_price( $product, $bestrule_data['avg'] );
                //error_log ( sprintf("Discounted price of %s on product %s", $bestrule_avg_price, $product->id) );
            }
            
        }
    }  
    

}
