<?php
/**
 * Scoring Rule add/edit form template
 *
 * @link       https://personalizewp.com/
 * @since      3.2.0 Merged into PWP
 * @since      1.1.0
 *
 * @package    PersonalizeWP
 * @subpackage PersonalizeWP/Admin
 *
 * @var PersonalizeWP\Model\Scoring_Rule $score_rule The instance of the Scoring Rule class.
 */

use PersonalizeWP\Admin\PageScoringRules;
use PersonalizeWP\Admin\Utils;

defined( 'ABSPATH' ) || exit; // Exit if accessed directly.

if ( $this->getError( 'form' ) ) :
	?>
	<div class="alert alert-danger" role="alert">
		<?php echo implode( '<br>', array_map( 'esc_html', $this->getError( 'form' ) ) ); ?>
	</div>
	<?php
endif;
?>
<input type="hidden" name="pwp_form[is_active]" value="<?php echo (int) ( $score_rule->ID ? $score_rule->is_active : 1 ); ?>" />

<div class="row mb-3">
	<div class="col-12 col-lg-6">
		<div class="form-group mb-2">
			<label for="pwp_form[name]"><?php esc_html_e( 'Rule Name', 'personalizewp' ); ?></label>

			<input type="text" id="pwp_form[name]" name="pwp_form[name]" value="<?php echo esc_attr( $score_rule->name ); ?>"
				class="form-control <?php echo ( $this->getError( 'name' ) ? esc_attr( 'is-invalid' ) : '' ); ?>" />

			<?php if ( $this->getError( 'name' ) ) : ?>
				<div class="invalid-feedback">
					<span class="dashicons dashicons-warning"></span>
					<?php echo esc_html( implode( ', ', $this->getError( 'name' ) ) ); ?>
				</div>
			<?php endif; ?>
		</div>
	</div>
</div>


<div class="row mb-3">
	<div class="col-12 col-lg-6">
		<div class="form-group mb-2 category-dropdown">
			<label for="pwp_form_type"><?php esc_html_e( 'Type', 'personalizewp' ); ?></label>

			<select required name="pwp_form[type]" id="pwp_form_type" class="form-control <?php echo ( $this->getError( 'type' ) ? esc_attr( 'is-invalid' ) : '' ); ?>">
				<?php
				$options = [ '' => __( '-- Select scoring rule type --', 'personalizewp' ) ] + PageScoringRules::get_scoring_rule_types();
				foreach ( $options as $opt_val => $opt_label ) {
					printf(
						'<option value="%1$s" %2$s>%3$s</option>',
						esc_attr( $opt_val ),
						selected( $score_rule->type === $opt_val, true, false ),
						esc_html( $opt_label )
					);
				}
				?>
			</select>

			<?php if ( $this->getError( 'type' ) ) : ?>
				<div class="invalid-feedback">
					<span class="dashicons dashicons-warning"></span>
					<?php echo esc_html( implode( ', ', $this->getError( 'type' ) ) ); ?>
				</div>
			<?php endif; ?>
		</div>
	</div>
</div>

<div class="row mb-3">
	<div class="col-12 col-lg-6">
		<div class="form-group mb-2 lead_score">
			<label for="pwp_form_lead_score"><?php esc_html_e( 'Score Value', 'personalizewp' ); ?></label>
			<p class="description"><?php esc_html_e( 'Enter the score to be added for this rule', 'personalizewp' ); ?></p>

			<input type="number" required inputmode="numeric" name="pwp_form[lead_score]" id="pwp_form_lead_score" value="<?php echo ( ! empty( $score_rule->lead_score ) ? (int) $score_rule->lead_score : '' ); ?>" maxlength="5"
				placeholder="<?php esc_attr_e( 'Set a positive or negative value', 'personalizewp' ); ?>" class="form-control medium-input <?php echo ( $this->getError( 'lead_score' ) ? esc_attr( 'is-invalid' ) : '' ); ?>" />

			<?php if ( $this->getError( 'lead_score' ) ) : ?>
				<div class="invalid-feedback">
					<span class="dashicons dashicons-warning"></span>
					<?php echo esc_html( implode( ', ', $this->getError( 'lead_score' ) ) ); ?>
				</div>
			<?php endif; ?>
		</div>
	</div>
