<?php
/**
 * Shared server-side validation for play save requests.
 *
 * @package CartCue\Admin
 */

namespace CartCue\Admin;

use CartCue\Actions\GhostAction;
use CartCue\Plugin;
use CartCue\Triggers\GhostTrigger;

defined( 'ABSPATH' ) || exit;

final class PlaySaveGuard {

	public static function sanitize_status( $raw ): string {
		$status = sanitize_key( wp_unslash( (string) $raw ) );
		return in_array( $status, [ 'active', 'paused' ], true ) ? $status : 'active';
	}

	public static function reject_ghost_trigger( Plugin $plugin, string $trigger_slug ): void {
		if ( $plugin->is_pro() ) {
			return;
		}
		$trigger = $plugin->get_trigger( $trigger_slug );
		if ( ! $trigger instanceof GhostTrigger ) {
			return;
		}
		wp_die(
			esc_html__( 'Pro-only triggers cannot be saved on the free plan. Choose a free trigger or upgrade to CartCue Pro.', 'cartcue-sales-automation' ),
			esc_html__( 'Cannot save play', 'cartcue-sales-automation' ),
			[ 'response' => 403, 'back_link' => true ]
		);
	}

	/**
	 * Drop any Pro-only (ghost) actions from a submitted action list on free.
	 * Ghosts can't be selected in the UI, but a crafted POST could include one.
	 *
	 * @param array<int,array<string,mixed>> $actions
	 * @return array<int,array<string,mixed>>
	 */
	public static function strip_ghost_actions( Plugin $plugin, array $actions ): array {
		if ( $plugin->is_pro() ) {
			return $actions;
		}
		return array_values( array_filter(
			$actions,
			static function ( $a ) use ( $plugin ) {
				$obj = $plugin->get_action( (string) ( $a['type'] ?? '' ) );
				return ! $obj instanceof GhostAction;
			}
		) );
	}

	public static function redirect_if_active_limit( Plugin $plugin, string $status, int $play_id ): void {
		if ( 'active' !== $status || $plugin->can_activate_more_plays( $play_id ) ) {
			return;
		}
		$redirect_args = [
			'page'         => 'cartcue',
			'active_limit' => '1',
		];
		if ( $play_id ) {
			$redirect_args['action'] = 'edit';
			$redirect_args['id']     = $play_id;
		} else {
			$redirect_args['action'] = 'new';
		}
		wp_safe_redirect( add_query_arg( $redirect_args, admin_url( 'admin.php' ) ) );
		exit;
	}
}
