<?php
/**
 * Adds UI and persistence for per-product thresholds.
 *
 * @package StockGuardianPro
 */

declare(strict_types=1);

namespace StockGuardianPro\LowStock\Services;

use StockGuardianPro\LowStock\Plugin;
use WC_Product;

\defined('ABSPATH') || exit;

final class ProductThresholdService implements ServiceInterface
{
    private Plugin $plugin;

    private ThresholdRepository $thresholds;

    public function __construct(Plugin $plugin)
    {
        $this->plugin     = $plugin;
        $this->thresholds = new ThresholdRepository($plugin);
    }

    public function register(): void
    {
        add_action('woocommerce_product_options_inventory_product_data', [$this, 'render_product_field']);
        add_action('woocommerce_admin_process_product_object', [$this, 'save_product_threshold']);
        add_action('woocommerce_variation_options_inventory', [$this, 'render_variation_field'], 10, 3);
        add_action('woocommerce_save_product_variation', [$this, 'save_variation_threshold'], 10, 2);
    }

    public function render_product_field(): void
    {
        global $product_object;

        if (! $product_object instanceof WC_Product) {
            return;
        }

        $threshold = $this->thresholds->get_threshold($product_object->get_id());

        woocommerce_wp_text_input(
            [
                'id'          => 'woolsn_custom_threshold',
                'label'       => __('Low stock threshold override', 'stock-guardian-pro'),
                'desc_tip'    => true,
                'description' => __('Leave empty to use the global default threshold.', 'stock-guardian-pro'),
                'type'        => 'number',
                'custom_attributes' => [
                    'min' => '0',
                ],
                'value'       => $threshold !== null ? $threshold : '',
            ]
        );
    }

    public function save_product_threshold(WC_Product $product): void
    {
        // phpcs:ignore WordPress.Security.NonceVerification.Missing
        // WooCommerce handles nonce verification via woocommerce_admin_process_product_object action
        // phpcs:ignore WordPress.Security.NonceVerification.Missing
        if (! isset($_POST['woolsn_custom_threshold'])) {
            return;
        }
        // phpcs:ignore WordPress.Security.NonceVerification.Missing
        $value = sanitize_text_field((string) wp_unslash($_POST['woolsn_custom_threshold']));
        $value = trim((string) $value);

        if ($value === '') {
            $this->thresholds->delete_threshold((int) $product->get_id());
            return;
        }

        $this->thresholds->set_threshold((int) $product->get_id(), max(0, (int) $value));
    }

    public function render_variation_field(int $loop, array $variation_data, $variation): void // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter
    {
        $variation_id = isset($variation->ID) ? (int) $variation->ID : 0;
        if ($variation_id <= 0) {
            return;
        }

        $variation_product = wc_get_product($variation_id);
        if (! $variation_product instanceof WC_Product) {
            return;
        }

        $threshold = $this->thresholds->get_threshold(
            $variation_product->get_parent_id(),
            $variation_product->get_id()
        );

        woocommerce_wp_text_input(
            [
                'id'                => "woolsn_threshold_variation_{$variation_id}",
                'name'              => "woolsn_threshold_variation[{$variation_id}]",
                'label'             => __('Low stock threshold override', 'stock-guardian-pro'),
                'desc_tip'          => true,
                'description'       => __('Leave empty to inherit the parent product threshold.', 'stock-guardian-pro'),
                'type'              => 'number',
                'wrapper_class'     => 'form-row form-row-full',
                'custom_attributes' => [
                    'min' => '0',
                ],
                'value'             => $threshold !== null ? $threshold : '',
            ]
        );
    }

    public function save_variation_threshold(int $variation_id, int $loop): void // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter
    {
        // phpcs:ignore WordPress.Security.NonceVerification.Missing
        // WooCommerce handles nonce verification via woocommerce_save_product_variation action
        // phpcs:ignore WordPress.Security.NonceVerification.Missing
        if (! isset($_POST['woolsn_threshold_variation'][$variation_id])) {
            return;
        }
        // phpcs:ignore WordPress.Security.NonceVerification.Missing
        $value = sanitize_text_field((string) wp_unslash($_POST['woolsn_threshold_variation'][$variation_id]));
        $value = trim((string) $value);
        $variation_product = wc_get_product($variation_id);

        if (! $variation_product instanceof WC_Product) {
            return;
        }

        $parent_id = (int) $variation_product->get_parent_id();

        if ($value === '') {
            $this->thresholds->delete_threshold($parent_id, $variation_id);
            return;
        }

        $this->thresholds->set_threshold($parent_id, max(0, (int) $value), $variation_id);
    }
}



