<?php
/**
 * BuildFeatures — wires v1.4+ UX features into CartCue admin.
 *
 * @package CartCue\Admin
 */

namespace CartCue\Admin;

use CartCue\DB;
use CartCue\Plugin;
use CartCue\RevenueForecast;

defined( 'ABSPATH' ) || exit;

class BuildFeatures {

	private Plugin $plugin;

	public function __construct( Plugin $plugin ) {
		$this->plugin = $plugin;

		add_action( 'admin_enqueue_scripts', [ $this, 'enqueue' ], 20 );
		add_action( 'wp_ajax_cartcue_undo_delete_play', [ $this, 'ajax_undo_delete_play' ] );
		add_action( 'wp_ajax_cartcue_first_activation_seen', [ $this, 'ajax_first_activation_seen' ] );
		add_action( 'admin_post_cartcue_delete_play', [ $this, 'capture_before_delete' ], 9 );
		add_filter( 'cartcue_admin_localize', [ $this, 'localize' ], 10, 2 );
	}

	public function enqueue( string $hook ): void {
		if ( false === strpos( $hook, 'cartcue' ) ) {
			return;
		}

		$base_url = defined( 'CARTCUE_PLUGIN_URL' ) ? CARTCUE_PLUGIN_URL : plugin_dir_url( CARTCUE_PLUGIN_FILE );
		$ver      = defined( 'CARTCUE_VERSION' ) ? CARTCUE_VERSION : '1.0.0';

		wp_enqueue_style(
			'cartcue-build-features',
			$base_url . 'assets/css/build-features.css',
			[ 'cartcue-admin' ],
			$ver
		);

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$page   = sanitize_key( $_GET['page'] ?? '' );
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$action = sanitize_key( $_GET['action'] ?? '' );

		wp_enqueue_script(
			'cartcue-undo-bar',
			$base_url . 'assets/js/undo-bar.js',
			[ 'cartcue-admin', 'jquery' ],
			$ver,
			true
		);

		$is_play_editor = 'cartcue' === $page && in_array( $action, [ 'new', 'edit' ], true );
		$is_list        = 'cartcue' === $page && ( '' === $action || 'list' === $action );
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$just_activated = isset( $_GET['ap_activated'] );

		if ( $is_play_editor ) {
			wp_enqueue_script(
				'cartcue-live-preview',
				$base_url . 'assets/js/live-preview.js',
				[ 'cartcue-admin', 'jquery' ],
				$ver,
				true
			);
			wp_enqueue_script(
				'cartcue-audience-estimate',
				$base_url . 'assets/js/audience-estimate.js',
				[ 'cartcue-admin', 'jquery' ],
				$ver,
				true
			);
			wp_enqueue_script(
				'cartcue-trigger-recommendation',
				$base_url . 'assets/js/trigger-recommendation.js',
				[ 'cartcue-admin', 'jquery' ],
				$ver,
				true
			);

			if ( $this->is_unified_editor() ) {
				wp_enqueue_script(
					'cartcue-play-edit-unified',
					$base_url . 'assets/js/play-edit-unified.js',
					[ 'cartcue-admin', 'cartcue-play-ux', 'jquery' ],
					$ver,
					true
				);
			}
		}

		if ( $is_list && $just_activated ) {
			wp_enqueue_script(
				'cartcue-confetti',
				$base_url . 'assets/js/confetti-celebrate.js',
				[],
				$ver,
				true
			);
		}

		$inline = sprintf(
			'(function(){window.cartcueAdmin = window.cartcueAdmin || {}; window.cartcueAdmin.buildFeatures = %s;})();',
			wp_json_encode( $this->config() )
		);
		wp_add_inline_script( 'cartcue-admin', $inline, 'after' );
	}

	private function is_unified_editor(): bool {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$automation_type = sanitize_key( wp_unslash( $_GET['automation_type'] ?? 'event' ) );
		if ( 'campaign' === $automation_type ) {
			return false;
		}
		return 'unified' === apply_filters( 'cartcue_play_editor_view', 'unified' );
	}

	private function config(): array {
		return [
			'undoNonce'            => wp_create_nonce( 'cartcue_undo_delete' ),
			'firstActSeenNonce'    => wp_create_nonce( 'cartcue_first_activation_seen' ),
			'firstActivationShown' => (bool) get_user_meta(
				get_current_user_id(),
				'cartcue_first_activation_seen',
				true
			),
			'forecast'             => RevenueForecast::for_all_recipes(),
			'activation'           => $this->activation_context(),
			'showRecommendation'   => $this->should_show_trigger_recommendation(),
			'strings'              => [
				'previewLoading'    => __( 'Rendering…', 'cartcue-sales-automation' ),
				'previewEmpty'      => __( 'Start typing — your email shows up here in real time.', 'cartcue-sales-automation' ),
				'previewShow'       => __( 'Show live preview', 'cartcue-sales-automation' ),
				'previewHide'       => __( 'Hide live preview', 'cartcue-sales-automation' ),
				'audienceLoading'   => __( 'Counting…', 'cartcue-sales-automation' ),
				'audienceZero'      => __( 'No customers match right now. Loosen your filters?', 'cartcue-sales-automation' ),
				/* translators: %s: audience count */
				'audienceMany'      => __( '%s match today', 'cartcue-sales-automation' ),
				/* translators: %s: sample customer names */
				'audienceSample'    => __( 'Including %s', 'cartcue-sales-automation' ),
				'undoLabel'         => __( 'Undo', 'cartcue-sales-automation' ),
				'undoDeleted'       => __( 'Automation removed.', 'cartcue-sales-automation' ),
				'undoRestored'      => __( 'Restored.', 'cartcue-sales-automation' ),
				'undoFailed'        => __( 'Could not undo — sorry.', 'cartcue-sales-automation' ),
				'recommendTitle'    => __( 'Not sure where to start?', 'cartcue-sales-automation' ),
				'recommendBody'     => __( 'Most stores start with Cart Abandoned — it recovers the most revenue.', 'cartcue-sales-automation' ),
				'recommendCta'      => __( 'Use Cart Abandoned →', 'cartcue-sales-automation' ),
				'celebrateTitle'    => __( "You're live. 🎉", 'cartcue-sales-automation' ),
				/* translators: %s: estimated monthly revenue */
				'celebrateForecast' => __( 'Stores like yours typically recover %s/month with this automation.', 'cartcue-sales-automation' ),
				'celebrateTruth'    => __( "We'll track real revenue as it happens — no inflated numbers, just what your store actually recovered.", 'cartcue-sales-automation' ),
				'celebrateClose'    => __( 'Show me the dashboard', 'cartcue-sales-automation' ),
			],
		];
	}

