<?php
/**
 * Deactivation Feedback Controller
 *
 * Handles AJAX submission of deactivation feedback.
 *
 * @package    MOMCS_Sync
 * @subpackage MOMCS_Sync/includes/common/controllers
 * @author     miniOrange
 */

declare(strict_types=1);

namespace MOMCS_Sync\Includes\Common\Controllers;

use MOMCS_Sync\Includes\Common\Constants\Plugin_Constants;
use MOMCS_Sync\Includes\Common\Handlers\Deactivation_Feedback_Handler;
use MOMCS_Sync\Includes\Common\Utils\Utils;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class Deactivation_Feedback_Controller
 */
class Deactivation_Feedback_Controller {
	/**
	 * Handle AJAX submission for deactivation feedback.
	 *
	 * @return void
	 */
	public static function handle_submission(): void {
		check_ajax_referer( Plugin_Constants::NONCE_MAIN, 'nonce' );

		if ( ! current_user_can( 'manage_options' ) && ! current_user_can( 'activate_plugins' ) ) {
			wp_send_json_error( array( 'message' => __( 'Permission denied.', 'multi-channel-for-woocommerce' ) ) );
		}

		if ( Utils::is_premium_plan() ) {
			wp_send_json_error( array( 'message' => __( 'Feedback is available only for free plan users.', 'multi-channel-for-woocommerce' ) ) );
		}

		$reason  = isset( $_POST['reason'] ) ? sanitize_key( wp_unslash( $_POST['reason'] ) ) : '';
		$details = isset( $_POST['details'] ) ? sanitize_textarea_field( wp_unslash( $_POST['details'] ) ) : '';
		$email   = isset( $_POST['email'] ) ? sanitize_email( wp_unslash( $_POST['email'] ) ) : '';

		if ( '' === $reason ) {
			wp_send_json_error( array( 'message' => __( 'Please select a reason.', 'multi-channel-for-woocommerce' ) ) );
		}

		if ( '' !== $email && ! is_email( $email ) ) {
			wp_send_json_error( array( 'message' => __( 'Please enter a valid email address.', 'multi-channel-for-woocommerce' ) ) );
		}

		$handler = new Deactivation_Feedback_Handler();
		$result  = $handler->submit_feedback( $reason, $details, $email );

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( array( 'message' => $result->get_error_message() ) );
		}

		wp_send_json_success( $result );
	}
}
