<?php
/**
 * Contact preview and edit page template
 *
 * @link       https://personalizewp.com/
 * @since      3.2.0 Merged into PWP
 * @since      1.0.0
 *
 * @package    PersonalizeWP
 * @subpackage PersonalizeWP/Admin
 *
 * @var PersonalizeWP\Model\Contact $contact The instance of the Contact class.
 */

namespace PersonalizeWP\Admin;

use PersonalizeWP\Admin\PageContacts;
use PersonalizeWP\Admin\ListTableActivity;
use PersonalizeWP\Admin\Utils;

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

/**
 * Utility to display field data in table split across two tables.
 *
 * @param array  $fields      Array of fields each with 'label' and 'value'
 * @param string $table_class Class to add to the <table> element. Optional
 */
function display_as_split_table( $fields, $table_class = '' ) {
	if ( empty( $fields ) ) {
		return;
	}
	?>
	<table class="<?php echo esc_attr( $table_class ); ?>">
		<tbody>
		<?php
		$num  = 0;
		$half = intval( ceil( count( $fields ) / 2 ) );
		foreach ( $fields as $field_data ) :
			// Track current field num.
			++$num;
			?>
			<tr>
				<th scope="row"><?php echo esc_html( $field_data['label'] ); ?></th>
				<td>
					<?php
					// Sanitise, but allow links (email, url etc).
					echo wp_kses(
						$field_data['value'],
						[
							'a' => [
								'href'       => [],
								'aria-label' => [],
							],
						]
					);
					?>
				</td>
			</tr>
			<?php
			// Display base fields in 2 columns.
			if ( 1 < $half && $num === $half ) :
				?>
		</tbody>
	</table>
	<table class="<?php echo esc_attr( $table_class ); ?>">
		<tbody>
				<?php
			endif;
		endforeach;
		?>
		</tbody>
	</table>
	<?php
}
?>

	<main class="section entity-panel">
		<?php require_once plugin_dir_path( __DIR__ ) . '/_other/contacts-nav.php'; ?>

		<nav class="entity-panel__nav">
			<a href="<?php echo esc_url( admin_url( PageContacts::$index_url ) ); ?>" class="back">&larr; <?php esc_html_e( 'Back', 'personalizewp' ); ?></a>
		</nav>

		<section class="entity-panel__preview">
			<header class="entity-panel__header repel">
				<div class="sub-header repel">
					<div class="avatar">
						<?php
						echo get_avatar( $contact->email, 80, 'mystery', '', array( 'class' => 'avatar-img' ) );
						?>
					</div>
					<h2 class="visitor-name section-title">
						<?php
						$first_name = ! empty( $contact->first_name ) ? $contact->first_name : __( 'Anonymous', 'personalizewp' );
						$last_name  = ! empty( $contact->last_name ) ? $contact->last_name : __( 'User', 'personalizewp' );
						echo esc_html( trim( $first_name . ' ' . $last_name ) );
						?>
					</h2>
				</div>

				<ul class="context-links">
					<li><a class="contextual-link" href="<?php echo esc_url( wp_nonce_url( admin_url( PageContacts::$delete_url . $contact->ID ), 'delete-contact-' . $contact->ID ) ); ?>"
						data-show-modal="#deleteContactModal"><?php esc_html_e( 'Delete Visitor Profile', 'personalizewp' ); ?></a></li>
				</ul>
			</header>

			<div class="pwp-panel profile with-sidebar" data-direction="rtl">
				<div class="profile-fields">
					<?php
					// Collect the fields before grouping.
					$phone        = $contact->get_metadata( 'phone_number', true );
					$website      = $contact->get_metadata( 'website', true );
					$wp_user_id   = $contact->get_metadata( 'wp_user_id', true );
					$wp_user_data = false;
					if ( ! empty( $wp_user_id ) ) {
						$wp_user_data = get_userdata( $wp_user_id );
					}
					$user_role = implode( ', ', (array) $contact->get_metadata( 'wp_user_role', true ) );

					// Prep the base profile fields to display. Allow them to be filtered/reordered.
					$profile_fields = array(
						'email'        => array(
							'label' => __( 'Email', 'personalizewp' ),
							'value' => ! empty( $contact->email ) ? sprintf(
								'<a href="mailto:%1$s">%2$s</a>',
								esc_attr( $contact->email ),
								esc_html( $contact->email )
							) : '-',
						),
						'website'      => array(
							'label' => $contact->extended_fields['website'],
							'value' => ! empty( $website ) ? sprintf(
								'<a href="%1$s" target="_blank">%2$s</a>',
								esc_attr( set_url_scheme( $website, 'https' ) ),
								esc_html( $website )
							) : '-',
						),
						'first_seen'   => array(
							'label' => __( 'First Seen', 'personalizewp' ),
							'value' => esc_html( $contact->created ),
						),
						'last_seen'    => array(
							'label' => __( 'Last Seen', 'personalizewp' ),
							'value' => esc_html( $contact->last_seen ),
						),
						'phone_number' => array(
							'label' => $contact->extended_fields['phone_number'],
							'value' => ! empty( $phone ) ? sprintf(
								'<a href="tel:%1$s">%2$s</a>',
								esc_attr( $phone ),
								esc_html( $phone )
							) : '-',
						),
						'wp_user'      => array(
							'label' => __( 'WordPress User', 'personalizewp' ),
							'value' => (
								! empty( $wp_user_id ) && ! empty( $wp_user_data ) ? sprintf(
									'<a href="%1$s">%2$s</a>',
									esc_url( admin_url( 'user-edit.php?user_id=' . $wp_user_id ) ),
									esc_html( $wp_user_data->user_login )
								) : (
										! empty( $wp_user_id ) ?
										esc_html( $wp_user_id ) : '-'
									)
								),
						),
						'user_role'    => array(
							'label' => __( 'User Role', 'personalizewp' ),
							'value' => esc_html( $user_role ? $user_role : '-' ),
						),
					);
					/**
					 * Filter the base profile fields for contact display.
					 *
					 * @since 3.3.0
					 *
					 * @param array   $profile_fields Array of base profile sections with titles and rows.
					 * @param Contact $contact        The contact object.
					 */
					$profile_fields = apply_filters( 'personalizewp_contact_profile_fields', $profile_fields, $contact );
					?>
					<h3 class="subheading"><?php esc_html_e( 'Profile', 'personalizewp' ); ?></h3>
					<div class="cluster"><?php display_as_split_table( $profile_fields ); ?></div>

					<?php
					// Separate Contact meta fields into base/known fields and custom extended fields.
					$base_extended_fields   = array();
					$custom_extended_fields = array();
					foreach ( $contact->extended_fields as $field_key => $field_label ) {
						if ( str_starts_with( $field_key, 'custom_' ) ) {
							$custom_extended_fields[ $field_key ] = $field_label;
						} else {
							$base_extended_fields[ $field_key ] = $field_label;
						}
					}

					// Prep the display array, use location fields from extended fields.
					$display_location_fields = array();
					$location_field_keys     = array(
						'address_street',
						'address_line_2',
						'address_city',
						'address_state',
						'address_zipcode',
						'address_country',
					);
					$has_location_fields     = false;

					// Pre-process location fields, skip displaying any if none set.
					foreach ( $location_field_keys as $field_key ) {
						// Use labels from Contact class.
						$label = $contact->extended_fields[ $field_key ];
						if ( isset( $base_extended_fields[ $field_key ] ) ) {
							$value               = $contact->get_metadata( $field_key, true );
							$has_location_fields = true;
						}
						$display_location_fields[] = array(
							'label' => $label,
							'value' => esc_html( $value ? $value : '-' ),
						);
					}

					// Only show location fields if at least one is set.
					if ( $has_location_fields ) :
						?>
					<h3 class="subheading"><?php esc_html_e( 'Location', 'personalizewp' ); ?></h3>
					<div class="cluster"><?php display_as_split_table( $display_location_fields ); ?></div>
						<?php
					endif;
					?>

					<?php
					$consent        = $contact->get_metadata( 'marketing_consent', true );
					$consent_output = '-';
					// Is null when not set, so unknown
					if ( ! is_null( $consent ) ) :
						// Empty, or contents is zero.
						if ( empty( $consent ) || ( is_numeric( $consent ) && ! (bool) $consent ) ) :
							$consent_output = __( 'No', 'personalizewp' );
						elseif ( ! empty( $consent ) && is_numeric( $consent ) && (bool) $consent ) :
							// Non-empty and contents is not zero.
							$consent_output = __( 'Yes', 'personalizewp' );
						else :
							// Fallback to whatever was stored.
							$consent_output = $consent;
						endif;
					endif;
					$privacy        = $contact->get_metadata( 'privacy_policy', true );
					$privacy_output = '-';
					// Is null when not set, so unknown
					if ( ! is_null( $privacy ) ) :
						// Empty, or contents is zero.
						if ( empty( $privacy ) || ( is_numeric( $privacy ) && ! (bool) $privacy ) ) :
							$privacy_output = __( 'No', 'personalizewp' );
						elseif ( ! empty( $privacy ) && is_numeric( $privacy ) && (bool) $privacy ) :
							// Non-empty and contents is not zero.
							$privacy_output = __( 'Accepted', 'personalizewp' );
						else :
							// Fallback to whatever was stored.
							$privacy_output = $privacy;
						endif;
					endif;

					$display_marketing_fields = array(
						'consent' => array(
							'label' => __( 'Marketing Consent', 'personalizewp' ),
							'value' => $consent_output,
						),
						'privacy' => array(
							'label' => __( 'Privacy Policy', 'personalizewp' ),
							'value' => $privacy_output,
						),
					)
					?>
					<h3 class="subheading"><?php esc_html_e( 'Marketing Preferences', 'personalizewp' ); ?></h3>
					<div class="cluster"><?php display_as_split_table( $display_marketing_fields ); ?></div>

					<?php
					$excluded_fields   = array( 'phone_number', 'website', 'address_street', 'address_line_2', 'address_city', 'address_state', 'address_zipcode', 'address_country' );
					$other_base_fields = array_diff_key( $base_extended_fields, array_flip( $excluded_fields ) );
					if ( ! empty( $other_base_fields ) ) :
						// Ensure any other base fields not already outputted are displayed.
						$display_other_base_fields = array();
						foreach ( $other_base_fields as $name => $label ) {
							$field_value                 = $contact->get_metadata( $name, true );
							$display_other_base_fields[] = array(
								'label' => esc_html( $label ),
								'value' => $field_value ? $field_value : '-',
							);
						}
						?>
						<div class="cluster"><?php display_as_split_table( $display_other_base_fields, 'extended-profile-fields' ); ?></div>
						<?php
					endif;

					if ( ! empty( $custom_extended_fields ) ) :
						$display_custom_extended_fields = array();
						foreach ( $custom_extended_fields as $name => $label ) {
							$field_value                      = $contact->get_metadata( $name, true );
							$display_custom_extended_fields[] = array(
								'label' => esc_html( $label ),
								'value' => $field_value ? $field_value : '-',
							);
						}
						?>
						<h3 class="subheading"><?php esc_html_e( 'Custom Profile Fields', 'personalizewp' ); ?></h3>
						<div class="cluster"><?php display_as_split_table( $display_custom_extended_fields, 'custom-profile-fields' ); ?></div>
						<?php
					endif;
					?>
				</div>
				<div class="lead_score">
					<h3><?php esc_html_e( 'Lead Score', 'personalizewp' ); ?></h3>
					<p><?php echo esc_html( number_format_i18n( (int) $contact->lead_score, 0 ) ); ?></p>
				</div>
			</div>
		</section>

		<?php
		if ( 'production' !== wp_get_environment_type() ) :
			?>
			<section class="entity-panel__debug">
				<h2><?php esc_html_e( 'Unique Browser ID', 'personalizewp' ); ?></h2>
				<p><?php echo esc_html( $contact->uid ); ?></p>
			</section>
			<?php
		endif;
		?>

		<section class="entity-panel__segments">
			<header>
				<h2 class="pwp-panel__title mb-3"><?php esc_html_e( 'Segments', 'personalizewp' ); ?></h2>
			</header>

			<?php
			$segments = $contact->segments;
			if ( ! empty( $segments ) ) :
				?>
			<ul class="tag-list cluster">
				<?php foreach ( $segments as $segment ) : ?>
					<li>
						<a class="contextual-link " href="<?php echo esc_url( admin_url( PageSegments::$view_url . $segment->ID ) ); ?>">
							<?php echo esc_html( $segment->name ); ?>
						</a>
						<a class="trash" data-show-modal="#removeSegmentModal" href="<?php echo esc_url( wp_nonce_url( admin_url( PageContacts::$remove_contact_segment . $segment->ID . '&contact_id=' . $contact->ID ), 'remove-segment-' . $segment->ID . '-' . $contact->ID ) ); ?>" aria-label="<?php echo esc_attr_e( 'Remove visitor from segment', 'personalizewp' ); ?>">
							<?php Utils::svg_icon( 'cross' ); ?>
						</a>
					</li>
				<?php endforeach; ?>
			</ul>
				<?php
			else :
				printf(
					'<p>%s</p>',
					esc_html__( 'This Visitor Profile is not assigned to any segment.', 'personalizewp' )
				);
			endif;
			?>
		</section>

		<section class="entity-panel__activity">
			<header class="repel">
				<h2 class="pwp-panel__title"><?php esc_html_e( 'Events', 'personalizewp' ); ?></h2>
				<?php
				if ( ! empty( $wp_user_id ) ) :
					?>
					<ul class="context-links">
						<?php
						$export_link = admin_url(
							add_query_arg(
								array(
									'page'    => 'personalizewp/data-export',
									'user_id' => $wp_user_id,
								),
								'admin.php'
							)
						);
						?>
						<li><a class="contextual-link" href="<?php echo esc_url( $export_link ); ?>"><?php esc_html_e( 'Export Visitor Event Log', 'personalizewp' ); ?></a></li>
					</ul>
					<?php
				endif;
				?>
			</header>

			<form id="activities-filter" method="get" action="#activities-filter">
				<?php
				$contact_activity = new ListTableActivity();
				$contact_activity->prepare_items();
				$contact_activity->display();
				?>
			</form>
		</section>
	</main>

<?php
require_once __DIR__ . '/_modal-delete.php';
require_once __DIR__ . '/_modal-delete-activity.php';
require_once __DIR__ . '/_modal-remove-segment.php';
