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

use SabaiApps\Directories\Component\Entity\Type\IEntity;
use SabaiApps\Directories\Component\Field;
use SabaiApps\Directories\Component\Field\Type\ConditionableDateTrait;
use SabaiApps\Directories\Component\Field\Type\QueryableDateTrait;

class ExpiresFieldType extends Field\Type\AbstractValueType implements
	Field\Type\ISortable,
	Field\Type\ISchemable,
	Field\Type\IOpenGraph,
	Field\Type\IColumnable,
	Field\Type\IQueryable,
	Field\Type\IConditionable {

	use QueryableDateTrait;
	use ConditionableDateTrait;

	protected function _fieldTypeInfo() {
		return array(
			'label'       => __( 'Exp. Date', 'directories-pro' ),
			'admin_only'  => true,
			'icon'        => 'far fa-clock',
			'schema_type' => 'date',
		);
	}

	public function fieldSortableOptions( Field\IField $field ) {
		return array(
			array( 'label' => $label = __( 'Exp. Date', 'directories-pro' ) ),
			array(
				'args'  => array( 'desc' ),
				'label' => sprintf( __( '%s (desc)', 'directories-pro' ), $label ),
			),
		);
	}

	public function fieldSortableSort( Field\Query $query, $fieldName, ?array $args = null ) {
		$query->sortByField( $fieldName, 'EMPTY_LAST', 'value' ); // moves NULL or 0 to last in order
		$query->sortByField(
			$fieldName,
			isset( $args ) && $args[0] === 'desc' ? 'DESC' : 'ASC',
			'value'
		);
	}

	public function fieldSchemaProperties( Field\IField $field ) {
		return array( 'expires' );
	}

	public function fieldSchemaRenderProperty( Field\IField $field, $property, IEntity $entity ) {
		return array( date( 'Y-m-d', $entity->getTimestamp() ) );
	}

	public function fieldOpenGraphProperties() {
		return array( 'article:expiration_time' );
	}

	public function fieldOpenGraphRenderProperty( Field\IField $field, $property, IEntity $entity ) {
		return array( date( 'c', $entity->getTimestamp() ) );
	}

	public function fieldColumnableInfo( Field\IField $field ) {
		return array(
			'' => array(
				'label'  => $field->getFieldLabel(),
				'sortby' => 'value',
				'hidden' => true,
			),
		);
	}

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

		return $this->_application->System_Date( $values[0], true );
	}
}
