<?php
/**
 * Ad Expired
 *
 * @package     AutomatorWP\Integrations\Advanced_Ads\Triggers\Ad_Expired
 * @author      AutomatorWP <contact@automatorwp.com>, Ruben Garcia <rubengcdev@gmail.com>
 * @since       1.0.0
 */
// Exit if accessed directly
if( !defined( 'ABSPATH' ) ) exit;

class AutomatorWP_Advanced_Ads_Ad_Expired extends AutomatorWP_Integration_Trigger {

    public $integration = 'advanced_ads';
    public $trigger = 'advanced_ads_ad_expired';

    /**
     * Register the trigger
     *
     * @since 1.0.0
     */
    public function register() {

        automatorwp_register_trigger( $this->trigger, array(
            'integration'       => $this->integration,
            'label'             => __( 'User ad expires', 'automatorwp' ),
            'select_option'     => __( 'User ad <strong>expires</strong>', 'automatorwp' ),
            /* translators: %1$s: Number of times. */
            'edit_label'        => sprintf( __( 'User ad expires %1$s time(s)', 'automatorwp' ), '{times}' ),
            'log_label'         => __( 'User ad expires', 'automatorwp' ),
            'action'            => 'advanced-ads-ad-expired',
            'function'          => array( $this, 'listener' ),
            'priority'          => 10,
            'accepted_args'     => 2,
            'options'           => array(
                'times' => automatorwp_utilities_times_option(),
            ),
            'tags' => array_merge(
                automatorwp_utilities_post_tags(),
                automatorwp_utilities_times_tag()
            )
        ) );

    }

    /**
     * Trigger listener
     *
     * @since 1.0.0
     *
     * @param int $ad_id
     * @param Advanced_Ads_Ad $ad
     */
    public function listener( $ad_id, $ad ) {

        $post = get_post( $ad_id );

        // Bail if post does not exists
        if( ! $post ) {
            return;
        }

        $user_id = absint( $post->post_author );

        // Bail if post does not has an author assigned
        if( absint( $user_id === 0 ) ) {
            return;
        }

        automatorwp_trigger_event( array(
            'trigger'   => $this->trigger,
            'user_id'   => $user_id,
            'post_id'   => $ad_id,
        ) );

    }

}

new AutomatorWP_Advanced_Ads_Ad_Expired();