<?php

class Wiaas_Checkout {

	public static function init(){
		add_action( 'woocommerce_check_cart_items', array(__CLASS__, 'validate_wiaas_packages'));
	}

	public static function validate_wiaas_packages(){
		//check if any package became invalid
		$items = WC()->cart->get_cart();
		foreach($items as $item) { 
			$item_id =  $item['data']->get_id();
			if (wc_pb_is_bundle_container_cart_item($item) && 
				(Wiaas_Package_Status::get_package_status($item_id) !== Wiaas_Package_Status::AVAILABLE)){
					wc_add_notice( 'Package ' . $item['data']->get_title() . ' cannot be purchased at the moment', 'error' );
					return false;
			}	
		}
	}

	/**
	 * Process the order checkout.
	 *
	 * @param array $data Posted data.
	 *
	 * @return bool
	 */
	public static function process_checkout($data) {
		try {

			wc_maybe_define_constant( 'WOOCOMMERCE_CHECKOUT', true );
			wc_set_time_limit( 0 );

			do_action( 'woocommerce_before_checkout_process' );

			// Check if cart empty before proceeding
			if (WC()->cart->is_empty()) {
				return false;
			}

			do_action( 'woocommerce_checkout_process' );

			// Validate cart items before proceeding
			WC()->checkout()->check_cart_items();

			// if something is wrong bail out
			if(wc_notice_count( 'error' ) > 0) {
				return false;
			}

			// try processing order
			$order_id = WC()->checkout()->create_order($data);
			$order = wc_get_order( $order_id );

			if ( is_wp_error( $order_id ) ) {
				throw new Exception( $order_id->get_error_message() );
			}

			if ( ! $order ) {
				throw new Exception( __( 'Unable to create order.', 'woocommerce' ) );
			}

			self::_add_wiaas_checkout_data($order, $data);

			do_action( 'woocommerce_checkout_order_processed', $order_id, array(), $order );

			$order->payment_complete();

			WC()->cart->empty_cart( true );

			return true;

		} catch (Exception $e) {
			wc_add_notice( $e->getMessage(), 'error' );
			return false;
		}
	}

	/**
	 * Add additional wiaas checkout info for order
	 * @param $order
	 * @param array $data
	 */
	private static function _add_wiaas_checkout_data($order, $data) {

		// save additional wiaas order info
		Wiaas_Order::set_order_vat($order->get_id(), $data['vat']);
		Wiaas_Order::set_order_company($order->get_id(), $data['company_name']);
		Wiaas_Order::set_order_reference($order->get_id(), $data['reference']);
		Wiaas_Order::set_order_tender($order->get_id(), $data['tender']);

		// add order to project
		if (isset($data['project_id'])) {
			Wiaas_Order_Project::set_project_for_order($order->get_id(), $data['project_id']);
		}

	}
}

Wiaas_Checkout::init();
