<?php

namespace Groundhogg\DB\Traits;

use Groundhogg\Event;
use function Groundhogg\isset_not_empty;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
} // Exit if accessed directly

trait Event_Log {

	/**
	 * Add a activity
	 *
	 * @access  public
	 * @since   2.1
	 */
	public function add( $data = array() ) {

		// not sure why this is strictly required, as time always defaults to time() anyway
		// better not touch it and just set time manually within enqueue_event()
		if ( empty( $data['time'] ) ) {
			return false;
		}

		if ( isset_not_empty( $data, 'args' ) ) {
			$data['args'] = maybe_serialize( $data['args'] );
		}

		return $this->insert( $data );
	}


	/**
	 * Clean up DB events when this happens.
	 */
	protected function add_additional_actions() {
		add_action( 'groundhogg/db/post_delete/contact', [ $this, 'contact_deleted' ] );
		add_action( 'groundhogg/db/post_delete/funnel', [ $this, 'funnel_deleted' ] );
		add_action( 'groundhogg/db/post_delete/step', [ $this, 'step_deleted' ] );
		parent::add_additional_actions(); // TODO: Change the autogenerated stub
	}

	/**
	 * Delete events for a contact that was just deleted...
	 *
	 * @param $id
	 *
	 * @return false|int
	 */
	public function contact_deleted( $id ) {

		if ( ! is_numeric( $id ) ) {
			return false;
		}

		return $this->bulk_delete( [ 'contact_id' => $id ] );
	}

	/**
	 * Delete events for a funnel that was just deleted...
	 *
	 * @param $id
	 *
	 * @return false|int
	 */
	public function funnel_deleted( $id ) {

		if ( ! is_numeric( $id ) ) {
			return false;
		}

		return $this->bulk_delete( [ 'funnel_id' => $id ] );
	}

	/**
	 * Delete events for a step that was just deleted...
	 *
	 * @param $id
	 *
	 * @return false|int
	 */
	public function step_deleted( $id ) {

		if ( ! is_numeric( $id ) ) {
			return false;
		}

		// This is only used when funnel steps are deleted...
		return $this->bulk_delete( [ 'step_id' => $id, 'event_type' => Event::FUNNEL ] );
	}
}
