<?php
namespace SabaiApps\Directories\Component\WooCommerce;

use SabaiApps\Directories\Component\Payment\ISubscription;
use SabaiApps\Directories\Exception\RuntimeException;

class PaymentSubscription implements ISubscription {

	protected $_subscription, $_itemId, $_itemName, $_entityId, $_entityType;

	public function __construct( \WC_Subscription $subscription, $itemId, $itemName, $entityId, $entityType ) {
		$this->_subscription = $subscription;
		$this->_itemId       = $itemId;
		$this->_itemName     = $itemName;
		$this->_entityId     = $entityId;
		$this->_entityType   = $entityType;
	}

	public function getSubscription() {
		return $this->_subscription;
	}

	public function paymentSubscriptionId() {
		return $this->_subscription->get_id();
	}

	public function paymentSubscriptionNumber() {
		return '#' . $this->_subscription->get_id();
	}

	public function paymentSubscriptionName() {
		return $this->_itemName;
	}

	public function paymentSubscriptionStatus() {
		$status = $this->_subscription->get_status();
		$name   = wcs_get_subscription_status_name( $status );
		switch ( $status ) {
			case 'active':
				return array( $name, 'success' );
			case 'cancelled':
			case 'expired':
				return array( $name, 'danger' );
			case 'pending':
			case 'pending-cancel':
			case 'on-hold':
				return array( $name, 'warning' );
			default:
				return $name;
		}
	}

	public function paymentSubscriptionTotalHtml() {
		$price = $this->_subscription->get_item( $this->_itemId )->get_total();
		return wc_price( $price );
	}

	public function paymentSubscriptionNextPaymentHtml() {
		return $this->_subscription->get_date_to_display();
	}

	public function paymentSubscriptionAdminUrl() {
		return get_edit_post_link( $this->_subscription->get_id() );
	}

	public function paymentSubscriptionUserId() {
		return $this->_subscription->get_user_id();
	}

	public function paymentSubscriptionIsActive() {
		return $this->_subscription->get_status() === 'active';
	}

	public function paymentSubscriptionEntityId() {
		return $this->_entityId;
	}

	public function paymentSubscriptionEntityType() {
		return $this->_entityType;
	}

	public function paymentSubscriptionPlan() {
		$order_items = $this->_subscription->get_items( 'line_item' );
		if ( ! isset( $order_items[ $this->_itemId ] )
			|| ( ! $product = $order_items[ $this->_itemId ]->get_product() )
			|| ! $product instanceof IProduct
		) {
			throw new RuntimeException( 'Order item does note exist or invalid (order item ID: ' . $this->_itemId . ')' );
		}
		return new PaymentPlan( $product );
	}
}
