<?php
/**
 * Unsubscribe reason capture and reporting.
 *
 * @package CartCue
 */

namespace CartCue;

defined( 'ABSPATH' ) || exit;

final class UnsubscribeReasons {

	/** @return array<string, string> */
	public static function reason_labels(): array {
		return [
			'not_interested' => __( 'I no longer want these emails', 'cartcue-sales-automation' ),
			'never_signed_up' => __( 'I never signed up for this list', 'cartcue-sales-automation' ),
			'too_frequent'   => __( 'Emails are too frequent', 'cartcue-sales-automation' ),
			'not_relevant'   => __( 'Content is not relevant to me', 'cartcue-sales-automation' ),
			'other'          => __( 'Other', 'cartcue-sales-automation' ),
		];
	}

	public static function is_valid_reason( string $reason ): bool {
		return array_key_exists( $reason, self::reason_labels() );
	}

	public static function save( string $email, string $reason, string $other_text = '', int $workflow_id = 0 ): void {
		$email = strtolower( trim( sanitize_email( $email ) ) );
		if ( ! is_email( $email ) || ! self::is_valid_reason( $reason ) ) {
			return;
		}

		global $wpdb;
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery
		$wpdb->insert(
			DB::unsubscribe_reasons(),
			[
				'email'        => $email,
				'reason'       => sanitize_key( $reason ),
				'other_text'   => 'other' === $reason ? sanitize_text_field( substr( $other_text, 0, 500 ) ) : '',
				'workflow_id'  => max( 0, $workflow_id ),
				'created_at'   => current_time( 'mysql' ),
			],
			[ '%s', '%s', '%s', '%d', '%s' ]
		);
	}

	/**
	 * @return array{reason: string, other_text: string, created_at: string}|null
	 */
	public static function get_for_email( string $email ): ?array {
		global $wpdb;
		$email = strtolower( trim( sanitize_email( $email ) ) );
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery
		$row = $wpdb->get_row(
			$wpdb->prepare(
				'SELECT reason, other_text, created_at FROM %i WHERE email = %s ORDER BY id DESC LIMIT 1',
				DB::unsubscribe_reasons(),
				$email
			),
			ARRAY_A
		);
		return is_array( $row ) ? $row : null;
	}

	/**
	 * @param array{reason: string, other_text?: string} $row
	 */
	public static function format_label( array $row ): string {
		$labels = self::reason_labels();
		$reason = (string) ( $row['reason'] ?? '' );
		$label  = $labels[ $reason ] ?? $reason;
		if ( 'other' === $reason && ! empty( $row['other_text'] ) ) {
			$label .= ': ' . (string) $row['other_text'];
		}
		return sprintf(
			/* translators: %s: unsubscribe reason */
			__( 'Unsubscribed — %s', 'cartcue-sales-automation' ),
			$label
		);
	}

	/**
	 * @return array<int, array{reason: string, count: int, label: string}>
	 */
	public static function get_aggregate( int $days = 90 ): array {
		global $wpdb;
		$days = max( 1, $days );
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery
		$rows = $wpdb->get_results(
			$wpdb->prepare(
				'SELECT reason, COUNT(*) AS cnt FROM %i
				 WHERE created_at >= DATE_SUB(NOW(), INTERVAL %d DAY)
				 GROUP BY reason ORDER BY cnt DESC',
				DB::unsubscribe_reasons(),
				$days
			),
			ARRAY_A
		) ?: [];

		$labels = self::reason_labels();
		$out    = [];
		foreach ( $rows as $row ) {
			$reason = (string) $row['reason'];
			$out[]  = [
				'reason' => $reason,
				'count'  => (int) $row['cnt'],
				'label'  => $labels[ $reason ] ?? $reason,
			];
		}
		return $out;
	}

	/**
	 * @return array<int, array{email: string, reason: string, other_text: string, created_at: string}>
	 */
	public static function get_recent( int $limit = 50 ): array {
		global $wpdb;
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery
		return $wpdb->get_results(
			$wpdb->prepare(
				'SELECT email, reason, other_text, created_at FROM %i ORDER BY created_at DESC LIMIT %d',
				DB::unsubscribe_reasons(),
				$limit
			),
			ARRAY_A
		) ?: [];
	}
}
