<?php

namespace DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\ProductFields\Value;

use WC_Product;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\ProductFields\ProductFieldFloatValue;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\ProductFields\ProductFieldValue;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\ProductFields\StockModificator;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\ProductFields\ProductFieldValueModificator;
class StockProductFieldValue implements ProductFieldValue, ProductFieldFloatValue, StockModificator
{
    public const KEY = 'stock';
    private ?float $value = null;
    private WC_Product $product;
    private ?ProductFieldValueModificator $modificator = null;
    public function __construct(WC_Product $product)
    {
        $this->product = $product;
    }
    public static function get_key(): string
    {
        return self::KEY;
    }
    public static function get_name(): string
    {
        return esc_attr__('Stock quantity', 'dropshipping-export-free');
    }
    public function set_stock_modificator(ProductFieldValueModificator $modificator)
    {
        $this->modificator = $modificator;
        $this->modificator->set_product($this->product);
    }
    public function has_float_value(): bool
    {
        return \is_float($this->get_field_value());
    }
    public function get_float_value(): ?float
    {
        return $this->get_field_value();
    }
    private function get_field_value(): ?float
    {
        if ($this->value !== null) {
            return $this->value;
        }
        if (isset($this->modificator) && $this->modificator instanceof ProductFieldFloatValue && $this->modificator->has_float_value()) {
            $stock = $this->modificator->get_float_value();
        } else {
            $stock = $this->product->get_stock_quantity();
        }
        $this->value = is_numeric($stock) ? (float) $stock : null;
        return $this->value;
    }
}
