<?php

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

/**
 * Class Wiaas_Package_Pricing
 */
class Wiaas_Admin_Package_Pricing {

	public static function init() {

		add_action( 'woocommerce_product_data_tabs', array( __CLASS__, 'package_data_tabs' ) );
		add_action( 'woocommerce_product_data_panels', array( __CLASS__, 'package_data_panel' ) );

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

		add_action( 'woocommerce_process_product_meta', array( __CLASS__, 'process_meta_box' ), 1, 2 );
	}

	/**
	 * 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();
	}

	/**
	 * Registers wiaas pricing tab for package data
	 * @param $tabs
	 *
	 * @return array
	 */
	public static function package_data_tabs($tabs) {
		$tabs[ 'bundled_packages_price' ] = array(
			'label'    => __( 'Pricing', 'wiaas' ),
			'target'   => 'wiaas_package_price',
			'class'    => array( 'show_if_bundle', 'bundled_package_tab' ),
			'priority' => 50
		);

		return $tabs;
	}

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

		global $post;
		$package           = wc_get_product( $post->ID );
		$pricing_rules = Wiaas_Package_Pricing::get_package_prices($package);
		$commission = Wiaas_Package_Pricing::get_package_pricing_commission($package);

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

	/**
	 * Saves posted package pricing rules
	 * @param $post_id
	 * @param $post
	 */
	public function process_meta_box( $post_id, $post ) {
		Wiaas_Package_Pricing::set_package_prices(
			wc_get_product( $post_id ),
			$_POST['wiaas_pricing_rules'],
			$_POST['wiaas_pricing_rules_commision']);
	}
}

Wiaas_Admin_Package_Pricing::init();