<?php

namespace PostenBringCheckout\admin\api\handlers;

use Exception;
use PostenBringCheckout\admin\bring\CheckoutApi;
use WP_REST_Request;
use WP_REST_Response;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Handles bookings
 */
class FeedbackHandler {
	/**
	 * Handles the feedback POST request.
	 *
	 * @param WP_REST_Request $request The REST request object.
	 *
	 * @return WP_REST_Response The REST response object.
	 * @throws Exception If there is an error during feedback submission.
	 */
	function send_feedback( WP_REST_Request $request ): WP_REST_Response {
		$json_data = json_decode( $request->get_body(), true );

		try {
			$success = CheckoutApi::get_instance()->sendFeedback( $json_data['category'], $json_data['message'], $json_data['email'] );
			if ( $success ) {
				return new WP_REST_Response( array(), 200 );
			} else {
				return new WP_REST_Response( 'Feedback submission failed.', 500 );
			}
		} catch ( Exception $e ) {
			return new WP_REST_Response( 'An error occurred: ' . esc_html($e->getMessage()), 500 );
		}
	}

	/**
	 * Handles deactivation feedback POST request.
	 *
	 * @param WP_REST_Request $request The REST request object.
	 *
	 * @return WP_REST_Response The REST response object.
	 * @throws Exception If there is an error during deactivation feedback submission.
	 */
	function deactivation_reason ( WP_REST_Request $request): WP_REST_Response {
		$json_data = $request->get_json_params();

		try {
			update_option( 'posten-bring-checkout-deactivation-reason', $json_data['reason'] ?? '' );
			update_option( 'posten-bring-checkout-deactivation-feedback', $json_data['feedback'] ?? '');

			return new WP_REST_Response( 'OK', 200 );
		} catch ( Exception $e ) {
			wc_get_logger()->warning( 'Error occurred while handling deactivation feedback: ' . esc_html($e->getMessage()), array( 'source' => 'posten-bring-checkout' ) );
			return new WP_REST_Response( 'An error occurred: ' . esc_html($e->getMessage()), 500 );
		}
	}
}