	private function activation_context(): array {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( ! isset( $_GET['ap_activated'] ) ) {
			return [
				'playName'    => '',
				'triggerSlug' => '',
			];
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$highlight_id = absint( $_GET['cartcue_highlight'] ?? 0 );
		if ( ! $highlight_id ) {
			// phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$maybe = absint( wp_unslash( $_GET['ap_activated'] ?? '' ) );
			if ( $maybe > 1 ) {
				$highlight_id = $maybe;
			}
		}

		if ( ! $highlight_id ) {
			return [
				'playName'    => '',
				'triggerSlug' => '',
			];
		}

		global $wpdb;
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery
		$row = $wpdb->get_row(
			$wpdb->prepare(
				'SELECT name, trigger_slug FROM %i WHERE id = %d',
				DB::workflows(),
				$highlight_id
			),
			ARRAY_A
		);

		if ( ! $row ) {
			return [
				'playName'    => '',
				'triggerSlug' => '',
			];
		}

		return [
			'playName'    => (string) ( $row['name'] ?? '' ),
			'triggerSlug' => (string) ( $row['trigger_slug'] ?? '' ),
		];
	}

	private function should_show_trigger_recommendation(): bool {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( 'cartcue' !== sanitize_key( $_GET['page'] ?? '' ) ) {
			return false;
		}
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( 'new' !== sanitize_key( $_GET['action'] ?? '' ) ) {
			return false;
		}
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( ! empty( $_GET['recipe'] ) ) {
			return false;
		}
		return $this->is_unified_editor();
	}

	public function capture_before_delete(): void {
		// phpcs:ignore WordPress.Security.NonceVerification.Missing
		$id = absint( $_POST['id'] ?? $_GET['id'] ?? 0 );
		if ( ! $id ) {
			return;
		}
		check_admin_referer( 'cartcue_delete_' . $id );
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			return;
		}

		global $wpdb;
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery
		$row = $wpdb->get_row(
			$wpdb->prepare( 'SELECT * FROM %i WHERE id = %d', DB::workflows(), $id ),
			ARRAY_A
		);
		if ( ! $row ) {
			return;
		}

		$key = self::undo_key( $id, get_current_user_id() );
		set_transient( $key, $row, 60 );

		add_filter(
			'wp_redirect',
			static function ( $location ) use ( $id ) {
				return add_query_arg( 'cartcue_undo_id', $id, $location );
			},
			10
		);
	}

	public function ajax_undo_delete_play(): void {
		check_ajax_referer( 'cartcue_undo_delete', 'nonce' );
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( [ 'msg' => __( 'Permission denied.', 'cartcue-sales-automation' ) ], 403 );
		}

		$id  = absint( wp_unslash( $_POST['id'] ?? 0 ) );
		$key = self::undo_key( $id, get_current_user_id() );
		$row = get_transient( $key );

		if ( ! $row || ! is_array( $row ) ) {
			wp_send_json_error( [ 'msg' => __( 'Undo window expired.', 'cartcue-sales-automation' ) ] );
		}

		global $wpdb;
		unset( $row['id'] );
		$row['status']     = 'paused';
		$row['updated_at'] = current_time( 'mysql' );

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery
		$ok = $wpdb->insert( DB::workflows(), $row );
		if ( ! $ok ) {
			wp_send_json_error( [ 'msg' => __( 'Could not restore.', 'cartcue-sales-automation' ) ] );
		}

		delete_transient( $key );
		Plugin::bust_play_count_cache();

		wp_send_json_success(
			[
				'restored_id' => (int) $wpdb->insert_id,
				'name'        => (string) ( $row['name'] ?? '' ),
			]
		);
	}

	public function ajax_first_activation_seen(): void {
		check_ajax_referer( 'cartcue_first_activation_seen', 'nonce' );
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( null, 403 );
		}
		update_user_meta( get_current_user_id(), 'cartcue_first_activation_seen', 1 );
		wp_send_json_success();
	}

	/**
	 * @param array<string,mixed> $localize
	 * @return array<string,mixed>
	 */
	public function localize( array $localize, string $context ): array {
		return $localize;
	}

	private static function undo_key( int $id, int $user_id ): string {
		return 'cartcue_undo_play_' . $user_id . '_' . $id;
	}
}
