<?php
/**
 * Shared cart action handlers for admin UI.
 *
 * @package EDD\Pro\CartRecovery\Admin\Emails
 * @copyright Copyright (c) 2026, Sandhills Development, LLC
 * @license https://opensource.org/licenses/gpl-2.0.php GNU Public License
 * @since 3.6.5
 */

namespace EDD\Pro\CartRecovery\Admin\Emails;

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

use EDD\Pro\CartRecovery\Database\Queries\RecoveryEmail;
use EDD\EventManagement\SubscriberInterface;
use EDD\Pro\CartRecovery\Traits\Debug;

/**
 * Centralises cart-related admin actions (bulk + AJAX).
 */
final class Actions implements SubscriberInterface {
	use Debug;

	/**
	 * Returns the subscribed events.
	 *
	 * @since 3.6.5
	 * @return array
	 */
	public static function get_subscribed_events(): array {
		return array(
			'load-download_page_edd-cart-recovery' => 'handle_bulk_actions',
		);
	}

	/**
	 * Process bulk actions for the cart recovery list table.
	 *
	 * This is hooked to 'load-download_page_edd-cart-recovery' which fires before
	 * the page is rendered, allowing us to process actions and redirect cleanly.
	 *
	 * @since 3.6.5
	 */
	public function handle_bulk_actions(): void {
		// Bail if this method was called directly.
		if ( 'load-download_page_edd-cart-recovery' !== current_action() ) {
			_doing_it_wrong( __METHOD__, 'This method is not meant to be called directly.', '3.6.5' );
			return;
		}

		// Check user capability.
		if ( ! current_user_can( 'manage_shop_settings' ) ) {
			return;
		}

		// Get action from either bulk action dropdown.
		$action = isset( $_REQUEST['action'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['action'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( '-1' === $action || empty( $action ) ) {
			$action = isset( $_REQUEST['action2'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['action2'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		}

		// Bail if no valid action.
		if ( 'delete' !== $action ) {
			return;
		}

		// Get cart IDs from request.
		$email_ids = isset( $_GET['email_ids'] ) ? wp_unslash( $_GET['email_ids'] ) : array(); // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized

		if ( ! is_array( $email_ids ) ) {
			$email_ids = array( $email_ids );
		}

		$email_ids = wp_parse_id_list( $email_ids );

		// Bail if no cart IDs.
		if ( empty( $email_ids ) ) {
			return;
		}

		// Verify nonce.
		check_admin_referer( 'bulk-edd_acr_emails' );

		// Process the action.
		$success = false;
		$count   = count( $email_ids );

		$success = $this->delete_emails( $email_ids );
		if ( $success ) {
			$message = sprintf(
				/* translators: %d: number of carts */
				_n( '%d email record deleted.', '%d email records deleted.', $count, 'easy-digital-downloads' ),
				$count
			);
			$this->add_admin_notice( $message, 'success' );
		} else {
			$this->add_admin_notice( __( 'Failed to delete email records.', 'easy-digital-downloads' ), 'error' );
		}

		// Redirect back to the list table.
		edd_redirect( wp_get_referer() );
	}

	/**
	 * Bulk helper: delete multiple carts using a single database query.
	 *
	 * @since 3.6.5
	 * @param array $email_ids The cart IDs.
	 * @return int The number of emails deleted.
	 */
	public function delete_emails( array $email_ids ): int {
		if ( empty( $email_ids ) ) {
			return false;
		}

		$query   = new RecoveryEmail();
		$deleted = 0;
		foreach ( $email_ids as $email_id ) {
			$deleted += $query->delete_item( $email_id );
		}

		return $deleted;
	}

	/**
	 * Add an admin notice using EDD's notice system.
	 *
	 * @since 3.6.5
	 * @param string $message The message to display.
	 * @param string $type    The notice type (success, error, warning, info).
	 * @return void
	 */
	private function add_admin_notice( string $message, string $type = 'success' ): void {
		EDD()->notices::add_transient_notice(
			'edd_acr_bulk_action',
			$message,
			$type
		);
	}
}
