<?php

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

/**
 * Class Wiaas_Package_Pricing
 */
class Wiaas_Package_Pricing {

	/**
	 * Available pay types for wiaas packages
	 * @var array
	 */
	private static $pay_types = array(
		'purchase' => array(
			'title' => 'Purchase',
			'package_pay_period' => 0,
			'services_contract_period' => 0,
			'max_contract_period' => 36,
			'period_unit' => 'month',
			'labe'
		),
		'purchase_24' => array(
			'title' => 'Purchase with 24M commitment',
			'package_pay_period' => 0,
			'services_contract_period' => 24,
			'max_contract_period' => 36,
			'period_unit' => 'month'
		),
		'managed_36' => array(
			'title' => 'Managed service 36M rent',
			'package_pay_period' => 36,
			'services_contract_period'=> 36,
			'max_contract_period' => 36,
			'period_unit' => 'month'
		)
	);

	/**
	 * Payment fields for pricing rules
	 * @var array
	 */
	private static $payment_fields = array(
		'minimal_fixed_price' => 0,
		'principal_amount' => 0,
		'minimal_services_price' => 0
	);

	public static function init() {
	
		add_action('woocommerce_update_product', array(__CLASS__, 'on_product_update' ), 10, 1 );
	}

	/**
	 * Get configuration for available payment types
	 * @return array
	 */
	public static function get_available_pay_types() {
		return self::$pay_types;
	}

	/**
	 * Get empty payment rule with initialized fields to default values
	 * @return array
	 */
	public static function get_empty_pricing_rule() {
		return self::$payment_fields;
	}

	/**
	 * Retrieve configured payment prices for package
	 * @param $package
	 *
	 * @return array
	 */
	public static function get_package_prices($package) {
		return self::_get_package_prices($package);
	}

	public static function get_package_pricing_commission($package) {
		return self::_get_package_pricing_commision($package);
	}

	public static function get_package_max_cost_margin($package){
		return self::_get_package_max_cost_margin($package);
	}

	/**
	 * Persist payment prices configuration for package
	 * @param $package
	 * @param $pricing_rules
	 */
	public static function set_package_prices($package, $pricing_rules, $commision, $max_cost_margin) {
		if ( isset( $pricing_rules ) ) {
			$package->update_meta_data( '_wiaas_pricing_rules', $pricing_rules );
			$package->update_meta_data('_package_pricing_commision', $commision, true);
			$package->update_meta_data('_package_max_cost_margin', $max_cost_margin, true);
		} else {
			$package->delete_meta_data( '_wiaas_pricing_rules' );
		}
		$package->save_meta_data();

		self::_validate_package($package);
	}

	/**
	 *  Executes when woocommerce product is updated
	 */
	public static function on_product_update($product_id) {
		$product = wc_get_product($product_id);

		if ($product->get_type() === WC_Product_Simple::get_type()){
			$product_price = Wiaas_Product_Pricing::get_product_price($product);

			$packages_containing_updated_product = wc_pb_get_bundled_product_map( $product );

			foreach($packages_containing_updated_product as $index => $package_id){
				$package = new WC_Product_Bundle($package_id);
				self::_validate_package($package);
			}	
		}else if ($product->get_type() === WC_Product_Bundle::get_type()){
			self::_validate_package($product);
		}
	}

	// PRIVATE

	private static function _get_package_prices($package) {
		$pricing_rules = $package->get_meta( '_wiaas_pricing_rules' );

		if (empty($pricing_rules)) {
			return null;
		}

		$commision = self::_get_package_pricing_commision($package);

		$prices = array();
		foreach ($pricing_rules as $type => $pricing_rule) {

			$pay_type = self::$pay_types[$type];

			$prices[$type] = array(
				'id' => $type,
				'payment_type' => $pay_type['title'],
				'max_contract_period' => $pay_type['max_contract_period'],
				'package_pay_period' => floatval($pay_type['package_pay_period']),
				'period_unit' => $pay_type['period_unit'],
				'services_contract_period' => $pay_type['services_contract_period'],
				'commision_split' => $commision / 100.00,

				'minimal_fixed_price' => floatval($pricing_rule['minimal_fixed_price']),
				'principal_amount' => floatval($pricing_rule['principal_amount']),
				'minimal_services_price' => floatval($pricing_rule['minimal_services_price']),
			);

            $minimal_recurrent_price = $prices[$type]['minimal_services_price'];
            if ($prices[$type]['principal_amount'] > 0 && $prices[$type]['package_pay_period'] > 0) {
                $minimal_recurrent_price += wiaas_PMT(
                    Wiaas_Pricing::INTEREST_RATE,
                    $prices[$type]['package_pay_period'],
                    $prices[$type]['principal_amount']);
            }

            $prices[$type]['minimal_recurrent_price'] = round($minimal_recurrent_price);
		}

		return $prices;
	}

	private static function _get_package_pricing_commision($package) {
		$commision = $package->get_meta( '_package_pricing_commision', true);

		if (!isset($commision) || $commision === '') {
			return 50.00;
		}

		return (float) $commision;
	}

	private static function _get_package_max_cost_margin($package) {
		$max_cost_margin = $package->get_meta( '_package_max_cost_margin', true);

		if (!isset($max_cost_margin) || $max_cost_margin === '') {
			return 0;
		}

		return (float) $max_cost_margin;
	}

	private static function _validate_package($package){
		$package_total_cost = Wiaas_Pricing::get_package_total_cost($package);
		$package_max_cost_margin = Wiaas_Package_Pricing::get_package_max_cost_margin($package);
		if (($package_max_cost_margin != 0) && ($package_total_cost > $package_max_cost_margin)){
			Wiaas_Package_Status::set_package_status($package->get_id(), Wiaas_Package_Status::INVALID_MARGIN);
		}else{
			Wiaas_Package_Status::set_package_status($package->get_id(), Wiaas_Package_Status::AVAILABLE);
		}
	}
}

Wiaas_Package_Pricing::init();