<?php
/**
 * Deactivation feedback (Plugins screen) and api.maca.se reporting.
 *
 * @package MacaHold
 */

defined( 'ABSPATH' ) || exit;

require_once MACA_HOLD_PATH . 'includes/maca-api.php';

/**
 * Allowed deactivation feedback reason keys.
 *
 * @return array<string, string>
 */
function maca_hold_deactivation_feedback_reasons() {
	return array(
		'missing_feature'        => __( 'Missing a feature I need', 'maca-hold' ),
		'hard_to_use'            => __( 'Too difficult to set up or use', 'maca-hold' ),
		'bug'                    => __( 'Something is broken or not working', 'maca-hold' ),
		'maintenance_not_working' => __( 'Maintenance mode or bypass is not working well', 'maca-hold' ),
		'switching'              => __( 'Switching to another solution', 'maca-hold' ),
		'temporary'              => __( 'Only needed temporarily / testing', 'maca-hold' ),
		'other'                  => __( 'Other', 'maca-hold' ),
	);
}

/**
 * English reason labels for API telemetry.
 *
 * @return array<string, string>
 */
function maca_hold_deactivation_feedback_api_labels() {
	return array(
		'missing_feature'        => 'Missing a feature I need',
		'hard_to_use'            => 'Too difficult to set up or use',
		'bug'                    => 'Something is broken or not working',
		'maintenance_not_working' => 'Maintenance mode or bypass is not working well',
		'switching'              => 'Switching to another solution',
		'temporary'              => 'Only needed temporarily / testing',
		'other'                  => 'Other',
	);
}

/**
 * Handle AJAX deactivation report before redirect to deactivate URL.
 *
 * @return void
 */
function maca_hold_handle_deactivation_feedback() {
	check_ajax_referer( 'maca_hold_deactivation_feedback', 'nonce' );

	if ( ! current_user_can( 'activate_plugins' ) ) {
		wp_send_json_error( array( 'message' => 'Forbidden' ), 403 );
	}

	$reasons = maca_hold_deactivation_feedback_api_labels();
	$reason  = isset( $_POST['reason'] ) ? sanitize_key( wp_unslash( $_POST['reason'] ) ) : '';
	$details = isset( $_POST['details'] ) ? sanitize_textarea_field( wp_unslash( $_POST['details'] ) ) : '';
	$extra   = array();

	if ( '' !== $reason && isset( $reasons[ $reason ] ) ) {
		$extra['reason']       = $reason;
		$extra['reason_label'] = $reasons[ $reason ];
		if ( '' !== $details ) {
			$extra['details'] = $details;
		}
	}

	maca_hold_api_send_event( 'deactivated', $extra, true );
	maca_hold_api_mark_deactivated_reported();

	wp_send_json_success();
}

add_action( 'wp_ajax_maca_hold_deactivation_feedback', 'maca_hold_handle_deactivation_feedback' );