</div>

<div class="row" id="condition-operator" hidden>
	<div class="col-12 col-lg-6">
		<div class="form-group mb-2 category-dropdown">

			<label for="condition-operator-select"><?php esc_html_e( 'Condition Matching', 'personalizewp' ); ?></label>
			<p class="description"><?php esc_html_e( 'Apply the scoring rule to the activity if:', 'personalizewp' ); ?></p>
			<select name="pwp_form[operator]" id="condition-operator-select">
				<option value="ANY" <?php selected( 'ANY', strtoupper( $score_rule->operator ) ); ?>><?php esc_html_e( 'Any of the conditions match (OR logic)', 'personalizewp' ); ?></option>
				<option value="ALL" <?php selected( 'ALL', strtoupper( $score_rule->operator ) ); ?>><?php esc_html_e( 'All of the conditions match (AND logic)', 'personalizewp' ); ?></option>
			</select>

		</div>
	</div>
</div>

<div class="row js">
	<div class="col-12 col-xl-10">
		<div class="form-group mb-2">
			<?php
			$conditions = ! empty( $score_rule->conditions ) ? json_decode( $score_rule->conditions, true ) : [];
			$cons_count = count( $conditions );

			// We output all form variants for all scoring rule types. JS then selectively changes what
			// "conditions" are shown based on type; as well as creating new rows from a <template>
			// specific to each condition type, or deleting rows as needed.
			?>

			<?php
			$products = [];
			if ( 'product' === $score_rule->type && ! empty( $conditions ) ) :
				foreach ( $conditions as $_con_plugin => $_con_args ) :
					foreach ( $_con_args as $_con_type => $_con_ids ) :
						foreach ( $_con_ids as $_con_id ) :
							if ( is_numeric( $_con_id ) ) :
								// e.g. `woocommerce:product:1`
								$_title     = Utils::get_product_title( $_con_id, $_con_type, $_con_plugin );
								$products[] = array(
									'value' => sprintf(
										'%1$s:%2$s:%3$d',
										$_con_plugin,
										$_con_type,
										$_con_id
									),
									'text'  => esc_html( ! empty( $_title ) ? $_title : __( 'Unknown', 'personalizewp' ) ),
								);
							endif;
						endforeach;
					endforeach;
				endforeach;
			endif;
			?>
			<div <?php echo ( 'product' !== $score_rule->type ) ? 'hidden' : ''; ?>
					data-condition-count="<?php echo (int) ( 'product' === $score_rule->type ? 1 : 0 ); ?>"
					data-condition-type="product" class="conditions-container">
				<label for="auto-complete-product"><?php esc_html_e( 'Category / Product', 'personalizewp' ); ?></label>
				<p class="description"><?php esc_html_e( 'Search for and add a product or category', 'personalizewp' ); ?></p>
				<div data-condition="row" class="condition mb-3 mb-sm-3">
					<auto-complete
						mode="product" label-id="auto-complete-product"
						placeholder="<?php esc_attr_e( 'Search for a category or product', 'personalizewp' ); ?>"
						content="<?php echo esc_attr( wp_json_encode( $products ) ); ?>">

						<template hidden>
							<input type="hidden" name="pwp_form[product][]" value="" />
							<span></span>
							<button type="button" class="button" aria-label="<?php esc_attr_e( 'Remove item', 'personalizewp' ); ?>">
								<?php Utils::svg_icon( 'cross' ); ?>
							</button>
						</template>
					</auto-complete>
				</div>
			</div><!-- .conditions-container -->

			<?php
			$forms = [];
			if ( 'form' === $score_rule->type && ! empty( $conditions ) ) :
				foreach ( $conditions as $form_id => $current_form_opts ) :
					if ( is_numeric( $form_id ) ) :
						// e.g. `gravityforms:1`
						$form_title = Utils::get_form_title( $form_id, $current_form_opts );
						$forms[]    = array(
							'value' => sprintf(
								'%1$s:%2$d',
								$current_form_opts,
								$form_id
							),
							'text'  => esc_html( ! empty( $form_title ) ? $form_title : __( 'Unknown', 'personalizewp' ) ),
						);
					endif;
				endforeach;
			endif;
			?>
			<div <?php echo ( 'form' !== $score_rule->type ) ? 'hidden' : ''; ?>
					data-condition-count="<?php echo (int) ( 'form' === $score_rule->type ? 1 : 0 ); ?>"
					data-condition-type="form" class="conditions-container">
				<label for="auto-complete-form"><?php esc_html_e( 'Form', 'personalizewp' ); ?></label>
				<p class="description"><?php esc_html_e( 'Search for and add an existing form', 'personalizewp' ); ?></p>
				<div data-condition="row" class="condition">
					<auto-complete
						mode="form" label-id="auto-complete-form"
						placeholder="<?php esc_attr_e( 'Search for a form', 'personalizewp' ); ?>"
						content="<?php echo esc_attr( wp_json_encode( $forms ) ); ?>">

						<template hidden>
							<input type="hidden" name="pwp_form[form][]" value="" />
							<span></span>
							<button type="button" class="button" aria-label="<?php esc_attr_e( 'Remove item', 'personalizewp' ); ?>">
								<?php Utils::svg_icon( 'cross' ); ?>
							</button>
						</template>
					</auto-complete>
				</div>
			</div><!-- .conditions-container -->

			<?php
			$cpt_pages = ( 'page' === $score_rule->type && ! empty( $conditions ) ) ? $conditions : [ '' ];
			// Split conditions into IDs and strings.
			$page_ids  = [];
			$page_urls = [];
			foreach ( $cpt_pages as $index => $cpt_page ) :
				if ( is_numeric( $cpt_page ) ) :
					$page_ids[] = array(
						'value' => (string) $cpt_page, // Web component standardises on strings
						'text'  => get_the_title( $cpt_page ),
					);
				elseif ( is_numeric( $index ) && ! is_numeric( $cpt_page ) ) :
					// Legacy format of URL, without options.
					$page_urls[$cpt_page] = '';
				elseif ( ! is_numeric( $index ) && is_string( $index ) ) :
					// Newer format, index *is* URL.
					$page_urls[$index] = $cpt_page;
				endif;
			endforeach;
			if ( empty( $page_urls ) ) :
				// Always ensure we display at least 1 plain URL input
				$page_urls = [ '' => '' ];
			endif;
			?>
			<div <?php echo ( 'page' !== $score_rule->type ) ? 'hidden' : ''; ?>
					data-condition-count="<?php echo (int) ( 'page' === $score_rule->type ? count( $page_urls ) : 0 ); ?>"
					data-condition-type="page" class="conditions-container">
					<label for="auto-complete-page"><?php esc_html_e( 'Page / Post', 'personalizewp' ); ?></label>
				<p class="description"><?php esc_html_e( 'Search for and add an existing page or post', 'personalizewp' ); ?></p>
				<div data-condition="row" class="condition">
					<auto-complete
						mode="post" content-types="post,page" label-id="auto-complete-page"
						placeholder="<?php esc_attr_e( 'Search for a post or page', 'personalizewp' ); ?>"
						content="<?php echo esc_attr( wp_json_encode( $page_ids ) ); ?>">

						<template hidden>
							<input type="hidden" name="pwp_form[page][id][]" value="" />
							<span></span>
							<button type="button" class="button" aria-label="<?php esc_attr_e( 'Remove item', 'personalizewp' ); ?>">
								<?php Utils::svg_icon( 'cross' ); ?>
							</button>
						</template>
					</auto-complete>
				</div>

				<p class="description"><?php esc_html_e( 'Or add your own URL in the plain text input below', 'personalizewp' ); ?></p>
				<?php
				foreach ( $page_urls as $page_url => $url_opts ) :
					$is_regex = ! empty( $url_opts ) && 'regex' === $url_opts;
					?>
					<div data-condition="row" class="condition mb-3 mb-sm-3">
						<input type="text" data-type="page" name="pwp_form[page][url][]" class="form-control"
							value="<?php echo esc_attr( $page_url ); ?>" />

						<label for="pwp_form_url_regex_<?php echo esc_attr( $row_count ); ?>" class="nowrap">
							<input type="checkbox" data-type="referer" id="pwp_form_url_regex_<?php echo esc_attr( $row_count ); ?>" name="pwp_form[page][regex][]" value="regex" class="form-control"
							<?php checked( $is_regex ); ?> />
							<?php esc_html_e( 'Is Regex?', 'personalizewp' ); ?>
						</label>

						<div class="button-conditions-wrapper">
							<button type="button" value="remove" class="remove-condition" aria-label="<?php esc_attr_e( 'Remove item', 'personalizewp' ); ?>">
								<?php Utils::svg_icon( 'bin' ); ?>
							</button>
						</div>
					</div>
					<?php
				endforeach;
				?>
				<template hidden>
					<div data-condition="row" class="condition mb-3 mb-sm-3">
						<input type="text" data-type="page" name="pwp_form[page][url][]" class="form-control" value="" />

						<label for="pwp_form_url_regex_{{ID}}" class="nowrap">
							<input type="checkbox" data-type="referer" id="pwp_form_url_regex_{{ID}}" name="pwp_form[page][regex][]" value="regex" class="form-control" />
							<?php esc_html_e( 'Is Regex?', 'personalizewp' ); ?>
						</label>

						<div class="button-conditions-wrapper">
							<button type="button" value="remove" class="remove-condition" aria-label="<?php esc_attr_e( 'Remove item', 'personalizewp' ); ?>">
								<?php Utils::svg_icon( 'bin' ); ?>
							</button>
						</div>
					</div>
				</template>
			</div><!-- .conditions-container -->

			<?php
			$condition_errors = $this->getError( 'conditions' );
			if ( ! empty( $condition_errors ) ) :
				?>
				<div class="form-control is-invalid" style="display: none;"><!-- Used to show the next node --></div>
				<div class="invalid-feedback">
					<span class="dashicons dashicons-warning"></span>
					<?php echo esc_html( implode( ', ', $condition_errors ) ); ?>
				</div>
				<?php
			endif;
			?>
		</div>
	</div>
</div>

<div id="condition-addition" class="mb-3" hidden>
	<button type="button" value="add" class="add-condition">&plus; <?php esc_html_e( 'Add', 'personalizewp' ); ?></button>
</div>

<div id="form-actions">
	<?php if ( 0 !== (int) $score_rule->ID ) : ?>
		<button type="submit" value="save" class="primary btn"><?php esc_html_e( 'Save Changes', 'personalizewp' ); ?></button>
		<a href="<?php echo esc_url( admin_url( PageScoringRules::$index_url ) ); ?>" class="secondary btn"><?php esc_html_e( 'Cancel', 'personalizewp' ); ?></a>
	<?php else : ?>
		<button type="submit" value="create" class="primary btn"><?php esc_html_e( 'Create Scoring Rule', 'personalizewp' ); ?></button>
		<a href="<?php echo esc_url( admin_url( PageScoringRules::$index_url ) ); ?>" class="secondary btn"><?php esc_html_e( 'Cancel', 'personalizewp' ); ?></a>
	<?php endif; ?>
</div>
