<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use Discountify\Utils\Helper;

if ( file_exists( \Discountify::core_dir() . 'admin/settings/settings-fields.php' ) ) {
	include_once \Discountify::core_dir() . 'admin/settings/settings-fields.php';
}

// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Display only, form submission has nonce
$id               = ( isset( $_GET['id'] ) ) ? intval( $_GET['id'] ) : '';
$discountify_rule = Helper::get_single_rule( $id );

extract( $discountify_rule );

?>

<div class="mt-2 mb-2 content-header">
	<?php
		$title = $ID === '' ? esc_html__( 'Add Discount Rules', 'discountify' ) : esc_html__( 'Edit', 'discountify' ) . ' ' . $discount_name;
	?>
	<div class="title mr-1"><?php echo esc_html( $title ); ?></div>
	<?php // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Display only
	if ( ! isset( $_GET['rule'] ) || sanitize_key( $_GET['rule'] ) !== 'new-rule' ) : ?>
	<a href="<?php echo esc_url( admin_url( 'admin.php?page=discountify-rules&rule=new-rule' ) ); ?>" target="_self" style="margin-right:8px">
		<button type="button" class="button button-primary"><?php esc_html_e( 'Add Discount Rules', 'discountify' ); ?></button>
	</a>
	<?php endif; ?>
	<a href="<?php echo esc_url( admin_url( 'admin.php?page=discountify-rules' ) ); ?>" target="_self">
		<button type="button" class="button button-primary"><?php esc_html_e( 'View Discount Rules', 'discountify' ); ?></button>
	</a>
</div>

