<?php

namespace Simple_Giveaways;

/**
 * Class SG_AutomatorWP
 *
 * @package Simple_Giveaways
 */
class SG_Webhooks extends GA_Integration {

	/**
	 * Get Categories
	 *
	 * @return string[]
	 */
	public function get_categories() {
		return [
			'automation'
		];
	}

	/**
	 * Setting initial params
	 */
	public function __construct() {

		$this->title       = __( 'Webhooks', 'giveasap' );
		$this->settings_id = 'sg_webhooks';
		$this->image       = untrailingslashit( GASAP_URI ) . '/includes/integrations/assets/webhooks.svg';
		$this->desc        = __( 'Run Webhooks on each giveaway.', 'giveasap' );

		add_action( 'sg_metaboxes_before_register', array( $this, 'register_metabox' ) );

        add_action( 'giveasap_register_user', array( $this, 'trigger_register_user' ), 99, 5 );

        add_filter( 'sg_giveaway_meta_settings', array( $this, 'add_webhooks_settings' ) );

        //add_action( 'giveasap_notify_winners', array( $this, 'trigger_winner' ), 99, 2 );
		parent::__construct();
	}

    /**
     * Set fields
     */
    public function set_fields() {

        $this->fields = [
                'docs' => array(
                        'name'    => 'docs',
                        'title'   => __( 'Data sent', 'giveasap' ),
                        'type'    => 'custom',
                        'render'  => array( $this, 'show_data' ),
                        'default' => '',
                ),
        ];
    }

    public function show_data( $field ) {

        $data = [
            'giveaway_id'    => 'Giveaway ID:',
            'giveaway_title' => 'Giveaway Title',
            'url'            => 'Giveaway URL',
            'subscriber_id'  => 'Subscriber ID',
            'email'          => 'Subscriber Email',
            'ref_id'         => 'Subscriber Reference ID',
        ];

        echo '<tr>';

        echo '<th>' . $field['title'] . '</th>';

        echo '<td>';

        echo '<table class="sg-webhook-data-table">';

        foreach ( $data as $key => $value ) {
            echo '<tr><td><code>' . $key . '</code></td><td>' . $value . '</td></tr>';
        }

        echo '</table>';

        echo '</td>';

        echo '</tr>';
    }

    /**
     * Add the Webhooks meta settings to Giveaway object.
     *
     * @param array $meta_keys Array of meta keys.
     *
     * @return mixed
     */
    public function add_webhooks_settings( $meta_keys ) {
        $meta_keys[] = 'giveasap_webhooks';

        return $meta_keys;

    }

    public function trigger_register_user( $subscriber_id, $giveaway_id, $email, $entry, $ref_id ) {

        $giveaway = giveasap_get_giveaway( $giveaway_id );
        $settings = $giveaway->get_setting( 'giveasap_webhooks' );

        if ( empty( $settings ) ) {
            return;
        }

        $webhooks = ! empty( $settings['webhooks_on_register'] ) ? $settings['webhooks_on_register'] : [];

        if ( ! $webhooks ) {
            return;
        }

        $data = [
            'giveaway_id'    => $giveaway_id,
            'giveaway_title' => $giveaway->get_post()->post_title,
            'url'            => $giveaway->get_main_page_link(),
            'subscriber_id'  => $subscriber_id,
            'email'          => $email,
            'ref_id'         => $ref_id,
        ];

        $data = apply_filters( 'sg_webhooks_trigger_register_user_data', $data, $giveaway, $subscriber_id, $email, $entry );

        foreach ( $webhooks as $webhook ) {
            $webhook_url = $webhook['url'];
            $webhook_format = ! empty( $webhook['format'] ) ? $webhook['format'] : 'json';
            $webhook_headers = ! empty( $webhook['headers'] ) ? $webhook['headers'] : [];
            $headers = [];

            if ( $webhook_format === 'form' ) {
                $headers['Content-Type'] = 'application/x-www-form-urlencoded';
            } else {
                $headers['Content-Type'] = 'application/json';
                $data = json_encode( $data );
            }

            if ( ! empty( $webhook_headers ) ) {
                $keys = $webhook_headers['key'];
                $values = $webhook_headers['value'];

                foreach ( $keys as $index => $key ) {
                    $headers[$key] = isset( $values[$index] ) ? $values[$index] : '';
                }
            }

            wp_remote_post( $webhook_url, [
                'body' => $data,
                'headers' => $headers
            ]);

        }
    }

	/**
	 * @param \GiveASAP_Metaboxes $metaboxes
	 */
	public function register_metabox( $metaboxes ) {

		$metabox = new \GiveASAP_Metabox(
			'Webhooks',
			'giveasap_webhooks',
			array( 'giveasap' ),
			'advanced',
			'high',
			'<i class="fal fa-globe"></i>'
		);

		$metabox->add_field(

			array(

				'name' => 'webhooks_on_register',
				'title' => __( 'Send for entering the giveaway', 'giveasap' ),
				'type' => 'custom',
				'desc' => 'Trigger the webhooks when someone enters the giveaway',
				'render' => array( $this, 'webhook_metabox_field' ),
				'default' => '',
				'empty_if_not_set' => true,
			)
		);

		$metaboxes->add( $metabox );

	}

