<?php

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

/**
 * The custom settings REST API routes plugin class.
 *
 * @since      1.0.4
 * @package    Messageflow
 * @subpackage Messageflow/includes
 * @author     Autoserve <support@autoserve.io>
 */
class Messageflow_Settings_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, '/settings', array(
			'methods'               => 'GET',
			'callback'              => [ $this, 'get_settings' ],
			'permission_callback'   => function() {
				return current_user_can( 'can_view_messageflow' );
			}
		) );

		register_rest_route( $this->namespace, '/settings', array(
			'methods'               => 'POST',
			'callback'              => [ $this, 'save_settings' ],
			'permission_callback'   => function() {
				return current_user_can( 'can_view_messageflow' );
			}
		) );
	}

	public function get_settings() {
		$option_prefix = 'messageflow-settings-';

		// General settings' Twilio credentials
		$account_sid = get_option( $option_prefix . 'account-sid' );
		$auth_token = get_option( $option_prefix . 'auth-token' );
		$from_phone = get_option( $option_prefix . 'from-phone' );

		// General settings' testing Twilio credentials
		$enable_test_mode = get_option( $option_prefix . 'enable-test-mode' );
		$test_account_sid = get_option( $option_prefix . 'test-account-sid' );
		$test_auth_token = get_option( $option_prefix . 'test-auth-token' );
		$test_from_phone = get_option( $option_prefix . 'test-from-phone' );

		// Store settings checkout default sms subscription
		$checkout_default_sms_subscription = get_option( $option_prefix . 'checkout-sms-subscription-default' );

		// Order notification settings
		$include_statuses = get_option( $option_prefix . 'include-statuses' );
		$default_message = get_option( $option_prefix . 'default-message' );

		// Permission settings
		$visibility_permission = get_option( $option_prefix . 'visibility-permission' );

		if ( ! empty( $notify_service_sid ) ) {
			delete_option( $option_prefix . 'notify-service-sid' );
		}

		$response = array(
			'account-sid'                           => ! empty( $account_sid ) ? $account_sid : '',
			'auth-token'                            => ! empty( $auth_token ) ? $auth_token : '',
			'from-phone'                            => ! empty( $from_phone ) ? $from_phone : '',
			'enable-test-mode'                      => ! empty( $enable_test_mode ) ? $enable_test_mode : '',
			'test-account-sid'                      => ! empty( $test_account_sid ) ? $test_account_sid : '',
			'test-auth-token'                       => ! empty( $test_auth_token ) ? $test_auth_token : '',
			'test-from-phone'                       => ! empty( $test_from_phone ) ? $test_from_phone : '',
			'checkout-sms-subscription-default'     => ! empty( $checkout_default_sms_subscription ) ? $checkout_default_sms_subscription : '',
			'include-statuses'                      => ! empty( $include_statuses ) ? $include_statuses : '',
			'default-message'                       => ! empty( $default_message ) ? $default_message : '',
			'visibility-permission'                 => ! empty( $visibility_permission ) ? $visibility_permission : '',
		);
		foreach ( array_keys( $this->utils->woocommerce_get_all_order_statuses() ) as $status_slug ) {
			$option_value = get_option( $option_prefix . $status_slug  );
			if ( empty( $option_value ) ) {
				$response[ $status_slug ] = '';
			} else {
				$response[ $status_slug ] = $option_value;
			}
		}
		return rest_ensure_response( $response );
	}

	public function save_settings( $req ) {
		$option_prefix = 'messageflow-settings-';
		$option_slugs = [
			'account-sid',
			'auth-token',
			'from-phone',
			'enable-test-mode',
			'test-account-sid',
			'test-auth-token',
			'test-from-phone',
			'include-statuses',
			'default-message',
			'visibility-permission',
			'checkout-sms-subscription-default'
		];
		$status_slugs = array_keys( $this->utils->woocommerce_get_all_order_statuses() );
		$option_slugs = array_merge( $option_slugs, $status_slugs );

		$saved_options = [];
		foreach ( $option_slugs as $option_slug ) {
			$req_data = $req[ $option_slug ];

			$saved_options[ $option_prefix . $option_slug ] = $req_data;
			if ( is_array( $req_data ) ) {
				update_option( $option_prefix . $option_slug,  $req_data );
			} else {
				update_option( $option_prefix . $option_slug, sanitize_text_field( $req_data ) );
			}
		}

		if ( count( $saved_options ) ) {
			return rest_ensure_response( array(
				'status'         => 200,
				'message'        => 'Update settings successfully!',
				'settings_saved' => $saved_options
			) );
		} else {
			return new WP_Error( 'missing-argument', __( 'There is no data passed to endpoint. Please check again.', 'messageflow' ), array(
				'status'          => 403,
			) );
		}
	}
}
