<?php
namespace SabaiApps\Directories\Component\Faker\Generator;

use SabaiApps\Directories\Component\Entity\Model\Bundle;
use SabaiApps\Directories\Component\Field\IField;
use SabaiApps\Directories\Component\Entity\Type\IEntity;

class PaymentGenerator extends AbstractGenerator {

	protected function _fakerGeneratorInfo() {
		$info = parent::_fakerGeneratorInfo();
		switch ( $this->_name ) {
			case 'payment_plan':
				$info += array(
					'add_probability'  => true,
					'default_settings' => array(
						'probability' => 70,
						'days'        => array(
							'min' => 0,
							'max' => 365,
						),
					),
				);
				break;
		}

		return $info;
	}

	public function fakerGeneratorSettingsForm( IField $field, array $settings, $mode, array $parents = array() ) {
		switch ( $this->_name ) {
			case 'payment_plan':
				$plans = $this->_application->Payment_Plans( $field->Bundle->name, 'base', true );
				foreach ( array_keys( $plans ) as $plan_id ) {
					$plans[ $plan_id ] = $plans[ $plan_id ]->paymentPlanTitle();
				}
				return array(
					'plans' => array(
						'#type'          => 'checkboxes',
						'#title'         => __( 'Payment Plans', 'directories-pro' ),
						'#options'       => $plans,
						'#default_value' => array_keys( $plans ),
					),
					'days'  => array(
						'#type'          => 'range',
						'#title'         => __( 'Duration', 'directories-pro' ),
						'#min_value'     => 0,
						'#max_value'     => 365,
						'#default_value' => $settings['days'],
						'#description'   => __( 'Select the range of possible durations for the field.', 'directories-pro' ),
					),
				);
		}
	}

	public function fakerGeneratorGenerate( IField $field, array $settings, array &$formStorage, ?IEntity $entity = null ) {
		switch ( $this->_name ) {
			case 'payment_plan':
				if ( empty( $settings['plans'] ) ) {
					return;
				}

				if ( empty( $settings['days']['min'] ) && empty( $settings['days']['max'] ) ) {
					$never_expires = true;
				}

				return array(
					array(
						'plan_id'    => $settings['plans'][ array_rand( $settings['plans'] ) ],
						'component'  => $this->_application->getComponent( 'Payment' )->getPaymentComponent( false, true ),
						'expires_at' => empty( $never_expires ) ? time() + ( 86400 * mt_rand( $settings['days']['min'], $settings['days']['max'] ) ) : 0,
					),
				);
		}
	}

	public function fakerGeneratorSupports( Bundle $bundle, IField $field ) {
		switch ( $this->_name ) {
			case 'payment_plan':
				return ! empty( $bundle->info['payment_enable'] );
		}
		return true;
	}
}
