<?php

class Wiaas_Cart_API {
	/**
	 * Endpoint namespace.
	 *
	 * @var string
	 */
	private static $namespace = 'wiaas/cart';

	public static function register_routes() {
		register_rest_route( self::$namespace, 'count', array(
			'methods' => 'GET',
			'callback' => array(__CLASS__, 'get_cart_count'),
			'permission_callback' => array( __CLASS__, 'permission_check' ),
		) );

		register_rest_route( self::$namespace, 'items', array(
			'methods' => 'GET',
			'callback' => array(__CLASS__, 'get_cart_items'),
			'permission_callback' => array( __CLASS__, 'permission_check' ),
		) );

		register_rest_route( self::$namespace, 'documents', array(
			'methods' => 'GET',
			'callback' => array(__CLASS__, 'get_cart_documents'),
			'permission_callback' => array( __CLASS__, 'permission_check' ),
		) );

		register_rest_route( self::$namespace, 'add', array(
			'methods' => 'post',
			'callback' => array(__CLASS__, 'add_package_to_cart'),
			'permission_callback' => array( __CLASS__, 'permission_check' ),
		) );

		register_rest_route( self::$namespace, 'remove', array(
			'methods' => 'post',
			'callback' => array(__CLASS__, 'remove_package_from_cart'),
			'permission_callback' => array( __CLASS__, 'permission_check' ),
		) );

		register_rest_route( self::$namespace, 'update-quantity', array(
			'methods' => 'post',
			'callback' => array(__CLASS__, 'update_package_quantity'),
			'permission_callback' => array( __CLASS__, 'permission_check' ),
		) );

		register_rest_route( self::$namespace, 'place-order', array(
			'methods' => 'post',
			'callback' => array(__CLASS__, 'place_order'),
			'permission_callback' => array( __CLASS__, 'permission_check' ),
		) );
	}

	public static function permission_check() {
		if (!is_user_logged_in()) {
			return new WP_Error( 'wiaas_rest_authorization_required',
				__( 'Sorry, only authorized users can access!', 'wiaas' ),
				array( 'status' => rest_authorization_required_code() ) );
		}
		return true;
	}

	/**
	 * Get cart count
	 * TODO: This implementation is temporary to enable flow trough basic checkout process and should be changed
	 * @return WP_REST_Response
	 */
	public static function get_cart_count() {
		$items = WC()->cart->get_cart_contents();

		$count = 0;

		foreach ($items as $key => $item) {
			if (isset($item['_wiaas_standard_package'])) {
				$count++;
			}
		}

		return new WP_REST_Response(array(
			'count' => $count,
		));
	}

	/**
	 * Get cart items
	 * TODO: This implementation is temporary to enable flow trough basic checkout process and should be changed
	 * @return WP_REST_Response
	 */
	public static function get_cart_items() {
		$items = WC()->cart->get_cart_contents();

		$result = array();

		foreach ($items as $key => $item) {
			if (!isset($item['_wiaas_standard_package'])) {
				continue;
			}

			$package = wc_get_product($item['product_id']);

			// Retrieve package addons
			$addon_cart_items = wiaas_get_cart_item_addons($item);
			$additional_packages = array();

			foreach ($addon_cart_items as $addon_cart_item) {
				$additional_package = wc_get_product($addon_cart_item['product_id']);
				$additional_packages[] = array(
					'idAdditionalPackage' => $additional_package->get_id(),
					'packageName' => $additional_package->get_title(),
					'prices' => array(
						'fixedExtra' => $addon_cart_item['_wiaas_payment']['fixed_extra'],
						'recurrentExtra' => $addon_cart_item['_wiaas_payment']['recurrent_extra'],
						'servicesExtra' => $addon_cart_item['_wiaas_payment']['services_extra'],
					)
				);
			}

			// Retrieve package options
			$option_cart_items = wiaas_get_cart_item_options($item);
			$package_options = array();
			foreach ($option_cart_items as $option_cart_item) {
				$option_package = wc_get_product($option_cart_item['product_id']);
				$package_options[] = array(
					'idOptionPackage' => $option_package->get_id(),
					'groupName' => $option_cart_item['_wiaas_option_group_name'],
					'packageName' => $option_package->get_title(),
					'prices' => array(
						'fixedExtra' => $option_cart_item['_wiaas_payment']['fixed_extra'],
						'recurrentExtra' => $option_cart_item['_wiaas_payment']['recurrent_extra'],
						'servicesExtra' => $option_cart_item['_wiaas_payment']['services_extra'],
					)
				);
			}

			$totalPrices = Wiaas_Cart::get_cart_item_total($item);

			$country = Wiaas_Countries::get_package_country($package);


			$result[] = array(
				'idPackage' => $item['product_id'],
				'key' => $item['key'],
				'packageName' => $package->get_title(),
				'additionalPackages' => $additional_packages,
				'areAdditionalAvailable' => true,
				'areOptionsAvailable' => true,
				'bids' => array(),
				'commercialLead' => 'Coor Service Management',
				'country' => array(
					'currency' => $country['currency']
				),
				'options' => $package_options,
				'quantity' => $item['quantity'],

				'idPayType' => $item['_wiaas_payment']['id'],
				'payType' => $item['_wiaas_payment']['payment_type'],
 				'periodUnit' => $item['_wiaas_payment']['period_unit'],
 				'idPrice' => $item['_wiaas_payment']['id'],
				'fixedPrice' => $item['_wiaas_payment']['fixed_extra'],
				'recurrentPrice' => $item['_wiaas_payment']['recurrent_extra'],
				'servicesPrice' => $item['_wiaas_payment']['services_extra'],

				'totalPrices' => array(
					'fixedPrice' => $totalPrices['fixed_extra'],
					'recurrentPrice' => $totalPrices['recurrent_extra'],
					'servicesPrice' => $totalPrices['services_extra'],
				),

				'status' => 'available',
				'idCommercialLead' => 14,
			);
		}
		return new WP_REST_Response(
			array(
				'cartItems' => $result,
				'items' => $items,
				'totalPrice' => ''
			)
		);
	}

