<?php
/**
 * Used for handling extra actions.
 */

namespace Simple_Giveaways;

use GiveASAP_Metabox;

/**
 * Class SG_Actions
 */
class SG_Extra_Actions {

	/**
	 * SG_Extra_Actions constructor.
	 */
	public function __construct() {

		add_action( 'sg_metaboxes_before_register', array( $this, 'add_metaboxes' ), 3 );

		$this->includes();

		do_action( 'sg_extra_actions_loaded' );
	}

	protected function includes() {
		include_once 'extra-actions/class-sg-extra-action.php';
		include_once 'extra-actions/class-sg-action-visit.php';
		include_once 'extra-actions/class-sg-action-image.php';
		include_once 'extra-actions/class-sg-action-subscribe.php';
		include_once 'extra-actions/class-sg-action-referred.php';
		include_once 'extra-actions/class-sg-action-register.php';
		include_once 'extra-actions/class-sg-action-comment.php';
		include_once 'extra-actions/class-sg-action-premium-dummy.php';
	}

	/**
	 * Adding extra actions metabox
	 *
	 * @param \GiveASAP_Metaboxes $metaboxes
	 */
	public function add_metaboxes( $sg_metaboxes ) {
		$metabox_extra = new GiveASAP_Metabox( __( 'Extra Entries', 'giveasap' ), 'giveasap_extra_entries', array( 'giveasap' ), 'advanced', 'high', '<i class="fal fa-plus-square"></i>' );

		$metabox_extra->add_field(
			array(
				'name'     => 'entries_actions',
				'title'    => __( 'Extra Actions for Entries', 'giveasap' ),
				'type'     => 'custom',
				'render'   => array( $this, 'entries_actions_render' ),
				'validate' => array( $this, 'validate_actions' ),
				'desc'     => __( 'Create actions for subscribers to get extra entries.', 'giveasap' ),
			)
		);
		$sg_metaboxes->add( $metabox_extra );
	}

