<?php

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

/**
 * Class Wiaas_Package_Pricing
 */
class Wiaas_Admin_Package_Pricing {

	public static function init() {

		add_action( 'admin_menu', array(__CLASS__, 'add_package_pricing_editor_page') );

		add_action( 'wp_ajax_create_empty_pricing_rule', array(__CLASS__, 'create_empty_pricing_rule') );

		add_action('woocommerce_product_options_general_product_data', array(__CLASS__, 'render_edit_prices_link'));

		add_filter('woocommerce_bundle_price_html',  array( __CLASS__, 'get_package_price_html' ), 10, 2);
	}

	public static function get_package_price_html($price_html, $package) {
		$bundled_items = $package->get_bundled_items();

		$recurring_price = 0;

		foreach ($bundled_items as $bundled_item) {
			$product = $bundled_item->product;
			$product_price = Wiaas_Product_Pricing::get_product_price($product);
			if ($product_price['is_recurring']) {
				$recurring_price += $product_price['price'] * $bundled_item->get_quantity();
			}
		}

		$edit_link = admin_url( 'edit.php?post_type=product&page=wiaas-package_price_editor&id=' . absint( $package->get_id() ) );

		$price_html = 'Fixed: ' . $price_html . ' and ' . $recurring_price . ' / month' .
                      ' <br> <a class="button button-link" href="' .  esc_url($edit_link) .'" target="_blank">Edit price<a>';

		return $price_html;
	}

	public static function render_edit_prices_link() {
		global $post;

		$edit_link = admin_url( 'edit.php?post_type=product&page=wiaas-package_price_editor&id=' . absint( $post->ID ) );

		?>
		<div class="options_group hide_if_simple hide_if_wiaastemplate">
			<p>
				<a href="<?php echo esc_url($edit_link) ?>" target="_blank">
					<span>Edit prices</span>
				</a>
			</p>

		</div>
		<?php
	}

	public static function add_package_pricing_editor_page() {

		add_submenu_page(
			'edit.php?post_type=product',
			__( 'Edit prices', 'wiaas' ),
			null,
			'create_products',
			'wiaas-package_price_editor',
			array(__CLASS__, 'package_pricing_editor')
		);
	}

	/**
	 * Creates and renders new empty package pricing rule
	 */
	public static function create_empty_pricing_rule() {
		$pay_type = $_POST['pay_type'];
		$pricing_rules                        = array();
		$pricing_rules[ $pay_type ]          = Wiaas_Package_Pricing::get_empty_pricing_rule();

		require 'views/html-package-pricing-rules-list.php';

		die();
	}

	/**
	 * Renderes wiaas pricing tab content for package
	 */
	public static function package_pricing_editor() {

		$plugin_url = untrailingslashit( plugins_url( '/', WIAAS_FILE ) );
		wp_enqueue_script('admin_package_edit_prices', $plugin_url . '/assets/js/wiaas-admin-package-edit-prices.js');

		$package_id = absint($_GET['id']);
		$package           = wc_get_product( $package_id );

		if (empty($package) || $package->get_type() !== 'bundle') {
			return;
		}

		// save prices
		if (! empty($_POST['wiaas_save_package_prices_nonce']) &&
		    wp_verify_nonce($_POST['wiaas_save_package_prices_nonce'], 'wiaas_save_package_prices')) {
			self::_save_posted_package_prices($package_id);
		}

		$pricing_rules = Wiaas_Package_Pricing::get_package_prices($package);
		$commission = Wiaas_Package_Pricing::get_package_pricing_commission($package);
		$max_cost_margin = Wiaas_Package_Pricing::get_package_max_cost_margin($package);

		// collect package bundle items pricing info to display
		$bundled_items = $package->get_bundled_items();
		$bundled_items_per_category = array();

		foreach ($bundled_items as $bundled_item) {
			$product = $bundled_item->product;
			$product_cat = Wiaas_Product_Category::get_category($product);

			if ($product_cat === 'hardware' || $product_cat === 'software') {
				$product_cat = 'product';
			}

			$bundled_items_per_category[$product_cat] ?: array( );

			$bundled_items_per_category[$product_cat][] = $bundled_item;


		}

		include 'views/html-package-pricing-page.php';
	}


	// PRIVATE HELPERS

	/**
	 * Save posted package pricing information
	 *
	 * @param int $package_id
	 */
	private static function _save_posted_package_prices($package_id) {
		$commission = wp_unslash($_POST['wiaas_pricing_rules_commision']);
		$max_cost_margin = wp_unslash($_POST['wiaas_max_cost_margin']);
		$pricing_rules = array();

		$posted_pricing_rules = isset($_POST['wiaas_pricing_rules']) ? wp_unslash($_POST['wiaas_pricing_rules']) : array();

		foreach ($posted_pricing_rules as $rule_type => $posted_prices) {

			$posted_prices = wp_unslash($posted_prices);
			$prices = array();

			foreach ($posted_prices as $posted_price_type => $posted_price) {
				$prices[sanitize_key($posted_price_type)] = wp_unslash($posted_price);
			}

			$pricing_rules[sanitize_key($rule_type)] = $prices;
		}

		Wiaas_Package_Pricing::set_package_prices(
			wc_get_product( $package_id ),
			$pricing_rules,
			$commission,
			$max_cost_margin);
	}
}

Wiaas_Admin_Package_Pricing::init();