	/**
	 * Get cart documents
	 * TODO: This implementation is temporary to enable flow trough basic checkout process and should be changed
	 * @return WP_REST_Response
	 */
	public static function get_cart_documents() {
		return new WP_REST_Response(array(
			'areFilesUploaded' => true,
			'templates' => array(),
			'uploaded' => array()
		));
	}

	/**
	 * Add package to cart
	 * TODO: This implementation is temporary to enable flow trough basic checkout process and should be changed
	 * @return WP_REST_Response
	 * @throws Exception
	 */
	public static function add_package_to_cart() {
		$package_id = $_POST['package_id'];

		$success = WC()->cart->add_to_cart($package_id, 1, 0, array(), array(
			'_wiaas_standard_package' => true
		));

		if ($success) {
			return new WP_REST_Response(array(
				'messages' => array(
					array(
						'code' => 'success',
						'message' => 'PACKAGE_ADDED'
					)
				)
			));
		}

		return new WP_REST_Response(array(
			'messages' => array(
				array(
					'code' => 'error',
					'message' => 'PACKAGE_ALREADY_IN_CART'
				)
			)
		));
	}

	/*
	 * Remove package from cart
	 * TODO: This implementation is temporary to enable flow trough basic checkout process and should be changed
	 */
	public static function remove_package_from_cart() {
		$package_cart_key = $_POST['package_item_key'];

		$success = WC()->cart->remove_cart_item($package_cart_key);

		if ($success) {
			return new WP_REST_Response(array(
				'messages' => array(
					array(
						'code' => 'success',
						'message' => 'PACKAGE_REMOVED_FROM_CART'
					)
				)
			));
		}

		return new WP_REST_Response(array(
			'messages' => array(
				array(
					'code' => 'error',
					'message' => 'INVALID_PACKAGE_FOR_REMOVE'
				)
			)
		));
	}

	/**
	 * Update package quantity in cart
	 * TODO: This implementation is temporary to enable flow trough basic checkout process and should be changed
	 * @return WP_REST_Response
	 */
	public static function update_package_quantity() {
		$package_item_key = $_POST['package_item_key'];
		$new_quantity = $_POST['quantity'];

		$success = WC()->cart->set_quantity($package_item_key, $new_quantity, true);

		if ($success) {
			return new WP_REST_Response(array(
				'messages' => array(
					array(
						'code' => 'success',
						'message' => 'QUANTITY_UPDATED'
					)
				)
			));
		}

		return new WP_REST_Response(array(
			'messages' => array(
				array(
					'code' => 'error',
					'message' => 'QUANTITY_NOT_UPDATED'
				)
			)
		));
	}

	/**
	 * Placing order as part of checkout process
	 * TODO: This implementation is temporary to enable flow trough basic checkout process and should be changed
	 * @return WP_REST_Response
	 * @throws Exception
	 */
	public static function place_order() {

		$details = $_POST['details'];
		$vat_code = $_POST['vat'];
		$company_name = $_POST['companyName'];
		$delivery_address = $_POST['delivery'];
		$billing_address = $_POST['billing'];

		$order_id = WC()->checkout()->create_order(array());
		$order = wc_get_order( $order_id );

		// set order currency
		$line_items = $order->get_items();
		foreach ($line_items as $line_item) {
			if (isset($line_item['wiaas_currency'])) {
				$order->set_currency($line_item['wiaas_currency']);
				break;
			}
		}

		$order->set_shipping_city($delivery_address['city']);
		$order->set_shipping_country($delivery_address['countryName']);
		$order->set_shipping_address_1($delivery_address['detailedAddress']);
		$order->set_shipping_postcode($delivery_address['zipCode']);

		$order->set_billing_city($billing_address['city']);
		$order->set_billing_country($billing_address['countryName']);
		$order->set_billing_address_1($billing_address['detailedAddress']);
		$order->set_billing_postcode($billing_address['zipCode']);
		$order->set_billing_first_name($billing_address['firstName']);
		$order->set_billing_last_name($billing_address['lastName']);

		$order->payment_complete();


		add_post_meta($order_id, '_wiaas_vat_code', $vat_code);
		add_post_meta($order_id, '_wiaas_company_name', $company_name);
		add_post_meta($order_id, '_wiaas_project_id', $details['idProject']);
		add_post_meta($order_id, '_wiaas_reference', $details['reference']);
		add_post_meta($order_id, '_wiaas_tender', $details['tender']);

		// $order->get_li

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

		return new WP_REST_Response(array(
			'messages' => array(
				array(
					'code' => 'success',
					'message' => 'ORDER_PLACED'
				)
			),
			'details' => $details
		));
	}
}