<?php

add_action('admin_enqueue_scripts', 'wcmlim_enqueue_scripts');
add_action( 'wp_enqueue_scripts', 'wcmlim_enqueue_fronetend_scripts' );

function wcmlim_enqueue_scripts() {
    // Enqueue existing script for asynchronous location loading
    wp_enqueue_script(
        'wcmlim-async-locations',
        plugins_url('js/wcmlim-async-locations.js', __FILE__),
        ['jquery'],
        '1.0',
        true
    );

    // Localize both scripts for AJAX URL and nonce security
    wp_localize_script('wcmlim-async-locations', 'wcmlim_ajax', [
        'ajax_url' => admin_url('admin-ajax.php'),
        'security'    => wp_create_nonce('wcmlim_locations_nonce'),
    ]);

}

function wcmlim_enqueue_fronetend_scripts() {
    wp_enqueue_script(
        'wcmlim-async-stock',
        plugins_url('js/wcmlim-async-stock.js', __FILE__),
        array( 'jquery' ),
        '1.0',
        true
    );

    wp_localize_script( 'wcmlim-async-stock', 'wcmlim_ajax', array(
        'ajax_url' => admin_url( 'admin-ajax.php' ),
    ) );
}

function wcmlim_load_locations_data() {

    // Check nonce for security of CSRF
    check_ajax_referer('wcmlim_locations_nonce', 'security');

    if(isset($_POST['security']) && !wp_verify_nonce($_POST['security'], 'wcmlim_locations_nonce')) {
		wp_send_json(array(
			'success' => false,
			'message' => 'Invalid nonce'
		));
		return;
	}

    // Ensure no previous output to prevent JSON errors
    if (ob_get_length()) {
        ob_end_clean();
    }

    // Set response as JSON
    header('Content-Type: application/json; charset=utf-8');

    // Check user permission
    if (!current_user_can('edit_posts')) {
        wp_send_json_error(['message' => 'User does not have permission.']);
    }

    // Get and validate product ID
    $product_id = isset($_POST['product_id']) ? absint($_POST['product_id']) : 0;
    if (!$product_id) {
        wp_send_json_error(['message' => 'Product ID is missing.']);
    }

    // Retrieve WooCommerce product
    $product = wc_get_product($product_id);
    if (!$product) {
        wp_send_json_error(['message' => 'Invalid product.']);
    }

    // Fetch locations from cache or database
    $locations = get_transient('wcmlim_product_locations');
    if (!$locations) {
        $locations = get_terms([
            'taxonomy'   => 'locations',
            'hide_empty' => false,
            'parent'     => 0,
        ]);
        set_transient('wcmlim_product_locations', $locations, HOUR_IN_SECONDS);
    }

    // If no locations exist, return an error
    if (empty($locations)) {
        wp_send_json_error(['message' => 'No locations found.']);
    }

    // Get current user and role
    $user = wp_get_current_user();
    $user_roles = (array) $user->roles;

    /**
     * Check if the user is a regional manager and get locations from assigned groups.
     * - Verifies 'location_regional_manager' role.
     * - Retrieves all location groups.
     * - Matches user ID with 'wcmlim_shop_regmanager' metadata.
     * - Fetches locations from 'wcmlim_location' metadata for matched groups.
     */
    if (in_array('location_regional_manager', $user_roles)) {

        $location_groups = get_terms(array(
            'taxonomy' => 'location_group',
            'hide_empty' => false, // Get all groups even if they have no locations
        ));

        // $user_assigned_locations = [];
        $regional_manager_locations = [];

        foreach ($location_groups as $group) {
            // Decode serialized data if necessary
            $shop_regmanager = get_term_meta($group->term_id, 'wcmlim_shop_regmanager', true);
            $shop_regmanager = maybe_unserialize($shop_regmanager);

            // Check if the current user ID matches the shop_regmanager
            if (is_array($shop_regmanager) && in_array($user->ID, $shop_regmanager)) {

                $group_locations = get_term_meta($group->term_id, 'wcmlim_location', true);
                $group_locations = maybe_unserialize($group_locations);

                // Merge locations from all matching groups
                if (is_array($group_locations)) {
                    $regional_manager_locations = array_merge($regional_manager_locations, $group_locations);
                }
            }
        }

        // Remove duplicate locations, if any
        $regional_manager_locations = array_unique($regional_manager_locations);

    }
    
    // If the user is a Shop Manager, filter assigned locations
    if (in_array('shop_manager', $user_roles)) {
        $assigned_location_ids = get_user_meta($user->ID, 'wcmlim_assigned_locations', true);

        // Ensure assigned locations are in an array of integers
        if (!$assigned_location_ids) {
            $assigned_location_ids = [];
        } elseif (!is_array($assigned_location_ids)) {
            $assigned_location_ids = [(int) $assigned_location_ids];
        } else {
            $assigned_location_ids = array_map('intval', $assigned_location_ids);
        }

        // Debugging logs

        // Filter locations based on assigned location IDs
        $locations = array_filter($locations, function ($location) use ($assigned_location_ids, $product_id) {
            $is_assigned = in_array((int) $location->term_id, $assigned_location_ids, true);
            $is_allowed = get_post_meta($product_id, "wcmlim_stock_at_{$location->term_id}", true);
            return $is_assigned && !empty($is_allowed);
        });

        // Debugging logs

        // If no valid locations are assigned, return an error
        if (empty($locations)) {
            wp_send_json_error(['message' => 'No locations assigned to this user.']);
        }
    }

    // Capture output using output buffering
    ob_start();
    ?>
    <div class="wcmlim-stock-container">
        <!-- Simple Product -->
        <?php if ($product->is_type('simple')) : ?>
            <h4 class="wcmlim-product-title">Simple Product: <?= esc_html($product->get_name()); ?></h4>
            <div class="wcmlim-main-stock-row">
                <?php foreach ($locations as $location) :

                    $tmp = get_term_meta($location->term_id, 'wcmlim_shop_manager', true);
                    
                    // Conditoins to filter locatioons from frontend
                    if ((isset($tmp[0]) && get_current_user_id() == $tmp[0]) || 
                    (isset($regional_manager_locations) && !empty($regional_manager_locations) && in_array($location->term_id, $regional_manager_locations)) || 
                    current_user_can('administrator')) {
                    $stock_at_location = (int) get_post_meta($product_id, "wcmlim_stock_at_{$location->term_id}", true);
                ?>
                    <div class="wcmlim-stock-row">
                        <label class="wcmlim-stock-label">
                            <?= esc_html($location->name); ?>
                            <span class="stock_at_location_count">(<?= esc_attr($stock_at_location); ?>)</span>
                        </label>
                        <div class="wcmlim-stock-controls" style="display:none;">
                        <input type="number" class="wcmlim-stock-input" data-location-id="<?= esc_attr($location->term_id); ?>" value="<?= esc_attr($stock_at_location); ?>" />
                        <button type="button" class="button wcmlim-edit-stock-button" data-product-id="<?= esc_attr($product_id); ?>" data-location-id="<?= esc_attr($location->term_id); ?>">Save</button>
                    </div>
                    </div>
                <?php 
                } 
            endforeach; 
            ?>
            </div>
        <?php endif; ?>

        <!-- Variable Product -->
        <?php if ($product->is_type('variable')) : ?>
            <h4 class="wcmlim-product-title">Variable Product: <?= esc_html($product->get_name()); ?></h4>
            <div class="wcmlim-main-stock-row">
                <?php
                $variations = $product->get_children(); // Get all variations
                foreach ($variations as $variation_id) :

                    $variation = wc_get_product($variation_id);
                    if (!$variation) continue;

                    // Get variation name based on attributes
                    $variation_name = implode(', ', array_map('ucfirst', $variation->get_attributes()));
                ?>
                    <div class="wcmlim-variation-block">
                        <h5 class="wcmlim-variation-title"><?= esc_html($variation_name); ?></h5>
                        <?php foreach ($locations as $location) :

                         $variable = get_term_meta($location->term_id, 'wcmlim_shop_manager', true);

                        // Conditoins to filter locatioons from frontend
                        if ( (isset($variable[0]) && get_current_user_id() == $variable[0]) || 
                        (isset($regional_manager_locations) && !empty($regional_manager_locations) && in_array($location->term_id, $regional_manager_locations)) || 
                        current_user_can('administrator')) {

                            $stock_at_location = (int) get_post_meta($variation_id, "wcmlim_stock_at_{$location->term_id}", true);
                        ?>
                            <div class="wcmlim-stock-row">
                                <label class="wcmlim-stock-label">
                                    <?= esc_html($location->name); ?>
                                    <span class="stock_at_location_count">(<?= esc_attr($stock_at_location); ?>)</span>
                                </label>

                                 <div class="wcmlim-stock-controls" style="display:none;">
                                    <input type="number" class="wcmlim-stock-input" data-location-id="<?= esc_attr($location->term_id); ?>" value="<?= esc_attr($stock_at_location); ?>" />
                                    <button type="button" class="button wcmlim-edit-stock-button" data-product-id="<?= esc_attr($variation_id); ?>" data-location-id="<?= esc_attr($location->term_id); ?>">Save</button>
                                </div>
                            </div>
                        <?php 
                    }
                    endforeach; ?>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
    <?php
    $html = ob_get_clean();

    // Ensure no further output and return JSON response
    ob_end_clean();
    wp_send_json_success(['html' => $html]);
    exit;
}