<div class="discount-form mt-2">
	<form id="save_discount_rules" class="disc-wrapper" method="post">
		<input type="hidden" name="save_discount" value="save_discount">
		<?php
			wp_nonce_field( 'save_discount_rules', 'save_discount_rules', true, true );
			$discountify_disable = Helper::instance()->is_pro_active() === true ? false : true;

			// Discount name
			$discountify_args = array(
				'label'           => '',
				'field_type'      => 'hidden',
				'id'              => 'ID',
				'value'           => $ID,
				'condition_class' => 'd-none',
			);

			discountify_number_input_field( $discountify_args );

			// Discount rules
			$discountify_args = array(
				'label'       => esc_html__( 'Rules Type:', 'discountify' ),
				'id'          => 'rules_type',
				'select_type' => 'single',
				'selected'    => $rules_type,
				'options'     => Helper::instance()->rules_type( true ),
			);

			discountify_select_field( $discountify_args );

			?>
		<div id="rules_block" data-rules_type="simple">
			<?php
				// simple discount in
				$discountify_args = array(
					'label'   => esc_html__( 'Enable Rules:', 'discountify' ),
					'id'      => 'enable_rules',
					'checked' => $enable_rules,
				);
				discountify_checkbox_field( $discountify_args );
				?>
			<?php
				$discountify_discount_label_cond    = ( $rules_type === 'free_shipping' ) ? 'd-none' : '';
				$discountify_cart_adjustment_cond   = $rules_type === 'cart_adjustment' ? '' : 'd-none';
				$discountify_free_shipping_based_on = ! empty( $discountify_rule['free_shipping_based_on'] ) ? $discountify_rule['free_shipping_based_on'] : 'product';
			?>
			<div class="rules-block <?php echo esc_attr( $enable_rules ) === 'yes' ? esc_attr( 'enable_rules' ) : esc_attr( 'd-none' ); ?>">
				<?php
						// Discount name
						$discountify_args = array(
							'label'      => esc_html__( 'Discount Rules Name:', 'discountify' ),
							'field_type' => 'text',
							'id'         => 'discount_name',
							'value'      => $discount_name,
							'docs'       => esc_html__( 'Discount Rules Name will be shown in Admin', 'discountify' ),
						);
						discountify_number_input_field( $discountify_args );
						// Discount label
						$discountify_args = array(
							'label'           => esc_html__( 'Discount Message:', 'discountify' ),
							'field_type'      => 'text',
							'id'              => 'discount_label',
							'value'           => $discount_label === '' ? esc_html__( 'Discount', 'discountify' ) : $discount_label,
							'condition_class' => 'discount_label_field ' . $discountify_discount_label_cond,
							'docs'            => esc_html__( 'This message will be displayed on the frontend', 'discountify' ),
						);
						discountify_number_input_field( $discountify_args );
						?>
				<div class="discount_in <?php echo esc_attr( $discountify_discount_label_cond ); ?>">
					<?php
						// Apply discount in product/category
						$discountify_disable = class_exists( 'DiscountifyPro' ) ? false : true;
						// Enable category for cart_adjustment even without pro
					if ( $rules_type === 'cart_adjustment' ) {
						$discountify_disable = false;
					}
						$discountify_args = array(
							'label'       => esc_html__( 'Discount In:', 'discountify' ),
							'id'          => 'discount_in',
							'select_type' => 'single',
							'selected'    => $discount_in,
							'options'     => array(
								'product'  => esc_html__( 'Product', 'discountify' ),
								'category' => esc_html__( 'Category', 'discountify' ),
							),
						);
						if ( $discountify_disable ) {
							$discountify_args['disable'] = 'category';
						}
						discountify_select_field( $discountify_args );

						// Apply discount in products
						$discountify_prod_condition = $discount_in === 'category' ? 'd-none' : '';

						$discountify_args = array(
							'label'           => esc_html__( 'Filter By Products:', 'discountify' ),
							'id'              => 'filter_by_products',
							'selected'        => $filter_by_products,
							'select_type'     => 'multiple',
							'condition_class' => 'select2-multiple product ' . $discountify_prod_condition,
							'options'         => Helper::get_products(),
						);
						discountify_select_field( $discountify_args );

						// Apply discount in category
						$discountify_cat_condition = $discount_in === 'product' ? 'd-none' : '';

						$discountify_args = array(
							'label'           => esc_html__( 'Filter By Categories:', 'discountify' ),
							'id'              => 'filter_by_category',
							'selected'        => $filter_by_category,
							'select_type'     => 'multiple',
							'condition_class' => 'select2-multiple category ' . $discountify_cat_condition,
							'options'         => Helper::get_categories(),
						);
						discountify_select_field( $discountify_args );
						?>
				</div>
				<?php
					$discountify_simple_cond          = $rules_type === 'simple' ? '' : 'd-none';
					$discountify_bogo_cond            = $rules_type === 'bogo' ? '' : 'd-none';
					$discountify_free_shipping_cond   = $rules_type === 'free_shipping' ? '' : 'd-none';
					$discountify_simple_repeater_cond = ( $rules_type === '' || $rules_type === 'simple' || $rules_type === 'free_shipping' ) ? 'd-none' : '';
				?>
				<!-- Free Shipping Section -->
				<div class="free_shipping <?php echo esc_attr( $discountify_free_shipping_cond ); ?>">
					<?php
						// Free Shipping - Discount Based On
						$discountify_args = array(
							'label'       => esc_html__( 'Discount Based On:', 'discountify' ),
							'id'          => 'free_shipping_based_on',
							'select_type' => 'single',
							'selected'    => $discountify_free_shipping_based_on,
							'options'     => array(
								'product'     => esc_html__( 'Product', 'discountify' ),
								'category'    => esc_html__( 'Category', 'discountify' ),
								'cart_amount' => esc_html__( 'Cart Amount', 'discountify' ),
							),
						);
						discountify_select_field( $discountify_args );

						// Free Shipping - Filter By Products
						$discountify_fs_prod_condition = $discountify_free_shipping_based_on !== 'product' ? 'd-none' : '';
						$discountify_args  = array(
							'label'           => esc_html__( 'Filter By Product:', 'discountify' ),
							'id'              => 'free_shipping_products',
							'selected'        => ! empty( $discountify_rule['free_shipping_products'] ) ? $discountify_rule['free_shipping_products'] : array(),
							'select_type'     => 'multiple',
							'condition_class' => 'select2-multiple free_shipping_product ' . $discountify_fs_prod_condition,
							'options'         => Helper::get_products(),
						);
						discountify_select_field( $discountify_args );

						// Free Shipping - Filter By Category
						$discountify_fs_cat_condition = $discountify_free_shipping_based_on !== 'category' ? 'd-none' : '';
						$discountify_args = array(
							'label'           => esc_html__( 'Filter By Categories:', 'discountify' ),
							'id'              => 'free_shipping_categories',
							'selected'        => ! empty( $discountify_rule['free_shipping_categories'] ) ? $discountify_rule['free_shipping_categories'] : array(),
							'select_type'     => 'multiple',
							'condition_class' => 'select2-multiple free_shipping_category ' . $discountify_fs_cat_condition,
							'options'         => Helper::get_categories(),
						);
						discountify_select_field( $discountify_args );

						// Free Shipping - Minimum Cart Amount
						$discountify_fs_cart_condition = $discountify_free_shipping_based_on !== 'cart_amount' ? 'd-none' : '';
						$discountify_args  = array(
							'label'             => esc_html__( 'Minimum Cart Amount:', 'discountify' ),
							'field_type'        => 'number',
							'id'                => 'free_shipping_min_amount',
							'value'             => ! empty( $discountify_rule['free_shipping_min_amount'] ) ? $discountify_rule['free_shipping_min_amount'] : '',
							'extra_label'       => Helper::currency_symbol(),
							'extra_label_class' => 'free_shipping_min_amount_label',
							'condition_class'   => 'free_shipping_cart_amount ' . $discountify_fs_cart_condition,
							'docs'              => esc_html__( 'Enter minimum cart amount to qualify for free shipping', 'discountify' ),
						);
						discountify_number_input_field( $discountify_args );
						?>
				</div>
				<!-- Cart Adjustment Section -->
				<div class="cart_adjustment <?php echo esc_attr( $discountify_cart_adjustment_cond ); ?>">
					<?php
						// Cart Adjustment - Discount On
						$discountify_cart_discount_on = ! empty( $discountify_rule['cart_discount_on'] ) ? $discountify_rule['cart_discount_on'] : 'cart_total';
						$discountify_args = array(
							'label'       => esc_html__( 'Discount On:', 'discountify' ),
							'id'          => 'cart_discount_on',
							'select_type' => 'single',
							'selected'    => $discountify_cart_discount_on,
							'options'     => array(
								'cart_total' => esc_html__( 'Cart Total', 'discountify' ),
								'cart_qty'   => esc_html__( 'Cart Quantity', 'discountify' ),
							),
							'docs'        => esc_html__( 'Choose whether to apply discount based on cart total amount or cart quantity', 'discountify' ),
						);
						discountify_select_field( $discountify_args );

						// Cart Adjustment Repeater - Label and Discount
						$discountify_cart_label = ( $discountify_cart_discount_on === 'cart_total' || $discountify_cart_discount_on === '' ) ? esc_html__( 'Subtotal', 'discountify' ) : esc_html__( 'Quantity', 'discountify' );

						$discountify_cart_adjustment_repeater = array(
							array(
								'label'       => $discountify_cart_label . ':',
								'label_class' => 'cart-adjustment-label',
								'field_type'  => 'number',
								'id'          => 'label',
								'value'       => '',
							),
							array(
								'label'      => esc_html__( 'Discount:', 'discountify' ),
								'field_type' => 'number',
								'id'         => 'discount',
								'value'      => '',
							),
							array(
								'field_type'      => 'span',
								'id'              => 'currency',
								'condition_class' => 'cart-adjustment-symbol',
								'value'           => class_exists( 'WooCommerce' ) ? get_woocommerce_currency_symbol() : '',
							),
						);

						$discountify_args = array(
							'label'        => esc_html__( 'Discount Rules:', 'discountify' ),
							'id'           => 'cart_adjustment_rules',
							'name'         => 'multi_discounts[cart_adjustment]',
							'repeat_field' => $discountify_cart_adjustment_repeater,
						);

						?>
				</div>
				<div class="simple <?php echo esc_attr( $discountify_simple_cond ); ?>">
					<?php
						// Apply discount by
						$discountify_args = array(
							'label'       => esc_html__( 'Discount Type:', 'discountify' ),
							'id'          => 'discount_type',
							'select_type' => 'single',
							'selected'    => $discount_type,
							'options'     => array(
								'fixed_product'   => esc_html__( 'Fixed Discount', 'discountify' ),
								'percent_product' => esc_html__( 'Percentage Discount', 'discountify' ),
							),
						);
						discountify_select_field( $discountify_args );

						// discount in fixed or percentage
						$discountify_args = array(
							'label'             => esc_html__( 'Discount:', 'discountify' ),
							'field_type'        => 'number',
							'id'                => 'discount_number',
							'value'             => $discount_number,
							'extra_label'       => $discount_type === 'fixed_product' ? Helper::currency_symbol() : '%',
							'extra_label_class' => 'discount_number_label',
						);
						discountify_number_input_field( $discountify_args );
						?>
				</div>
				
				<?php
				/**
				 * Repeater field
				 */
				$discountify_repeater_value = ! empty( $discountify_rule['multi_discounts'] ) ? $discountify_rule['multi_discounts'] : array();
				$type           = ! empty( $discountify_rule['rules_type'] ) ? $discountify_rule['rules_type'] : '';
				?>
				<div class="repeater-main <?php echo esc_attr( $discountify_simple_repeater_cond ); ?>">
					<div class="bogo <?php echo esc_attr( $discountify_bogo_cond ); ?>">
						<?php
						if ( file_exists( \Discountify::core_dir() . 'admin/discount-rules/add-bogo-rules.php' ) ) {
							include \Discountify::core_dir() . 'admin/discount-rules/add-bogo-rules.php';
						}
						?>
					</div>
					<?php
					$bogo_hide_repeater = ( isset( $bogo_discount_type ) && $bogo_discount_type === 'bogo_free' ) ? ' style="display:none;"' : '';
					?>
					<div class="discountify-repeater-wrap"<?php echo $bogo_hide_repeater; ?>>
					<?php
					if ( file_exists( \Discountify::core_dir() . 'admin/discount-rules/repeater-field.php' ) ) {
						include_once \Discountify::core_dir() . 'admin/discount-rules/repeater-field.php';
					}
					?>
					</div>
					<script>
						jQuery(document).ready(function() {
							let repeater_value = <?php echo ! empty( $discountify_repeater_value ) ? json_encode( $discountify_repeater_value ) : json_encode( array( array() ) ); ?>;
							repeater_block( repeater_value , '<?php echo esc_js( $type ); ?>' , jQuery );
							new_rules_action(jQuery,repeater_value , '<?php echo esc_js( $type ); ?>' );
							bogo_apply_field_visibility(jQuery, jQuery('#bogo_discount_type').val());
						})
					</script>
				</div>
			</div>
		</div>
		
		<?php
			// user role
			$discountify_args = array(
				'label'   => esc_html__( 'Discount Condition Based on Specific Customer / Customer Role', 'discountify' ),
				'id'      => 'enable_user_discount',
				'checked' => $enable_user_discount,
				'desc'    => esc_html__( 'Apply discount based on customer', 'discountify' ),
			);
			discountify_checkbox_field( $discountify_args );

			$discountify_user_discount_cond = $enable_user_discount === 'yes' ? '' : 'd-none';

			$discountify_args = array(
				'label'           => esc_html__( 'Specific Roles:', 'discountify' ),
				'id'              => 'disc_user_roles',
				'select_type'     => 'multiple',
				'selected'        => $disc_user_roles,
				'condition_class' => 'enable_user_discount ' . $discountify_user_discount_cond,
				'options'         => Helper::wp_roles_arr(),
			);
			discountify_select_field( $discountify_args );


			discountify_number_input_field(
				array(
					'label' => esc_html__( 'Discount Rules Validation Period', 'discountify' ),
					'id'    => 'discount_valid',
					'desc'  => esc_html__( 'Leave empty for unlimited time', 'discountify' ),
					'value' => $discount_valid,
				)
			);

			?>
		<button class="button button-primary admin-button mt-3"><?php esc_html_e( 'Save Changes', 'discountify' ); ?></button>
	</form>
</div>
