<?php

namespace Webnestors\Wsn\Snippets;

class GeneralAddSecondStockLocation extends \Webnestors\Wsn\Snippet {
    public function is_pro(): bool {
        return false;
    }

    public function tab(): string {
        return "general";
    }

    public function title(): string {
        return __("Add a Second Stock Location", "enhancements-for-woocommerce");
    }

    public function description(): string {
        return __(
            "Create a second stock location for each product. You will find the second stock location when you will edit products. This will decrease the stock quantity automatically when a order is placed.",
            "enhancements-for-woocommerce"
        );
    }

    public function meta(): array {
        return [];
    }

    public function tooltip(): ?string {
        ob_start(); ?>
        <h1><strong><?php echo esc_html($this->title()); ?></strong></h1>
        <h3>Description</h3>
        <p>The Add a Second Stock Location module is a powerful tool for WooCommerce stores that need to manage inventory across multiple locations. With this feature, you can create a second stock location for each product, allowing you to track inventory separately for two distinct locations—such as a warehouse, retail store, or online fulfillment center. This module is particularly useful for businesses that operate from multiple locations or have separate stock for online and physical sales.</p>
        <p>Once the second stock location is configured, you will find the additional stock management option directly within the product editing page, alongside the standard stock fields. This means that for every product in your store, you can maintain two distinct stock quantities. Whenever an order is placed, the system automatically deducts from the specified stock location, ensuring that your inventory levels remain accurate and up to date. This functionality is essential for businesses that need a streamlined approach to managing multi-location inventory without relying on complex external systems.</p>
        <p>This module is only for the admins and not for your clients, so anything you place in the second stock location field in only for your eyes</p>
        <h3>Settings</h3>
        <p>There are no setting for this module</p>
        <h3>Quick Link</h3>
        <p><a href="/wp-admin/edit.php?post_type=product" target="_blank">PRODUCT EDIT PAGE</a> so that you can start adding the second stock location for each product</p>
        <h3>Appearance</h3>
        <p>There are no customization options for this module.</p>
        <?php return ob_get_clean();
    }

    public function run() {
        add_action("woocommerce_product_options_stock", [$this, "wn_additional_stock_location"]);
        add_action("save_post_product", [$this, "wn_save_additional_stock"]);
        add_filter(
            "woocommerce_product_get_stock_quantity",
            [$this, "wn_get_overall_stock_quantity"],
            9999,
            2
        );
        add_filter(
            "woocommerce_product_get_stock_status",
            [$this, "wn_get_overall_stock_status"],
            9999,
            2
        );
        add_filter(
            "woocommerce_payment_complete_reduce_order_stock",
            [$this, "wn_maybe_reduce_second_stock"],
            9999,
            2
        );
        
    }

    function wn_additional_stock_location() {
        global $product_object;
        echo '<div class="show_if_simple show_if_variable">';

        woocommerce_wp_text_input([
            "id" => "_stock2",
            "value" => get_post_meta($product_object->get_id(), "_stock2", true),
            "label" => "2nd Stock Location",
            "data_type" => "stock",
        ]);

        echo "</div>";
        
    }

    function wn_save_additional_stock($product_id) {
        global $typenow;

        if ("product" === $typenow) {
            if (defined("DOING_AUTOSAVE") && DOING_AUTOSAVE) {
                return;
            }

            if (isset($_POST["_stock2"])) {
                update_post_meta($product_id, "_stock2", $_POST["_stock2"]);
            }
        }
        
    }

    function wn_get_overall_stock_quantity($value, $product) {
        $value = (int) $value + (int) get_post_meta($product->get_id(), "_stock2", true);
        return $value;
        
    }

    function wn_get_overall_stock_status($status, $product) {
        if (!$product->managing_stock()) {
            return $status;
        }

        $stock =
            (int) $product->get_stock_quantity() +
            (int) get_post_meta($product->get_id(), "_stock2", true);

        $status = $stock && $stock > 0 ? "instock" : "outofstock";

        return $status;
        
    }

    function wn_maybe_reduce_second_stock($reduce, $order_id) {
        $order = wc_get_order($order_id);
        $atleastastock2change = false;

        foreach ($order->get_items() as $item) {
            if (!$item->is_type("line_item")) {
                continue;
            }

            $product = $item->get_product();
            $item_stock_reduced = $item->get_meta("_reduced_stock", true);

            if ($item_stock_reduced || !$product || !$product->managing_stock()) {
                continue;
            }

            $qty = apply_filters("woocommerce_order_item_quantity", $item->get_quantity(), $order, $item);
            $stock1 = (int) get_post_meta($product->get_id(), "_stock", true);

            if ($qty <= $stock1) {
                continue;
            }

            $atleastastock2change = true;
        }

        if (!$atleastastock2change) {
            return $reduce;
        }

        foreach ($order->get_items() as $item) {
            if (!$item->is_type("line_item")) {
                continue;
            }

            $product = $item->get_product();
            $item_stock_reduced = $item->get_meta("_reduced_stock", true);

            if ($item_stock_reduced || !$product || !$product->managing_stock()) {
                continue;
            }

            $item_name = $product->get_formatted_name();
            $qty = apply_filters("woocommerce_order_item_quantity", $item->get_quantity(), $order, $item);
            $stock1 = (int) get_post_meta($product->get_id(), "_stock", true);
            $stock2 = (int) get_post_meta($product->get_id(), "_stock2", true);

            if ($qty <= $stock1) {
                wc_update_product_stock($product, $qty, "decrease");

                $order->add_order_note(
                    sprintf(
                        'Reduced stock for item "%s"; Stock 1: "%s" to "%s".',
                        $item_name,
                        $stock1,
                        $stock1 - $qty
                    )
                );
            } else {
                $newstock2 = $stock2 - ($qty - $stock1);
                wc_update_product_stock($product, $stock1, "decrease");
                update_post_meta($product->get_id(), "_stock2", $newstock2);
                $item->add_meta_data("_reduced_stock", $qty, true);
                $item->save();

                $order->add_order_note(
                    sprintf(
                        'Reduced stock for item "%s"; Stock 1: "%s" to "0" and Stock 2: "%s" to "%s".',
                        $item_name,
                        $stock1,
                        $stock2,
                        $newstock2
                    )
                );
            }
        }

        $order->get_data_store()->set_stock_reduced($order_id, true);
        return false;
    }
    
}
