<?php

namespace Webnestors\Wsn\Snippets;

class AdminCostOfGoods extends \Webnestors\Wsn\Snippet {
    public function tab(): string {
        return "admin";
    }

    public function title(): string {
        return __("Cost of Goods", "enhancements-for-woocommerce");
    }

    public function description(): string {
        return __("Add cost of goods field to simple and variable products.", "enhancements-for-woocommerce");
    }

    public function snippet_name(): string {
        return "admin_cost_of_goods";
    }

    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 Cost of Goods module adds powerful cost tracking capabilities to your WooCommerce store. It allows you to track the actual cost of your products and monitor profitability at both product and order levels. This feature adds a cost field to both simple and variable products, enabling you to input the purchase or manufacturing cost for each item.</p>
        <p>The module automatically calculates and displays total costs and profit margins in the orders list, helping you track your store's profitability at a glance. Profits are color-coded (green for positive, red for negative) for quick visual reference.</p>
        <h3>Features</h3>
        <ul>
            <li>Cost field for simple products</li>
            <li>Cost field for each variation in variable products</li>
            <li>New columns in the orders list showing:
                <ul>
                    <li>Total Cost of Goods per order</li>
                    <li>Profit per order (with color coding)</li>
                </ul>
            </li>
        </ul>
        <h3>Usage</h3>
        <p>To add cost information, edit any product and look for the "Cost of Good" field in the pricing section. For variable products, you'll find the cost field within each variation's pricing options.</p>
        <h3>Appearance</h3>
        <p>The cost and profit information appears automatically in the orders list, with profits color-coded for easy reference.</p>
        <?php return ob_get_clean();
    }

    public function run() {
        // Add cost field to simple products
        add_action("woocommerce_product_options_pricing", [$this, "add_cost_field"]);
        add_action("woocommerce_process_product_meta", [$this, "save_cost_field"]);

        // Add cost field to variable products
        add_action("woocommerce_variation_options_pricing", [$this, "add_variation_cost_field"], 10, 3);
        add_action("woocommerce_save_product_variation", [$this, "save_variation_cost_field"], 10, 2);

        // Add new columns to orders page
        add_filter("manage_edit-shop_order_columns", [$this, "add_order_cost_columns"]);
        add_filter("manage_woocommerce_page_wc-orders_columns", [$this, "add_order_cost_columns"]);
        add_action("manage_shop_order_posts_custom_column", [$this, "populate_order_cost_columns"], 10, 2);
        add_action(
            "manage_woocommerce_page_wc-orders_custom_column",
            [$this, "populate_order_cost_columns"],
            10,
            2
        );
    }

    /**
     * Add cost field to simple products
     */
    public function add_cost_field() {
        woocommerce_wp_text_input([
            "id" => "_cost_of_good",
            "label" => __("Cost of Good", "enhancements-for-woocommerce"),
            "desc_tip" => true,
            "description" => __("Enter the cost price for this product.", "enhancements-for-woocommerce"),
            "type" => "number",
            "custom_attributes" => [
                "step" => "any",
                "min" => "0",
            ],
        ]);
    }

    /**
     * Save cost field for simple products
     */
    public function save_cost_field($post_id) {
        $cost = isset($_POST["_cost_of_good"]) ? sanitize_text_field($_POST["_cost_of_good"]) : "";
        update_post_meta($post_id, "_cost_of_good", $cost);
    }

    /**
     * Add cost field to variable products
     */
    public function add_variation_cost_field($loop, $variation_data, $variation) {
        woocommerce_wp_text_input([
            "id" => "_cost_of_good_variation[" . $loop . "]",
            "label" => __("Cost of Good", "enhancements-for-woocommerce"),
            "desc_tip" => true,
            "description" => __("Enter the cost price for this variation.", "enhancements-for-woocommerce"),
            "value" => get_post_meta($variation->ID, "_cost_of_good", true),
            "type" => "number",
            "custom_attributes" => [
                "step" => "any",
                "min" => "0",
            ],
            "wrapper_class" => "form-row form-row-first",
        ]);
    }

    /**
     * Save cost field for variable products
     */
    public function save_variation_cost_field($variation_id, $loop) {
        $cost = isset($_POST["_cost_of_good_variation"][$loop])
            ? sanitize_text_field($_POST["_cost_of_good_variation"][$loop])
            : "";

        update_post_meta($variation_id, "_cost_of_good", $cost);
    }

    /**
     * Add new columns to orders page
     */
    public function add_order_cost_columns($columns) {
        $new_columns = [];

        foreach ($columns as $column_name => $column_info) {
            $new_columns[$column_name] = $column_info;

            // Add our columns after the order total column
            if ($column_name === "order_total") {
                $new_columns["order_cost_of_goods"] = __(
                    "Total Cost of Goods",
                    "enhancements-for-woocommerce"
                );
                $new_columns["order_profit"] = __("Profit", "enhancements-for-woocommerce");
            }
        }

        return $new_columns;
    }

    /**
     * Calculate total cost of goods for an order
     */
    private function calculate_order_cost_of_goods($order) {
        $total_cost = 0;

        foreach ($order->get_items() as $item) {
            $product = $item->get_product();
            if (!$product) {
                continue;
            }

            // Get the product ID (handles both simple and variation products)
            $product_id = $product->get_id();

            // Get cost of good for this product
            $cost = get_post_meta($product_id, "_cost_of_good", true);

            // If cost exists, add it to total
            if ($cost !== "") {
                $total_cost += floatval($cost) * $item->get_quantity();
            }
        }

        return $total_cost;
    }

    /**
     * Populate our custom columns
     */
    public function populate_order_cost_columns($column, $order_id) {
        $order = wc_get_order($order_id);
        if (!$order) {
            return;
        }

        switch ($column) {
            case "order_cost_of_goods":
                $total_cost = $this->calculate_order_cost_of_goods($order);
                echo wc_price($total_cost);
                break;

            case "order_profit":
                $total_cost = $this->calculate_order_cost_of_goods($order);
                $order_total = $order->get_total();
                $profit = $order_total - $total_cost;

                // Display profit with color coding
                $color = $profit >= 0 ? "green" : "red";
                echo '<span style="color: ' . $color . '">' . wc_price($profit) . "</span>";
                break;
        }
    }
}
