<?php
/**
 * Handles WP_Comment related Activities
 *
 * @link       https://personalizewp.com/
 * @since      3.2.0 Merged into PWP
 * @since      1.0.0
 *
 * @package    PersonalizeWP
 * @subpackage PersonalizeWP/Tracking
 */

namespace PersonalizeWP\Tracking;

use PersonalizeWP\Tracking\Base;
use PersonalizeWP\Model\Contact;
use PersonalizeWP\Model\Activity;

defined( 'ABSPATH' ) || exit; // Exit if accessed directly.

/**
 * Defines comments functionality
 *
 * This class defines all code to add commenters to PWP contacts
 */
class Comments extends Base {

	/**
	 * Execute hooks
	 */
	public function setup() {
		add_action( 'wp_insert_comment', array( $this, 'comment_inserted' ), 10, 2 );
		add_action( 'comment_form', array( $this, 'add_hidden_input_field' ), 10, 2 );
	}

	/**
	 * Update Contact when a user comments
	 *
	 * @param int         $id      The comment ID.
	 * @param \WP_Comment $comment Comment object.
	 *
	 * @return void
	 */
	public function comment_inserted( $id, $comment ) {

		$uid = $this->get_uid();
		// Sanity check.
		if ( empty( $uid ) ) {
			return;
		}

		$user_data = [];
		$comment   = get_comment( $comment );
		// Require non-empty author, which should always exist.
		if ( ! empty( $comment->comment_author ) ) {
			// split string from first space and put the rest into last name
			$author    = explode( ' ', $comment->comment_author, 2 );
			$user_data = array(
				'first_name' => $author[0],
				'email'      => $comment->comment_author_email,
			);
			if ( ! empty( $author[1] ) ) {
				$user_data['last_name'] = $author[1];
			}
		}

		// Get the Contact record, creating it if we have user data to set.
		$contact = Contact::find_by_uid( $uid, $user_data );

		// Either we don't have a known user, or we are not tracking Anon users.
		if ( ! $contact ) {
			return;
		}

		if ( $this->anonymise_profiles ) {
			// Just provide link to comment parent, not the comment itself.
			$comment_link = get_permalink( $comment->comment_post_ID );
		} else {
			// Use a full link to the comment
			$comment_link = str_replace( home_url(), '', get_comment_link( $comment ) );
		}

		// add activity record of a comment
		Activity::record(
			$contact->uid,
			array(
				'url'           => $comment_link,
				'activity_type' => 'comment',
				'object_id'     => $id,
			)
		);
	}
}