// Hook into AJAX actions
add_action('wp_ajax_wcmlim_load_locations_data', 'wcmlim_load_locations_data');
add_action('wp_ajax_nopriv_wcmlim_load_locations_data', 'wcmlim_load_locations_data'); // Allow non-logged-in users if needed

function wcmlim_build_simple_product_html($product, $locations)
{
    $html = '<label>#' . esc_html($product->get_id()) . ':</label><br>';

    if ($product->managing_stock()) {
        foreach ($locations as $location) {
            $stock_at_location = (int) get_post_meta($product->get_id(), 'wcmlim_stock_at_' . $location->term_id, true);
            $html .= '<span>' . esc_html($location->name) . ': ' . esc_html($stock_at_location) . '</span><br>';
        }
    } else {
        $stock_status = $product->is_in_stock() ? 'In stock' : 'Out of stock';
        $html .= '<mark>' . esc_html($stock_status) . '</mark>';
    }

    return $html;
}


function wcmlim_build_variable_product_html($product, $locations)
{
    $html = '';
    $variation_ids = $product->get_children();

    foreach ($variation_ids as $variation_id) {
        $variation_product = wc_get_product($variation_id);

        if ($variation_product->managing_stock()) {
            $attributes = $variation_product->get_variation_attributes();
            $attribute_list = implode(', ', array_map('ucfirst', $attributes));

            $html .= '<label>#' . esc_html($variation_id) . ' (' . esc_html($attribute_list) . '):</label><br>';
            foreach ($locations as $location) {
                $stock_at_location = (int) get_post_meta($variation_id, 'wcmlim_stock_at_' . $location->term_id, true);
                $html .= '<span>' . esc_html($location->name) . ': ' . esc_html($stock_at_location) . '</span><br>';
            }
        }
    }

    return $html;
}

add_action('wp_ajax_wcmlim_update_stock_data', 'wcmlim_update_stock_data');
function wcmlim_update_stock_data()
{
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error([
            'message' => 'Unauthorized access',
        ], 403);
        return;
    }
    // check nonce for CSRF security
    check_ajax_referer('wcmlim_locations_nonce', 'security');

    if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'wcmlim_locations_nonce')) {
        wp_send_json_error(['message' => 'Nonce verification failed.']);
    }

    if (!current_user_can('edit_posts')) {
        wp_send_json_error(['message' => 'User does not have permission.']);
    }

    $product_id = isset($_POST['product_id']) ? absint($_POST['product_id']) : 0;
    $location_id = isset($_POST['location_id']) ? absint($_POST['location_id']) : 0;
    $new_stock = isset($_POST['new_stock']) ? intval($_POST['new_stock']) : 0;

    if (!$product_id || !$location_id) {
        wp_send_json_error(['message' => 'Missing product or location ID.']);
    }

    update_post_meta($product_id, "wcmlim_stock_at_{$location_id}", $new_stock);

    wp_send_json_success(['message' => 'Stock updated successfully.']);
}

?>