<?php
namespace SabaiApps\Directories\Component\PaymentGateway\FieldType;

use SabaiApps\Directories\Component\Field\IField;
use SabaiApps\Directories\Application;
use SabaiApps\Directories\Component\Entity\Type\IEntity;

class SubscriptionFieldType extends AbstractOrderFieldType {

	protected $_persistentValues = array(
		'number'             => '',
		'status'             => 'active',
		'gateway'            => 'stripe',
		'next_payment_at'    => 0,
		'parent_entity_id'   => 0,
		'parent_entity_type' => '',
	);

	public function __construct( Application $application, $name ) {
		parent::__construct( $application, $name, __( 'Subscription', 'directories-pro' ) );
	}

	public function fieldTypeSchema( array $settings = array() ) {
		$schema                               = parent::fieldTypeSchema( $settings );
		$schema['columns']['next_payment_at'] = array(
			'type'     => Application::COLUMN_INTEGER,
			'notnull'  => true,
			'unsigned' => true,
			'was'      => 'next_payment_at',
			'default'  => 0,
			'length'   => 10,
		);
		$schema['indexes']['next_payment_at'] = array(
			'fields' => array( 'next_payment_at' => array( 'sorting' => 'ascending' ) ),
			'was'    => 'next_payment_at',
		);
		return $schema;
	}

	public function fieldColumnableInfo( IField $field ) {
		$info                    = parent::fieldColumnableInfo( $field );
		$info['next_payment_at'] = array(
			'label'  => __( 'Next payment', 'directories-pro' ),
			'sortby' => 'next_payment_at',
		);
		return $info;
	}

	public function fieldColumnableColumn( IField $field, IEntity $entity, $column = '' ) {
		if ( $column === 'next_payment_at' ) {
			if ( ( ! $values = $entity->getFieldValue( $field->getFieldName() ) )
				|| $values[0]['status'] !== 'active'
				|| empty( $values[0]['next_payment_at'] )
				|| $values[0]['next_payment_at'] <= time()
			) {
				return;
			}

			return $this->_application->System_Date_datetime( $values[0]['next_payment_at'] );
		}
		return parent::fieldColumnableColumn( $field, $entity, $column );
	}

	protected function _getPaymentPlanTypes( $contentBundleName ) {
		return array( 'subscription' );
	}

	protected function _getStatuses() {
		return $this->_application->PaymentGateway_Subscription_statuses();
	}

	protected function _getStatusLabel( $status, $html = true, $badge = true ) {
		return $this->_application->PaymentGateway_Subscription_statusLabel( $status, $html, $badge );
	}
}
