<?php
/**
 * Dismissal AJAX handler
 *
 * Handles dismissal of the review request and premium upsell sidebar boxes.
 *
 * @package Relatedly\Admin\Ajax
 * @since   2.0.0
 */

namespace Relatedly\Admin\Ajax;

defined( 'ABSPATH' ) || exit;

/**
 * Handles dismissal requests for admin sidebar boxes.
 *
 * @since 2.0.0
 */
class Dismissal {

	/**
	 * Register the dismissal AJAX action.
	 *
	 * @since 2.0.0
	 */
	public function init_hooks(): void {
		add_action( 'wp_ajax_relatedly_dismiss_box', [ $this, 'handle' ] );
	}

	/**
	 * Process a dismissal request.
	 *
	 * @since 2.0.0
	 */
	public function handle(): void {
		check_ajax_referer( 'relatedly_settings', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( [ 'message' => __( 'Permission denied.', 'relatedly' ) ] );
		}

		$box  = sanitize_key( $_POST['box'] ?? '' );
		$type = sanitize_key( $_POST['type'] ?? 'permanent' );

		$allowed = [ 'review', 'premium' ];
		if ( ! in_array( $box, $allowed, true ) ) {
			wp_send_json_error( [ 'message' => __( 'Invalid box.', 'relatedly' ) ] );
		}

		$option_key = 'relatedly_' . $box . '_dismissed';

		if ( 'temporary' === $type ) {
			// Dismiss for 30 days.
			update_option( $option_key, time() + ( 30 * DAY_IN_SECONDS ) );
		} else {
			update_option( $option_key, 'permanent' );
		}

		wp_send_json_success();
	}
}
