<?php
if ( ! defined( 'ABSPATH' ) ) exit;

require_once VSERPB_PLUGIN_DIR . '/Schema_classes/class-vserpb-organization.php';

class Vserpb_Offer {

	private $price;
	private $priceCurrency;
	private $availability;
	private $url;
	private $seller;
	private $priceValidUntil;

	// Shipping data
	private $weight;
	private $dimensions;
	private $shippingRate;
	private $shippingDestination;
	private $deliveryTime;

	public function __construct( $product_id ) {

		$product = wc_get_product( $product_id );
		if ( ! $product ) return;

		// Offer price + seller
			if ( $product->is_type( 'variable' ) ) {
			 if ( $product->is_in_stock() ) {
				$this->price = $product->get_variation_price( 'min', true );
			 }

		} else {
			  if ( $product->is_in_stock() ) {
				$this->price = $product->is_on_sale()
					? $product->get_sale_price()
					: $product->get_regular_price();
			}
		}
		$this->priceCurrency = get_woocommerce_currency();
		$this->availability  = $product->is_in_stock() ? 'InStock' : 'OutOfStock';
		$this->url           = get_permalink( $product_id );
		$this->seller        = get_bloginfo( 'name' );


		$sale_start_date = $product->get_date_on_sale_from();
			$this->validFrom = $sale_start_date
			? gmdate('Y-m-d', strtotime($sale_start_date))
			: gmdate('Y-m-d'); // default today's date

		// Sale expiry / fallback
		$sale_end_date = $product->get_date_on_sale_to();
		$this->priceValidUntil = $sale_end_date
			? gmdate('Y-m-d', strtotime($sale_end_date))
			: gmdate('Y-m-d', strtotime('+30 days'));

		// Shipping values from WooCommerce
		$this->weight = $product->get_weight();
		$this->dimensions = [
			$product->get_length(),
			$product->get_width(),
			$product->get_height()
		];

		// ⭐ Get Shipping Costs + Zone Destination
		$this->load_shipping_details();
	}

	/**
	 * Fetch shipping rate + destination from WooCommerce shipping zones.
	 * Reads zone/method data directly — never touches WC()->cart so it is
	 * safe to call from the admin (product edit screen) as well as the front-end.
	 */
	private function load_shipping_details() {

		$default_delivery_time = '3-7 business days';

		// Guard: WC_Shipping_Zones may not be loaded on every admin screen.
		if ( ! class_exists( 'WC_Shipping_Zones' ) ) {
			return;
		}

		$zones = WC_Shipping_Zones::get_zones();

		foreach ( $zones as $zone ) {
			foreach ( $zone['shipping_methods'] as $method ) {

				if ( $method->enabled !== 'yes' ) {
					continue;
				}

				// Read the flat-rate cost directly from the method instance
				// (works for flat_rate; other types return null gracefully).
				$rate_cost = null;
				if ( isset( $method->cost ) && $method->cost !== '' ) {
					$rate_cost = wc_format_decimal( $method->cost, wc_get_price_decimals() );
				}

				$this->shippingRate = $rate_cost !== null
					? $rate_cost . ' ' . get_woocommerce_currency()
					: null;

				// Destination country/region code, e.g. "IN" or "US".
				$this->shippingDestination = ! empty( $zone['zone_locations'] )
					? $zone['zone_locations'][0]->code
					: null;

				$this->deliveryTime = $default_delivery_time;

				return; // use first active method found
			}
		}
	}


	/**
	 * JSON-LD Schema Builder
	 */
	public function vserpb_getSchema() {

		$schema = [
			'@type'         => 'Offer',
			'price'         => $this->price,
			'priceCurrency' => $this->priceCurrency,
			'availability'  => $this->availability,
			'url'           => $this->url,
			'seller'        => ( new Vserpb_Organization( $this->seller, '' ) )->vserpb_getSchema(),
			'priceValidUntil'=> $this->priceValidUntil,
			'validFrom'     => $this->validFrom,
		];

		// --- ADD FULL SHIPPING SCHEMA SECTION ---
		if ( $this->weight || array_filter($this->dimensions) ) {

		$schema['shippingDetails'] = [
				'@type' => 'OfferShippingDetails',
				'Weight' => !empty($this->weight) ? [
					'@type' => 'QuantitativeValue',
					'value' => $this->weight,
					'unitCode' => 'KGM' // kg unit code
				] : null,
				'height' => !empty($this->dimensions['height']) ? [
					'@type' => 'QuantitativeValue',
					'value' => $this->dimensions['height'],
					'unitCode' => 'CMT' // cm unit code
				] : null,
				'width' => !empty($this->dimensions['width']) ? [
					'@type' => 'QuantitativeValue',
					'value' => $this->dimensions['width'],
					'unitCode' => 'CMT'
				] : null,
				'depth' => !empty($this->dimensions['length']) ? [
					'@type' => 'QuantitativeValue',
					'value' => $this->dimensions['length'],
					'unitCode' => 'CMT'
				] : null,
				'deliveryTime'        => $this->deliveryTime ?? null,
				'shippingRate'        => $this->shippingRate ?? null,
				'shippingDestination' => $this->shippingDestination ?? null
			];

		}

		return $schema;
	}
}
