<?php
namespace BricksUltimate\Elements;

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

use BricksUltimate\{Helpers,WooCommerce};

class WooStockIndicator extends \Bricks\Element {
	public $category = 'ultimate';
	public $name 	= 'bu-stock-indicator';
	public $icon 	= 'ti-line-double';

	// Return localized element label
	public function get_label() {
		return esc_html__( '(BU)Stock Indicator', 'bricksultimate' );
	}

	public function set_controls() {

		$this->controls['hideOnLowStock'] = [
			'label'       => esc_html__( 'Disable if low stock', 'bricksultimate' ),
			'type'        => 'checkbox',
		];

		$this->controls['barHeight'] = [
			'label'       => esc_html__( 'Height', 'bricksultimate' ),
			'type'        => 'number',
			'units'       => true,
			'placeholder' => 7,
			'css'         => [
				[
					'property' => 'height',
				],
				[
					'property' => 'max-height',
				]
			],
		];

		$this->controls['barColor'] = [
			'label' => esc_html__( 'Default color', 'bricksultimate' ),
			'type'  => 'color',
			'css'   => [
				[
					'property' => 'background-color',
				],
			],
		];

		$this->controls['activeColor'] = [
			'label' => esc_html__( 'Active color', 'max-addons' ),
			'type'  => 'color',
			'css'   => [
				[
					'property' => 'background-color',
					'selector' => '.indicator-res',
				],
			],
		];

		$this->controls['barBorder'] = [
			'label' => esc_html__( 'Bar border', 'max-addons' ),
			'type'  => 'border',
			'css'   => [
				[
					'property' => 'border',
				],
			],
			'exclude' => [ 'box-shadow', 'border-radius' ]
		];

		$this->controls['container'] = [
			'label' => esc_html__( 'Context selector', 'bricksultimate' ),
			'description' => esc_html__( 'Required for the variable products. It will work on the single product page', 'bricksultimate' ),
			'type' => 'text',
		];
	}

	private function managing_stock( $product ) {
		if ( ! $product->is_type('variable') ) {
			return $product->managing_stock();
		}

		if ( $product->is_type('variable') ) {
			foreach ( $product->get_visible_children() as $key => $variation_id ) {
				$variation = wc_get_product( $variation_id );
				if( $variation->managing_stock() )
					return true;
			}
		}

		return false;
	}

	// Render element HTML
	public function render() {
		global $product;

		$product = wc_get_product( $this->post_id );

		if ( empty( $product ) ) {
			return $this->render_element_placeholder(
				[
					'title'       => esc_html__( 'For better preview select content to show.', 'bricks' ),
					'description' => esc_html__( 'Go to: Settings > Template Settings > Populate Content', 'bricks' ),
				]
			);
		}

		if ( ! $this->managing_stock( $product ) ) {
			return;
		}

		if ( ! empty( $settings['hideOnLowStock'] ) && WooCommerce::has_low_stock( $product ) ) {
			return;
		}

		$sold = $product->get_total_sales();
		$current_stock = ( $sold ? $sold : 0 ) + WooCommerce::get_stock_quantity( $product );

		$barWidth = ( $sold > 0 ) ? round( $sold / $current_stock * 100 ) : 0;

		if ( ! \Bricks\Query::is_looping() ) {
			$this->set_attribute('_root', 'class', ['single-product-bustock'] );
			$this->set_attribute('_root', 'data-total-sold', $sold );
			$this->set_attribute('_root', 'data-available-stock', WooCommerce::get_stock_quantity( $product ) );
		}

		$settings = $this->settings;
		if( ! empty( $settings['container'] ) ) {
			$this->set_attribute('_root', 'data-selector', $settings['container'] );
		}

		echo "<{$this->tag} {$this->render_attributes('_root')}>";
		?>
			<div class="indicator-res" style="width: <?php echo $barWidth; ?>%;"></div>
		<?php

		if ( $product->is_type('variable') && ! \Bricks\Query::is_looping() ) {
			foreach ( $product->get_visible_children() as $key => $variation_id ) {
				$variation = wc_get_product( $variation_id );
				if( $variation->managing_stock() ) {
					$sold = $variation->get_total_sales(); 

					if( $sold <= 0 )
						$sold = $this->count_stock_from_variation($variation_id);

					$current_stock = ( $sold ? $sold : 0 ) + WooCommerce::get_stock_quantity( $variation );

					$barWidth = ( $sold > 0 ) ? round( $sold / $current_stock * 100 ) : 0;

					printf( 
						'<div class="indicator-res variation-stock screen-reader-text variation-%d" data-total-sold="%d" data-available-stock="%d" style="width: %s;"></div>', 
						$variation_id, 
						$sold, 
						$variation->get_stock_quantity(), 
						$barWidth . "%"
					);
				}
			}
		}

		echo "</{$this->tag}>";
	}

	/**
	 * credit: https://stackoverflow.com/questions/50285451/count-number-of-orders-for-a-variation-in-woocommerce
	 */
	private function count_stock_from_variation($variation_id){
		global $wpdb;

		// DEFINE below your orders statuses
		$statuses = array('wc-completed', 'wc-processing', 'wc-hold');

		$statuses = implode("','", $statuses);

		return $wpdb->get_var("
			SELECT count(p.ID) FROM {$wpdb->prefix}woocommerce_order_items AS woi
			JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS woim ON woi.order_item_id = woim.order_item_id
			JOIN {$wpdb->prefix}posts AS p ON woi.order_id = p.ID
			WHERE p.post_type = 'shop_order' AND p.post_status IN ('$statuses')
			AND woim.meta_key LIKE '_variation_id' AND woim.meta_value = $variation_id
		");
	}

	public static function render_builder() { ?>
		<script type="text/x-template" id="tmpl-bricks-element-bu-stock-indicator">
			<component :is="'div'">
				<div class="indicator-res" style="width: 45%;"></div>
			</component>
		</script>
	<?php
	}
}