	/**
	 * Extra Actions.
	 *
	 * @param array $field
	 */
	public function entries_actions_render( $field ) {
		global $post;

		$values                  = isset( $field['default'] ) && is_array( $field['default'] ) ? $field['default'] : array();
		$registered_actions      = giveasap_get_registered_actions();
		$registered_categories   = giveasap_get_actions_categories();
		$categories_with_actions = array();
		$templates               = array();
		$option_templates        = array();
        $render_context          = isset( $field['_render_context'] ) ? $field['_render_context'] : 'table';

		if ( ! $registered_actions ) {
			return;
        }

		foreach ( $registered_actions as $action_key => $action ) {
			if ( ! class_exists( $action ) ) {
				continue;
			}
			$object = new $action();

			if ( $object->is_internal_only() ) {
				continue;
			}

			$category = $object->get_category();

			if ( ! $category || ! in_array( $category, array_keys( $registered_categories ), true ) ) {
				$category = apply_filters( 'entries_actions_default_category', 'general' );
			}

			if ( ! isset( $categories_with_actions[ $category ] ) ) {
				$categories_with_actions[ $category ] = array();
			}

			$categories_with_actions[ $category ][] = $object;
		}

		if ( $post ) {
			$max_instance_id = get_post_meta( $post->ID, 'sg_extra_actions_max_instance_id', true );
		} else {
			$max_instance_id = 0;
		}

        if ( 'visual' !== $render_context ) {
		?>
		<tr>
			<td colspan="2" style="padding:0;">
				<script>
					window.giveasap_actions = [];
                    window.giveasap_max_instance_id = <?php echo absint( $max_instance_id ); ?>

					<?php
					foreach ( $values as $index => $action ) {
						?>
					window.giveasap_actions.push({
						'title': '<?php echo esc_html( $action['title'] ); ?>',
						'instance': '<?php echo esc_html( $action['instance_id'] ); ?>',
					});
						<?php
					}
					?>
				</script>
                <?php } ?>
				<p><strong><?php echo esc_html( $field['title'] ); ?></strong></p>
				<p class="description"><?php echo esc_html( $field['desc'] ); ?></p>
				<div id="sgEntriesActions<?php if ( 'visual' === $render_context ) { echo "Visual"; } ?>" class="sg-extra-actions" data-giveasap-sync-key="actions_repeater" data-giveasap-adapter="repeater" data-giveasap-repeater-row=".sg-admin-action" data-giveasap-repeater-handle=".sg-admin-action-title">
					<?php
					// In the visual builder the rows are cloned from the metabox
					// container by syncRepeater() on open, so the metabox stays
					// the single source of truth for the saved actions.
					if ( 'visual' !== $render_context ) {
						foreach ( $values as $index => $action ) {
							$action_slug = isset( $action['action'] ) ? $action['action'] : false;
							$class       = $action_slug && isset( $registered_actions[ $action_slug ] ) ? $registered_actions[ $action_slug ] : false;

							if ( ! $class ) {
								continue;
							}

							if ( ! class_exists( $class ) ) {
								continue;
							}

							$object = new $class();
							$object->set_admin_data( $action );
							$object->form_admin( $index );
						}
					}
					?>
				</div>
				<hr/>
				<?php

				if ( $categories_with_actions ) {
					echo '<ul class="sg-actions-categories">';
					foreach ( $categories_with_actions as $category => $actions ) {
						echo '<li class="sg-action-category sg-action-category-' . esc_attr( $category ) . '">';
						echo '<span class="sg-action-category-title">' . esc_html( $registered_categories[ $category ] ) . '</span>';
						echo '<ul class="sg-actions">';
						foreach ( $actions as $action_object ) {
							$action_object->set_admin_data( array() );
							$description = $action_object->get_description();
							$icon        = $action_object->get_icon();
							$template    = $action_object->get_admin_form( '{{ data.index }}' );

							if ( $template ) {
								$templates[ $action_object->get_slug() ] = $action_object->get_admin_form( '{{ data.index }}', '{{ data.instance_id }}' );

								if ( $action_object->option_templates ) {
									foreach ( $action_object->option_templates as $option_slug => $option_template ) {
										$option_templates[ $option_slug ] = $option_template;
									}
								}
							}

							echo '<li class="sg-action" data-slug="' . esc_attr( $action_object->get_slug() ) . '">';
							if ( $icon ) {
								echo $icon;
							}
							echo '<strong>' . esc_html( $action_object->get_title() ) . '</strong>';
							if ( $description ) {
								echo '<p class="description">' . $description . '</p>';
							}
							echo '</li>';
						}
						echo '</ul>';
						echo '</li>';
					}
					echo '</ul>';

                    // No nee to render in sivual builder as well.
                    if ( 'table' === $render_context ) {
                        foreach ( $templates as $tmpl_id => $template ) {
                            ?>
                            <script type="text/template" id="tmpl-<?php echo esc_attr( $tmpl_id ); ?>">
                                <?php echo $template; ?>
                            </script>
                            <?php
                        }

                        foreach ( $option_templates as $option_template ) {
                            echo $option_template;
                        }
                    }
				}

                if ( 'visual' !== $render_context ) {
				?>
			</td>
		</tr>
		<?php
                }
	}


	/**
	 * Validate actions.
	 * Adding the instance ID if missing.
	 *
	 * @param array            $actions
	 * @param GiveASAP_Metabox $settings Object.
	 *
	 * @return array
	 */
	public function validate_actions( $actions, $settings = null ) {
		if ( $actions && is_array( $actions ) ) {

			$max_instance_id = max( array_map( 'absint', wp_list_pluck( $actions, 'instance_id' ) ) );
			if ( $settings->get_post_id() ) {
				$saved_instance_id = get_post_meta( $settings->get_post_id(), 'sg_extra_actions_max_instance_id', true );
				if ( absint( $saved_instance_id ) > $max_instance_id ) {
					$max_instance_id = absint( $saved_instance_id );
				}
			}

			if ( ! $max_instance_id ) {
				$max_instance_id = 0;
            }

			foreach ( $actions as $index => $action ) {
				if ( ! $action['instance_id'] ) {
					$max_instance_id++;
					$action['instance_id'] = $max_instance_id;
					$actions[ $index ]     = $action;
				}
			}
			$actions = array_values( $actions );
			if ( $settings->get_post_id() ) {
				update_post_meta( $settings->get_post_id(), 'sg_extra_actions_max_instance_id', $max_instance_id );
			}
		}
		return $actions;
	}

}
