<?php
namespace SabaiApps\Directories\Component\DirectoryPro\EntityFeature;

use SabaiApps\Directories\Component\Entity\Model\Bundle;
use SabaiApps\Directories\Component\Entity\Type\IEntity;
use SabaiApps\Directories\Component\Entity\Feature\AbstractFeature;

class PhotosEntityFeature extends AbstractFeature {

	protected function _entityFeatureInfo() {
		return array(
			'label'            => __( 'Photo Settings', 'directories-pro' ),
			'weight'           => 9,
			'default_settings' => array(
				'unlimited' => false,
				'num'       => 5,
			),
		);
	}

	public function entityFeatureSupports( Bundle $bundle, $planType = 'base' ) {
		return $bundle->type === 'directory__listing';
	}

	public function entityFeatureSettingsForm( Bundle $bundle, array $settings, array $parents = array() ) {
		return array(
			'unlimited' => array(
				'#title'         => $this->_maxNumAllowedLabel( __( 'Photos', 'directories-pro' ) ),
				'#on_label'      => __( 'Unlimited', 'directories-pro' ),
				'#type'          => 'checkbox',
				'#switch'        => false,
				'#default_value' => ! empty( $settings['unlimited'] ),
				'#horizontal'    => true,
			),
			'num'       => array(
				'#type'          => 'slider',
				'#default_value' => $settings['num'],
				'#integer'       => true,
				'#min_value'     => 0,
				'#max_value'     => 50,
				'#states'        => array(
					'invisible' => array(
						sprintf( 'input[name="%s[unlimited][]"]', $this->_application->Form_Form_fieldName( $parents ) ) => array(
							'type'  => 'checked',
							'value' => true,
						),
					),
				),
				'#horizontal'    => true,
			),
		);
	}

	public function entityFeatureOnEntityForm( Bundle $bundle, array $settings, array &$form, ?IEntity $entity = null, $isAdmin = false ) {
		if ( $isAdmin && $this->_application->IsAdministrator() ) {
			return; // do not restrict for administrators
		}

		if ( empty( $settings['unlimited'] ) ) {
			$limit = $settings['num'];

			if ( empty( $limit ) ) {
				// No photos allowed
				unset( $form['directory_photos'] );
				return;
			}

			if ( empty( $form['directory_photos']['#max_num_files'] )
				|| $limit < $form['directory_photos']['#max_num_files']
			) {
				$form['directory_photos']['#max_num_files'] = $limit;
			}
		} else {
			$form['directory_photos']['#max_num_files'] = 0;
		}
	}
}
