<?php

use BracketSpace\Notification\Abstracts\Trigger;
use BracketSpace\Notification\Defaults\MergeTag\StringTag;
use BracketSpace\Notification\Defaults\MergeTag\UrlTag;
use Merkulove\Contacter\CROptionsMetaBox;

class ContacterAddedTrigger extends Trigger {

	public function __construct() {

		/** Add slug and the title. */
		parent::__construct(
			'contacter/record/added',
			esc_html__( 'Contacter Record Added', 'contacter' )
		);

		/** Hook to the action. */
		$this->add_action( 'contacter_record_added', 10, 1 );

		/** Add description to trigger. */
		$this->set_description(
			esc_html__( 'Fires when a new Contacter Record submitted.', 'contacter' )
		);

	}

	public function action( $post_id ) {

		/** If $post_id is empty, don't send any notifications. */
		if ( empty( $post_id ) ) { return false; }

		/** Set the trigger properties. */
		$this->post = get_post( $post_id );

	}

	public function merge_tags() {

		$this->add_merge_tag( new UrlTag( [
			'slug'        => 'record_url',
			'name'        => __( 'Record URL', 'contacter' ),
			'resolver'    => function ( $trigger ) {

				/** Prepare edit link. */
				$action = '&action=edit';

				$post_type_object = get_post_type_object( $trigger->post->post_type );
				if ( ! $post_type_object ) { return ''; }

				if ( $post_type_object->_edit_link ) {
					$link = admin_url( sprintf( $post_type_object->_edit_link . $action, $trigger->post->ID ) );
				} else {
					$link = '';
				}

				return  $link;

			},
		] ) );

		$this->add_merge_tag( new StringTag( [
			'slug'        => 'record_title',
			'name'        => __( 'Record title', 'contacter' ),
			'resolver'    => function ( $trigger ) {

				return $trigger->post->post_title;

			},
		] ) );

		$this->add_merge_tag( new UrlTag( [
			'slug'        => 'record_audio',
			'name'        => __( 'Audio URL', 'contacter' ),
			'resolver'    => function ( $trigger ) {

				/** Get Audio path value from meta if it's exist. */
				$audio_path = get_post_meta( $trigger->post->ID, 'mdp_contacter_audio', true );
				if ( empty( $audio_path ) ) { return ''; }

				return CROptionsMetaBox::get_instance()->abs_path_to_url( $audio_path );

			},
		] ) );

		$this->add_merge_tag( new StringTag( [
			'slug'        => 'record_field_FIELD_NAME',
			'name'        => __( 'Record Field', 'contacter' ),
			'resolver'    => function ( $trigger ) {

				return '';

			},
		] ) );

	}

}
