<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class DSPILOT_Coupon_Discount {

    private $plugin_options = array();
    public $discounts = array();

    public function __construct() {
       $this->plugin_options = Dspilot_Plugin::get_plugin_options();
       $this->discounts = Dspilot_Plugin::get_discounts('coupon_discounts');
       
        add_action( 'woocommerce_cart_loaded_from_session', [ $this, 'apply_discounts' ] );
        add_filter( 'woocommerce_get_shop_coupon_data', [ $this, 'register_virtual_coupons' ], 10, 2 );
        add_filter( 'woocommerce_cart_totals_coupon_label', [ $this, 'custom_coupon_label' ], 10, 2 );
        add_filter( 'woocommerce_coupon_get_discount_amount', [ $this, 'force_discount_amount' ], 10, 5 );
    }

    /**
     * Apply all defined discounts to cart automatically
     */
    public function apply_discounts() {
        if ( is_admin() ) return;

        // first apply url coupons
        $this->apply_discounts_by_url();

        foreach ( $this->discounts as $discount ) {
            if ( !empty($discount['auto_apply']) && ! WC()->cart->has_discount( $discount['id'] ) ) {
                WC()->cart->add_discount( $discount['id'] );
            }
        }
    }
    /**
     * Apply discount by URL
     */
    public function apply_discounts_by_url() {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- URL coupons are public shareable links, nonce verification would break this feature
        if ( ! isset( $_GET['coupon'] ) ) {
            return;
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- URL coupons are public shareable links, nonce verification would break this feature
        $discount_id = sanitize_text_field( wp_unslash( $_GET['coupon'] ) );
        $discount = Dspilot_Helper::get_discount_by_id($discount_id);

        if ( !empty($discount['url_coupon']) && ! WC()->cart->has_discount( $discount_id ) ) {
            WC()->cart->add_discount( $discount_id );
        }
    }

    /**
     * Replace label with custom one
     */
    public function custom_coupon_label( $label, $coupon ) {
        foreach ( $this->discounts as $discount ) {
            if ( $discount['id'] === $coupon->get_code() ) {
                return $discount['label'];
            }
        }
        return $label;
    }

    /**
     * Register coupons WooCommerce doesn't find in the DB
     */
    public function register_virtual_coupons( $data, $code ) {
        foreach ( $this->discounts as $discount ) {
            if ( $discount['id'] === $code ) {

                // ✅ Check date range
                $now   = current_time( 'timestamp' );
                $start = ! empty( $discount['start_date'] ) ? strtotime( $discount['start_date'] ) : false;
                $end   = ! empty( $discount['end_date'] ) ? strtotime( $discount['end_date'] . ' 23:59:59' ) : false;

                if ( ( $start && $now < $start ) || ( $end && $now > $end ) ) {
                    continue; // ❌ Skip expired or future coupons
                }

                // ✅ Conditions fallback
                $condition_groups = ! empty( $discount['condition_groups'] ) ? $discount['condition_groups'] : [];

                if ( $this->evaluate_discount_condition_groups( $condition_groups ) ) {
                    // ✅ Set discount type
                    $mapped_type = $discount['type'] === 'percentage' ? 'percent' : 'fixed_cart';

                    // ✅ Return the full virtual coupon structure
                    return [
                        'id'                       => $discount['id'],
                        'code'                     => $discount['id'],
                        'discount_type'            => $mapped_type,
                        'coupon_amount'            => floatval( $discount['amount'] ),
                        'individual_use'           => ! empty( $discount['individual_use'] ),
                        'product_ids'              => ! empty( $discount['product_ids'] ) ? array_map( 'intval', $discount['product_ids'] ) : [],
                        'exclude_product_ids'      => ! empty( $discount['exclude_product_ids'] ) ? array_map( 'intval', $discount['exclude_product_ids'] ) : [],
                        'usage_limit'              => ! empty( $discount['usage_limit'] ) ? intval( $discount['usage_limit'] ) : '',
                        'usage_limit_per_user'     => ! empty( $discount['usage_limit_per_user'] ) ? intval( $discount['usage_limit_per_user'] ) : '',
                        'limit_usage_to_x_items'   => ! empty( $discount['limit_usage_to_x_items'] ) ? intval( $discount['limit_usage_to_x_items'] ) : '',
                        'usage_count'              => 0,
                        'expiry_date'              => $discount['end_date'], // Woo will convert this internally
                        'apply_before_tax'         => isset( $discount['apply_before_tax'] ) ? (bool) $discount['apply_before_tax'] : true,
                        'free_shipping'            => ! empty( $discount['free_shipping'] ),
                        'meta_data'                => [
                            'condition_groups' => $condition_groups,
                        ],
                    ];
                }

                
            }
        }

        return $data;
    }

    public function force_discount_amount( $discount, $discounting_amount, $cart_item, $single, $coupon ) {
       foreach ( $this->discounts as $custom ) {
            if ( $coupon->get_code() === $custom['id'] ) {

                // ✅ Handle discount type
                if ( $custom['type'] === 'percentage' ) {
                    return $discounting_amount * ( floatval( $custom['amount'] ) / 100 );
                }

                return floatval( $custom['amount'] );
            }
        }
    }

    /**
     * Evaluate discount conditions
     * Returns true if all conditions are met, false otherwise
     */
    public function evaluate_discount_condition_groups ( $condition_groups ) {
        if ( empty( $condition_groups ) || ! is_array( $condition_groups ) ) {
            return true;
        }

        foreach ( $condition_groups as $group ) {
            if ( ! empty( $group['conditions'] ) && is_array( $group['conditions'] ) ) {
                if ( ! $this->evaluate_discount_conditions( $group['conditions'] ) ) {
                    return false; // If any group fails, the whole evaluation fails
                }
            }
        }

        return true; // All groups passed
    }
     
    /**
     * Evaluate individual discount conditions
     * Returns true if all conditions are met, false otherwise
     */
    public function evaluate_discount_conditions( $conditions ) {
        if ( empty( $conditions ) || ! is_array( $conditions ) ) {
            return true;
        }

        $cart = WC()->cart; 
        $customer = wp_get_current_user();
        $cart_items = $cart->get_cart();
        $cart_total_weight = $cart->get_cart_contents_weight();
        $cart_subtotal_incl_tax = $cart->get_subtotal() + $cart->get_subtotal_tax();
        $cart_subtotal_excl_tax = $cart->get_subtotal();
        $cart_item_count = $cart->get_cart_contents_count();
        $cart_contents = $cart->get_cart_contents();
        $cart_coupons = $cart->get_applied_coupons();

        $cart_max_width_height = Dspilot_Helper::get_cart_max_width_height();
        $cart_max_height = $cart_max_width_height['max_height'];
        $cart_max_width = $cart_max_width_height['max_width'];

       
        $cart_max_length = Dspilot_Helper::get_cart_max_length();
        $cart_min_stock = Dspilot_Helper::get_min_stock_of_cart_items();
        $cart_product_ids = Dspilot_Helper::get_cart_product_ids();

        $cart_product_variations = Dspilot_Helper::get_cart_product_variation_ids();
        $current_user_id = get_current_user_id();

        $chosen_payment_method_id = WC()->session->get( 'chosen_payment_method' ); 
        $chosen_shipping_method_id = Dspilot_Helper::get_selected_shipping_method(); 


        foreach ( $conditions as $condition ) {
            $type = $condition['condition'] ?? '';
            $compare = $condition['condition_compare'] ?? 'equal_to';

            if(in_array($type, ['user_email', 'user_meta', 'coupons_applied', 'shipping_city', 'shipping_postcode'])){
                $value = $condition['text'];
            }else if(in_array($type, ['last_order_date'])){
                $value = $condition['date'];
            }else if(in_array($type, ['products_in_cart', 'featured_products_in_cart', 'onsale_products_in_cart', 'bought_products', 'bought_featured_products', 'bought_onsale_products'])){
                $value = $condition['product_ids'] ?? [];
            }else if(in_array($type, ['product_categories_in_cart', 'bought_product_categories'])){
                $value = $condition['category_ids'] ?? [];
            }else if(in_array($type, ['product_brands_in_cart', 'bought_product_brands'])){
                $value = $condition['brand_ids'] ?? [];
            }else if(in_array($type, ['product_variations_in_cart', 'quantity_of_variations', 'bought_variations', 'quantity_of_bought_variations', 'amount_of_bought_variations'])){
                $value = $condition['variation_ids'] ?? [];
            }else if(in_array($type, ['shipping_classes_in_cart'])){
                $value = $condition['shipping_classes'] ?? [];
            }else if(in_array($type, ['user_roles'])){
                $value = $condition['user_roles'];
            }else if(in_array($type, ['user_capability'])){
                $value = $condition['user_capabilities'];
            }else if(in_array($type, ['is_user_logged_in'])){
                $value = $condition['bool'];
            }else if(in_array($type, ['payment_method'])){
                $value = $condition['payment_methods'];
            }else if(in_array($type, ['shipping_method'])){
                $value = $condition['shipping_methods'];
            }else if(in_array($type, ['shipping_country'])){
                $value = $condition['shipping_countries'];
            }else if(in_array($type, ['shipping_state'])){
                $value = $condition['shipping_states'];
            }else if(in_array($type, ['shipping_zone'])){
                $value = $condition['shipping_zones'];
            }else{
                $value = $condition['number'];
            }

            $product_ids = $condition['product_ids'] ?? [];
            $variation_ids = $condition['variation_ids'] ?? [];
            $category_ids = $condition['category_ids'] ?? [];
            $brand_ids = $condition['brand_ids'] ?? [];
            $user_roles = $condition['user_roles'] ?? [];
            $shipping_classes = $condition['shipping_classes'] ?? [];
            $user_meta_key = $condition['user_meta_key'] ?? '';

        
            $value = is_array( $value ) ? $value : ( is_numeric( $value ) ? floatval( $value ) : sanitize_text_field( $value ) );
            $target = null;
            $target = apply_filters( 'dspilot_discount_condition_target', $target, $type, $condition );

            if ( null === $target ) {
            switch ( $type ) {
                // ✅ Cart conditions
                case 'cart_total_weight':
                    $target = $cart_total_weight;
                    break;
                case 'number_of_cart_items':
                    $target = count( $cart_items );
                    break;
                case 'subtotal_including_tax':
                    $target = $cart_subtotal_incl_tax;
                    break;

                case 'bought_products':
                    $target = Dspilot_Helper::bought_products();
                    $value =  $product_ids;
                    break;


                default:
                    do_action( 'dspilot_custom_coupon_condition_fallback', $type, $compare, $value );
                    break;
            }
            }

            if (! Dspilot_Helper::evaluate_condition_compare($target, $compare, $value)) {
                return false;
            }
        }

        return true;
    }




}

new DSPILOT_Coupon_Discount();

add_action( 'wp_footer', function(){
    
});
