<?php


/**
 * The file that defines all the custom SMS subscription REST API routes in the plugin
 *
 * @link       https://autoserve.io
 * @since      1.0.4
 *
 * @package    Messageflow
 * @subpackage Messageflow/includes
 */

/**
 * The custom SMS subscription REST API routes plugin class.
 *
 * @since      1.0.4
 * @package    Messageflow
 * @subpackage Messageflow/includes
 * @author     Autoserve <support@autoserve.io>
 */
class Messageflow_Sms_Subscription_Rest_Routes {

	private $utils;

	private $namespace;

	public function __construct( $utils ) {
		$this->utils     = $utils;
		$this->namespace = 'messageflow/v1';

		add_action( 'rest_api_init', array( $this, 'create_settings_rest_routes' ) );
	}

	// Register settings REST route
	public function create_settings_rest_routes() {
		register_rest_route( $this->namespace, '/sms-subscribe', array(
			'methods'             => 'GET',
			'callback'            => [ $this, 'get_sms_subscription_meta' ],
			'permission_callback' => function () {
				return current_user_can( 'can_call_messageflow_api' );
			},
			'args'                => array(
				'order-number' => array(
					'validate_callback' => function ( $param, $request, $key ) {
						return is_numeric( $param );
					}
				)
			)
		) );

		register_rest_route( $this->namespace, '/sms-subscribe', array(
			'methods'             => 'POST',
			'callback'            => [ $this, 'update_sms_subscription_meta' ],
			'permission_callback' => function () {
				return current_user_can( 'can_call_messageflow_api' );
			}
		) );
	}

	public function update_sms_subscription_meta( $req ) {
		$order_number  = $req['order-number'];

		if ( $order_number ) {
			$order = wc_get_order( $order_number );

			$currentStatus = $order->get_meta( 'messageflow_order_noti_is_subscribed' );

			if ( empty( $currentStatus ) ) {
				$order->update_meta_data( 'messageflow_order_noti_is_subscribed', 1 );
			} else {
				$order->delete_meta_data( 'messageflow_order_noti_is_subscribed' );
			}

			$order->save_meta_data();

			return rest_ensure_response( array(
				'status'  => 200,
				'message' => 'Order SMS subscription updated',
			) );
		} else {
			return new WP_Error( 'missing-argument', __( 'Missing arguments. Please check again.', 'messageflow' ), array(
				'status'          => 403,
			) );
		}
	}

	public function get_sms_subscription_meta( $req ) {
		$params       = $req->get_params();
		$order_number = $params['order-number'];

		if ( $order_number ) {
			$order        = wc_get_order( intval( $order_number ) );
			$is_subscribed = $order->get_meta( 'messageflow_order_noti_is_subscribed' );

			return rest_ensure_response( array(
				'status'        => 200,
				'message'       => 'SMS subscription status fetched successfully.',
				'is-subscribed' => $is_subscribed
			) );
		} else {
			return new WP_Error( 'missing-argument', __( 'Missing arguments. Please check again.', 'messageflow' ), array(
				'status'          => 403,
			) );
		}
	}
}
