<?php
/**
 * OpenPOS Dynamic Pricing based on Location
 *
 * This code dynamically adjusts product prices based on the user's location
 * and the associated warehouse in OpenPOS.
 *
 * @package OpenPOS
 */

// Don't run pricing hooks in customizer to avoid issues
if (!is_customize_preview()) {
    add_filter( 'woocommerce_get_price', 'wcmlim_openpos_price_based_on_location', 10, 2 );
    add_filter( 'woocommerce_get_regular_price', 'wcmlim_openpos_price_based_on_location', 10, 2 );
    add_filter( 'woocommerce_get_sale_price', 'wcmlim_openpos_price_based_on_location', 10, 2 );
}

// Additional filters for variable products
add_filter( 'woocommerce_variation_prices_price', 'wcmlim_openpos_variation_price_based_on_location', 10, 3 );
add_filter( 'woocommerce_variation_prices_regular_price', 'wcmlim_openpos_variation_price_based_on_location', 10, 3 );
add_filter( 'woocommerce_variation_prices_sale_price', 'wcmlim_openpos_variation_price_based_on_location', 10, 3 );

// Filter for product variation objects
add_filter( 'woocommerce_product_variation_get_price', 'wcmlim_openpos_price_based_on_location', 10, 2 );
add_filter( 'woocommerce_product_variation_get_regular_price', 'wcmlim_openpos_price_based_on_location', 10, 2 );
add_filter( 'woocommerce_product_variation_get_sale_price', 'wcmlim_openpos_price_based_on_location', 10, 2 );

// Additional filters for variable product price ranges
add_filter( 'woocommerce_variable_price_html', 'wcmlim_openpos_variable_price_html', 10, 2 );

// Clear variation prices cache when user changes
add_action( 'wp_login', 'wcmlim_clear_variation_price_cache' );
add_action( 'wp_logout', 'wcmlim_clear_variation_price_cache' );

function wcmlim_openpos_price_based_on_location( $price, $product ) {
    // Step 1: Get the current user ID from cookie
    $user_id = isset($_COOKIE['openpos_user_id']) ? intval($_COOKIE['openpos_user_id']) : 0;

    $user_meta_key = '_op_allow_pos';
    $user_meta_value = get_user_meta($user_id, $user_meta_key, true);
    
    if ($user_meta_value != 1) {
        return $price;
    }
	
	
    // Step 2: Search postmeta for the "_op_cashiers" key
    global $wpdb;
    $query = "
        SELECT post_id, meta_value
        FROM {$wpdb->prefix}postmeta
        WHERE meta_key = '_op_cashiers'
    ";
    $posts = $wpdb->get_results( $query );


    // Step 3: Check each post's meta value to see if the current user ID is in the serialized array
    $matching_post_ids = array();
    foreach ( $posts as $post ) {
        $meta_value = maybe_unserialize( $post->meta_value ); // Unserialize the meta value

        // Check if the user ID is present in the unserialized array
        if ( is_array( $meta_value ) && in_array( $user_id, $meta_value ) ) {
            $matching_post_ids[] = $post->post_id;
        }
    }

    

    if ( empty( $matching_post_ids ) ) {
        return $price; // Return original price if no matching post ID is found
    }

    // Step 4: For each post, check if it's in publish status and retrieve warehouse_id (post_id)
    foreach ( $matching_post_ids as $post_id ) {
        $post_status = get_post_status( $post_id );


        if ( 'publish' !== $post_status ) {
            continue; // Skip if the post is not published
        }
		
		$outlet_id = get_post_meta($post_id,'_op_warehouse',true);
		
		 $outlet_status = get_post_status( $post_id );
		
		 if ( 'publish' !== $outlet_status ) {
            continue; // Skip if the post is not published
        }

        // Step 5: Get the location_id from wcmlim_openpos_mapping table (mapped with warehouse_id)
        $location_id = $wpdb->get_var( $wpdb->prepare(
            "SELECT location_id FROM {$wpdb->prefix}wcmlim_openpos_mapping WHERE warehouse_id = %d",
            $outlet_id
        ) );


        if ( !$location_id ) {
            continue; // Skip if no location_id found
        }

        // Step 6: Dynamically construct the meta keys for the location
        $regular_price_key = 'wcmlim_regular_price_at_' . $location_id;
        $sale_price_key = 'wcmlim_sale_price_at_' . $location_id;

        // Get the product ID - for variations, we need the variation ID, not the parent
        $product_id = $product->get_id();
        
        // For variable products, check if this is a variation
        if ( $product->is_type( 'variation' ) ) {
            $product_id = $product->get_id(); // Use variation ID
        } elseif ( $product->is_type( 'variable' ) ) {
            // For variable products without specific variation, return original price
            // The variation-specific filters will handle individual variations
            continue;
        }

        // Fetch the prices from postmeta
        $regular_price = get_post_meta( $product_id, $regular_price_key, true );
        $sale_price = get_post_meta( $product_id, $sale_price_key, true );


        // If sale price is available, use it, otherwise use regular price
        if ( ! empty( $sale_price ) ) {
            return $sale_price;
        }

        if ( ! empty( $regular_price ) ) {
            return $regular_price;
        }

        // If neither sale nor regular price is found, return the default price
        return $price;
    }

    // If no valid price was found, return the original price
    return $price;
}

/**
 * Handle pricing for variable product variations
 */
function wcmlim_openpos_variation_price_based_on_location( $price, $variation, $product ) {
    // Get the variation object if it's not already a WC_Product_Variation
    if ( is_numeric( $variation ) ) {
        $variation_product = wc_get_product( $variation );
    } else {
        $variation_product = $variation;
    }
    
    if ( ! $variation_product || ! is_a( $variation_product, 'WC_Product_Variation' ) ) {
        return $price;
    }
    
    // Use the main pricing function for the variation
    return wcmlim_openpos_price_based_on_location( $price, $variation_product );
}

/**
 * Handle variable product price HTML display
 */
function wcmlim_openpos_variable_price_html( $price_html, $product ) {
    // Let WooCommerce handle the price HTML generation
    // The individual variation prices will be handled by the variation filters
    return $price_html;
}

/**
 * Clear variation price cache when user login status changes
 */
function wcmlim_clear_variation_price_cache() {
    // Clear all product variation price cache
    wp_cache_flush_group( 'wc_var_prices' );
    
    // Also clear individual product caches if needed
    global $wpdb;
    $variable_products = $wpdb->get_col( "
        SELECT DISTINCT post_parent 
        FROM {$wpdb->posts} 
        WHERE post_type = 'product_variation' 
        AND post_status = %s
    ", 'publish' );

    foreach ( $variable_products as $product_id ) {
        wc_delete_product_transients( $product_id );
    }
}
