<?php
/**
 * Twilio gateway.
 *
 * @package CartNinjaRecovery
 */

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

class CARTNINJA_Twilio_Gateway implements CARTNINJA_Gateway_Interface {

	public function send( $to, $message ) {
		$settings = get_option( 'cartninja_settings', array() );
		$twilio   = isset( $settings['twilio'] ) ? $settings['twilio'] : array();
		$sid      = isset( $twilio['account_sid'] ) ? sanitize_text_field( $twilio['account_sid'] ) : '';
		$token    = isset( $twilio['auth_token'] ) ? sanitize_text_field( $twilio['auth_token'] ) : '';
		$from     = isset( $twilio['from_phone'] ) ? sanitize_text_field( $twilio['from_phone'] ) : '';

		if ( empty( $sid ) || empty( $token ) || empty( $from ) ) {
			return array(
				'status'             => 'failed',
				'error_message'      => __( 'Twilio settings are incomplete.', 'cartninja-recovery-for-woocommerce' ),
				'gateway_message_id' => '',
			);
		}

		$response = wp_remote_post(
			sprintf( 'https://api.twilio.com/2010-04-01/Accounts/%s/Messages.json', rawurlencode( $sid ) ),
			array(
				'timeout' => 20,
				'headers' => array(
					'Authorization' => 'Basic ' . base64_encode( $sid . ':' . $token ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
				),
				'body'    => array(
					'To'   => $to,
					'From' => $from,
					'Body' => $message,
				),
			)
		);

		if ( is_wp_error( $response ) ) {
			return array(
				'status'             => 'failed',
				'error_message'      => $response->get_error_message(),
				'gateway_message_id' => '',
			);
		}

		$code = (int) wp_remote_retrieve_response_code( $response );
		$body = json_decode( wp_remote_retrieve_body( $response ), true );

		if ( $code < 200 || $code >= 300 ) {
			return array(
				'status'             => 'failed',
				'error_message'      => isset( $body['message'] ) ? sanitize_text_field( $body['message'] ) : __( 'Twilio request failed.', 'cartninja-recovery-for-woocommerce' ),
				'gateway_message_id' => isset( $body['sid'] ) ? sanitize_text_field( $body['sid'] ) : '',
			);
		}

		return array(
			'status'             => 'sent',
			'error_message'      => '',
			'gateway_message_id' => isset( $body['sid'] ) ? sanitize_text_field( $body['sid'] ) : '',
		);
	}
}