	/**
	 * Show Metabox field
	 *
	 * @return void
	 */
	public function webhook_metabox_field( $field ) {
		?>

		<tr>
			<th>
				<?php echo esc_html( $field['title'] ); ?>
			</th>
			<td>
                <div class="sg-webhooks-fields-container" data-giveasap-sync-key="webhooks_repeater" data-giveasap-adapter="repeater">
                    <?php
                        if ( ! empty( $field['default'] ) ) {
                            foreach ( $field['default'] as $index => $webhook ) {
                                ?>
                                <div class="sg-form-field" data-index="<?php echo esc_attr( $index ); ?>">
                                    <div class="sg-form-field-header">

                                        <div class="sg-field-name">
                                            <?php
                                                echo esc_html( $webhook['title'] );
                                            ?>
                                        </div>
                                    </div>
                                    <div class="sg-form-field-body">
                                        <table class="form-table sg-form-table">
                                            <tr class="sg-field-name">
                                                <td>
                                                    <label for="sg-field-name-<?php echo esc_attr( $index ); ?>"><?php esc_html_e( 'Title', 'giveasap' ); ?></label>
                                                    <input id="sg-field-name-<?php echo esc_attr( $index ); ?>" type="text" name="<?php echo esc_attr( $field['name'] ); ?>[<?php echo esc_attr( $index ); ?>][title]" value="<?php echo esc_attr( $webhook['title'] ); ?>" placeholder="<?php esc_html_e( 'Webhook Name', 'giveasap' ); ?>" />
                                                </td>
                                            </tr>
                                            <tr class="sg-field-url">
                                                <td>
                                                    <label for="sg-field-value-<?php echo esc_attr( $index ); ?>"><?php esc_html_e( 'URL', 'giveasap' ); ?></label>
                                                    <input id="sg-field-value-<?php echo esc_attr( $index ); ?>" type="url" name="<?php echo esc_attr( $field['name'] ); ?>[<?php echo esc_attr( $index ); ?>][url]" value="<?php echo esc_attr( $webhook['url'] ); ?>" placeholder="Webhook URL" />
                                                </td>
                                            </tr>
                                            <tr class="sg-field-format">
                                                <td>
                                                    <label for="sg-field-desc-<?php echo esc_attr( $index ); ?>"><?php esc_html_e( 'Request Format', 'giveasap' ); ?></label>

                                                    <select class="sg-field-desc-textarea" id="sg-field-key-<?php echo esc_attr( $index ); ?>" name="<?php echo esc_attr( $field['name'] ); ?>[<?php echo esc_attr( $index ); ?>][format]">
                                                        <option <?php selected( $webhook['format'], 'json', true ); ?> value="json"><?php esc_html_e( 'JSON', 'giveasap' ); ?></option>
                                                        <option <?php selected( $webhook['format'], 'form', true ); ?> value="form"><?php esc_html_e( 'Form', 'giveasap' ); ?></option>
                                                    </select>
                                                </td>
                                            </tr>
                                            <tr class="sg-field-headers">
                                                <td>
                                                    <label for="sg-prizes-field-headers-<?php echo esc_attr( $index ); ?>"><?php esc_html_e( 'Headers', 'giveasap' ); ?></label>
                                                    <div class="sg-field-headers-rows">
                                                        <?php
                                                            if ( ! empty( $webhook['headers'] ) && ! empty( $webhook['headers']['key'] ) ) {

                                                                foreach ( $webhook['headers']['key'] as $headerIndex => $key ) {
                                                                    ?>
                                                                    <div class="sg-field-headers-row">
                                                                        <input type="text" name="<?php echo esc_attr( $field['name'] ); ?>[<?php echo esc_attr( $index ); ?>][headers][key][]" value="<?php echo esc_attr( $key ); ?>" placeholder="Parameter Key" />
                                                                        <input type="text" name="<?php echo esc_attr( $field['name'] ); ?>[<?php echo esc_attr( $index ); ?>][headers][value][]" value="<?php echo esc_attr( $webhook['headers']['value'][$headerIndex] ); ?>" placeholder="Parameter Value" />
                                                                        <button type="button" class="button button-secondary sg-delete-webhook-header-field"><?php esc_html_e( 'Delete', 'giveasap' ); ?></button>
                                                                    </div>
                                                        <?php
                                                                }
                                                            }
                                                        ?>
                                                    </div>
                                                    <button type="button" class="button button-secondary sg-add-webhook-field-headers-row"><?php esc_html_e( 'Add New Header', 'giveasap' ); ?></button>

                                                </td>
                                            </tr>

                                            <tr>
                                                <td>
                                                    <button type="button" class="button button-secondary sg-delete-webhook-field"><?php esc_html_e( 'Delete Webhook', 'giveasap' ); ?></button>
                                                </td>
                                            </tr>
                                        </table>
                                    </div>
                                </div>

                                <?php
                            }
                        }
                    ?>
                </div>
                <?php if ( isset( $field['_render_context'] ) && 'visual' === $field['_render_context'] ) : ?>
                <button type="button" id="sgAddWebhookFieldVisual" class="button button-secondary sg-add-webhook-field"><?php esc_html_e( 'Add New Webhook', 'giveasap' ); ?></button>
                <?php else : ?>
                <button type="button" id="sgAddWebhookField" class="button button-secondary sg-add-webhook-field"><?php esc_html_e( 'Add New Webhook', 'giveasap' ); ?></button>
                <?php endif; ?>
				<p class="description"><?php echo esc_html( $field['desc'] ); ?></p>

                <script type="text/template" id="tmpl-sg-webhook-headers-field">
                    <div class="sg-field-headers-row">
                        <input type="text" name="<?php echo esc_attr( $field['name'] ); ?>[{{ data.index }}][headers][key][]" value="" placeholder="Parameter Key" />
                        <input type="text" name="<?php echo esc_attr( $field['name'] ); ?>[{{ data.index }}][headers][value][]" value="" placeholder="Parameter Value" />
                        <button type="button" class="button button-secondary sg-delete-webhook-header-field"><?php esc_html_e( 'Delete', 'giveasap' ); ?></button>
                    </div>
                </script>
                <script type="text/template" id="tmpl-sg-webhooks-field">
                    <div class="sg-form-field" data-index="{{ data.index }}">
                        <div class="sg-form-field-header">

                            <div class="sg-field-name">
                                <?php
                                esc_html_e( 'Webhook', 'giveasap' );
                                ?>
                            </div>
                        </div>
                        <div class="sg-form-field-body">
                            <table class="form-table sg-form-table">
                                <tr class="sg-field-name">
                                    <td>
                                        <label for="sg-field-name-{{ data.index }}"><?php esc_html_e( 'Title', 'giveasap' ); ?></label>
                                        <input id="sg-field-name-{{ data.index }}" type="text" name="<?php echo esc_attr( $field['name'] ); ?>[{{ data.index }}][title]" value="" placeholder="<?php esc_html_e( 'Webhook Name', 'giveasap' ); ?>" />
                                    </td>
                                </tr>
                                <tr class="sg-field-url">
                                    <td>
                                        <label for="sg-field-value-{{ data.index }}"><?php esc_html_e( 'URL', 'giveasap' ); ?></label>
                                        <input id="sg-field-value-{{ data.index }}" type="url" name="<?php echo esc_attr( $field['name'] ); ?>[{{ data.index }}][url]" value="" placeholder="Webhook URL" />
                                    </td>
                                </tr>
                                <tr class="sg-field-format">
                                    <td>
                                        <label for="sg-field-desc-{{ data.index }}"><?php esc_html_e( 'Request Format', 'giveasap' ); ?></label>

                                        <select class="sg-field-desc-textarea" id="sg-field-key-{{ data.index }}" name="<?php echo esc_attr( $field['name'] ); ?>[{{ data.index }}][format]">
                                            <option value="json"><?php esc_html_e( 'JSON', 'giveasap' ); ?></option>
                                            <option value="form"><?php esc_html_e( 'Form', 'giveasap' ); ?></option>
                                        </select>
                                    </td>
                                </tr>
                                <tr class="sg-field-headers">
                                    <td>
                                        <label for="sg-prizes-field-headers-{{ data.index }}"><?php esc_html_e( 'Headers', 'giveasap' ); ?></label>
                                        <div class="sg-field-headers-rows">

                                        </div>
                                        <button type="button" class="button button-secondary sg-add-webhook-field-headers-row"><?php esc_html_e( 'Add New Header', 'giveasap' ); ?></button>

                                    </td>
                                </tr>

                                <tr>
                                    <td>
                                        <button type="button" class="button button-secondary sg-delete-webhook-field"><?php esc_html_e( 'Delete Webhook', 'giveasap' ); ?></button>
                                    </td>
                                </tr>
                            </table>
                        </div>
                    </div>

                </script>
			</td>
		</tr>

		<?php

	}


}


add_filter( 'giveasap_integrations', '\Simple_Giveaways\sg_webhooks_register' );

/**
 * Registering Math Captcha
 *
 * @return array
 */
function sg_webhooks_register( $integrations ) {

	$integrations['sg_webhooks'] = '\Simple_Giveaways\SG_Webhooks';

	return $integrations;
}
