<?php

/**
 * The admin-specific functionality of the plugin.
 *
 * @link       garidium.com
 * @since      1.0.0
 *
 * @package    g_Ffl_Cockpit
 * @subpackage g_Ffl_Cockpit/admin
 */

/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    g_Ffl_Cockpit
 * @subpackage g_Ffl_Cockpit/admin
 * @author     Big G <sales@garidium.com>
 */


// Function to check if the product has the '_automated_listing' metadata set
function g_ffl_cockpit_is_automated_listing($product_id) {
    return get_post_meta($product_id, 'automated_listing') ? true : false;
}

// Hook to add custom section to product additional information tab
add_filter('woocommerce_product_tabs', 'g_ffl_cockpit_custom_product_section_tab');

function g_ffl_cockpit_custom_product_section_tab($tabs) {
    global $product;
    // Check if the current user is an admin
    if (current_user_can('administrator')) {
        if (g_ffl_cockpit_is_automated_listing($product->get_id())){
            // Add a new tab with the title 'Custom Section'
            $tabs['custom_section'] = array(
                'title'    => __('Admin', 'g-ffl-cockpit'),
                'priority' => 80,
                'callback' => 'g_ffl_cockpit_custom_product_section_content',
            );
        }
    }

    return $tabs;
}

function g_ffl_cockpit_custom_product_section_content() {
    global $product;

    // Get the UPC attribute value
    $upc = $product->get_attribute('upc');
    $product_id = $product->get_id();
    $gFFLCockpitKey = get_option('g_ffl_cockpit_key');

    // Add a radio button list with a search input inside a scrollable div
    echo '<span style="color:red;font-style:italic;">The "Admin" section will only appear to logged-in admin users of your site. Your customer will not see the "Admin" section.</span><br><b>Product Category Change:</b> This will update the product category on your site AND the product category this product is associated with for <u>All Cockpit Fed Sites</u>. So please make sure you are making changes that help everyone. <u>Thank you</u> for your contribution, Gary<br><br>';
    echo '<input type="text" id="ffl-cockpit-category-search" placeholder="Search categories..." style="width:450px; margin-bottom: 10px;"><br>';
    echo '<div id="ffl-cockpit-category-list" style="width:450px; max-height: 200px; overflow-y: auto; border: 1px solid #ccc; padding: 10px;"></div>';
    echo '<button id="ffl-cockpit-recategorize-button" style="width: 450px; margin-top: 10px;">Apply Category Update</button>';
    echo '
    <script>
        jQuery(document).ready(function ($) {
            $("#ffl-cockpit-recategorize-button").on("click", function () {
                var selected = document.querySelector(\'input[name="ffl-cockpit-category"]:checked\');
                if (!selected) {
                    alert("You must select a valid category");
                    return;
                }
                var category_id = selected.value;

                document.getElementById("ffl-cockpit-recategorize-button").disabled = true;
                document.getElementById("ffl-cockpit-recategorize-button").innerText = "Updating Category...";
                var product_id = "'.esc_attr($product_id).'";
                var upc = "'.esc_attr($upc).'";

                fetch("https://ffl-api.garidium.com", {
                    method: "POST",
                    headers: {
                    "Accept": "application/json",
                    "Content-Type": "application/json",
                    "x-api-key": "'.esc_attr($gFFLCockpitKey).'",
                    },
                    body: JSON.stringify({"action": "update_product_category", "data": {"product_id": product_id, "category_id": category_id , "upc": upc , "api_key": "'.esc_attr($gFFLCockpitKey).'"}})
                })
                .then(response => response.json())
                .then(data => { 
                    document.getElementById("ffl-cockpit-recategorize-button").disabled = false;
                    document.getElementById("ffl-cockpit-recategorize-button").innerText = "Apply Category Update";
                
                    if (data.success){
                        location.reload();
                    } else {
                        alert("There was a problem in recategorization");
                    }
                });
            });

            fetch("https://ffl-api.garidium.com", {
                method: "POST",
                headers: {
                "Accept": "application/json",
                "Content-Type": "application/json",
                "x-api-key": "'.esc_attr($gFFLCockpitKey).'",
                },
                body: JSON.stringify({"action": "get_category_list", "data": {"api_key": "'.esc_attr($gFFLCockpitKey).'"}})
            })
            .then(response => response.json())
            .then(data => { 
                // Get the container element
                const container = document.getElementById("ffl-cockpit-category-list");
                if (data != null && data.categories.length > 0){
                    // Loop through the data and create a radio button for each item
                    data.categories.forEach(item => {
                        const label = document.createElement("label");
                        label.style.display = "block";
                        label.style.marginBottom = "5px";

                        const radio = document.createElement("input");
                        radio.type = "radio";
                        radio.name = "ffl-cockpit-category";
                        radio.value = item.id;
                        radio.style.marginRight = "10px";

                        label.appendChild(radio);
                        var cat_label = item.name;
                        if (item.parent != null){
                            cat_label+=" (" + item.parent + ")"
                        }
                        label.appendChild(document.createTextNode(cat_label));

                        container.appendChild(label);
                    });
                }

                // Add event listener for search input
                document.getElementById("ffl-cockpit-category-search").addEventListener("input", function() {
                    const filter = this.value.toLowerCase();
                    const labels = container.getElementsByTagName("label");
                    for (let i = 0; i < labels.length; i++) {
                        const text = labels[i].textContent.toLowerCase();
                        labels[i].style.display = text.includes(filter) ? "block" : "none";
                    }
                });
            });
        });
    </script>';
}

add_action('woocommerce_duplicate_product', 'g_ffl_cockpit_handle_product_duplication_metadata', 10, 2);
function g_ffl_cockpit_handle_product_duplication_metadata($duplicated_product_id, $original_product) {
    // Ensure the duplicated product ID is valid
    if (!is_int($duplicated_product_id) || !$duplicated_product_id) {
        return;
    }

    // Retrieve the original product ID from the stdClass object
    $original_product_id = isset($original_product->ID) ? $original_product->ID : null;

    // If the original product ID is not available, exit
    if (!$original_product_id) {
        return;
    }

    // Check if the original product has the 'automated_listing' meta key
    $automated_listing_meta = get_post_meta($original_product_id, 'automated_listing', true);

    // If the 'automated_listing' meta key does not exist, exit
    if (empty($automated_listing_meta)) {
        return;
    }

    // Load the duplicated product object
    $duplicated_product = wc_get_product($duplicated_product_id);

    // Ensure the product object is valid
    if (!$duplicated_product) {
        return;
    }

    // Remove the 'automated_listing' meta key from the duplicated product
    delete_post_meta($duplicated_product_id, 'automated_listing');

    // Get the current user
    $current_user = wp_get_current_user();

    // Add metadata to identify the product as a duplicate
    update_post_meta($duplicated_product_id, '_is_duplicate', true);

    // Add metadata to capture who duplicated the product
    update_post_meta($duplicated_product_id, '_duplicated_by', $current_user->user_login);

    // Add metadata to capture when the product was duplicated
    update_post_meta($duplicated_product_id, '_duplicated_at', current_time('mysql'));

    // Add metadata to reference the original product ID
    update_post_meta($duplicated_product_id, '_original_product_id', $original_product_id);

    // Get the UPC attribute value
    $upc = $duplicated_product->get_attribute('upc');

    // Check if UPC exists and construct the new SKU
    if (!empty($upc)) {
        $new_sku = 'ISD|' . $upc;
        $duplicated_product->set_sku($new_sku); // Set the new SKU
        $duplicated_product->save(); // Save the updated product
    } else {
        g_ffl_debug_log('UPC attribute is missing for product ID: ' . $duplicated_product_id, 'warning');
    }
}
