<?php

/**
 * The class that contains all Woocommerce hooks and methods
 *
 * @link       https://autoserve.io
 * @since      1.0.4
 *
 * @package    Messageflow
 * @subpackage Messageflow/includes
 */

/**
 * The class that contains all Woocommerce hooks and methods
 *
 * @since      1.0.4
 * @package    Messageflow
 * @subpackage Messageflow/includes
 * @author     Autoserve <support@autoserve.io>
 */
class Messageflow_Woocommerce {
	/**
	 * The helper functions.
	 *
	 * @since   1.0.4
	 * @access  private
	 * @var     string $utils The helper functions of this plugin
	 */
	private $utils;

	/**
	 * MessageFlow API functions.
	 *
	 * @since   1.1.2.2
	 * @access  private
	 * @var     string      $utils      The helper functions of this plugin
	 */
	private $api;

	public function __construct( $utils, $api ) {
		$this->utils = $utils;
        $this->api = $api;

		add_action( 'woocommerce_before_order_notes', array( $this, 'action_woocommerce_sms_subscription_checkbox' ) );
		add_action( 'woocommerce_checkout_update_order_meta', array(
			$this,
			'action_woocommerce_sms_subscription_order_meta'
		) );
		add_action( 'woocommerce_init', array( $this, 'action_woocommerce_init' ) );
	}

	public function action_woocommerce_init() {
		$order_statuses = $this->utils->woocommerce_get_all_order_statuses();

		foreach ( array_keys( $order_statuses ) as $status ) {
			add_action( 'woocommerce_order_status_' . $status, array( $this, 'send_admin_order_noti' ) );
		}
	}

	// Function to handle send order notification and add order
	public function handle_sending_order_noti( $account_sid, $auth_token, $phone_number, $billing_phone, $message, $order ) {
		$user_id = get_option( 'messageflow-user-id' );

		$is_valid_account = $this->api->check_account_status( $user_id );

		if ( $is_valid_account ) {
			if ( $account_sid && $auth_token && $phone_number ) {
				$response = $this->utils->twilio_send_programmable_sms( $account_sid, $auth_token, $phone_number, $billing_phone, $message );

				if ( ! is_wp_error( $response ) ) {
					$response_body = json_decode( wp_remote_retrieve_body( $response ) );
				}

				if ( $response_body->messages[0]->status === 'success' ) {
					$private_note_log = '<b>MessageFlow SMS Notification</b><br />' . '<b>To:</b> ' . $billing_phone . '<br /><b>Message:</b> ' . $message . '<br /><b>Status:</b> <span style=\'color: green;\'>Sent</span>';
				} else {
					$private_note_log = '<b>MessageFlow SMS Notification</b><br />' . '<b>To:</b> ' . $billing_phone . '<br /><b>Message:</b> ' . $message . '<br /><b>Status:</b> <span style=\'color: red;\'>Failed</span>';
				}
				$order->add_order_note( $private_note_log );
			} else {
				$order->add_order_note( '<b>Missing Twilio credentials. Please add Twilio credentials in MessageFlow settings page!</b>' );
			}
		} else {
				$order->add_order_note( '<b>We are unable to proceed with your notification request for the moment due to your account not being in good standing.</b> <a href="https://app.messageflow.co" target="_blank" rel="noreferrer">Log in</a>' );
		}
	}

	// Replace the variable in the message with the correct data
	public function replace_variables( $message, $order ) {
		$is_shipment_tracking_enabled = $this->utils->woocommerce_is_shipment_tracking_enabled();

		$replacements = array(
			'{{Shop Name}}'         => $this->utils->get_site_name(),
			'{{Order ID}}'          => $order->get_id(),
			'{{Product Count}}'     => $order->get_item_count(),
			'{{Order Total Value}}' => $order->get_total(),
			'{{Order Status}}'      => ucfirst( join( ' ', explode( '-', $order->get_status() ) ) ),
			'{{Shipping Carrier}}'  => $is_shipment_tracking_enabled && $order->get_meta( '_wc_shipment_tracking_items' )
				? end( $order->get_meta( '_wc_shipment_tracking_items' ) )['tracking_provider']
				: null,
			'{{Shipping Method}}'   => $order->get_shipping_method(),
			'{{Tracking Number}}'   => $is_shipment_tracking_enabled && $order->get_meta( '_wc_shipment_tracking_items' )
				? end( $order->get_meta( '_wc_shipment_tracking_items' ) )['tracking_number']
				: null,
			'{{Full Name}}'         => $order->get_formatted_billing_full_name(),
			'{{First Name}}'        => $order->get_billing_first_name( 'edit' ),
			'{{Last Name}}'         => $order->get_billing_last_name( 'edit' ),
		);

		$replacement_variables = array_keys( $replacements );

		foreach ( $replacement_variables as $variable ) {
			if ( strpos( $message, $variable ) && strpos( $message, $variable ) >= 0 && ! $replacements[ $variable ] ) {
				return false;
			}
		}

		return str_replace( $replacement_variables, $replacements, $message );
	}

	// Woocommerce order status changed action callback
	public function send_admin_order_noti( $order_id ) {
		$order         = wc_get_order( $order_id );
		$billing_phone = $order->get_billing_phone();
		$is_subscribed = $order->get_meta( 'messageflow_order_noti_is_subscribed' );

		if ( ! empty( $is_subscribed ) && $billing_phone ) {
			$included_statuses = get_option( 'messageflow-settings-include-statuses' );

			$status = $order->get_status();

			if ( in_array( $status, $included_statuses ) ) {
				$is_test_mode_enabled = get_option( 'messageflow-settings-enable-test-mode' );
				$account_sid          = $is_test_mode_enabled === 'true'
					? get_option( 'messageflow-settings-test-account-sid' )
					: get_option( 'messageflow-settings-account-sid' );
				$auth_token           = $is_test_mode_enabled === 'true'
					? get_option( 'messageflow-settings-test-auth-token' )
					: get_option( 'messageflow-settings-auth-token' );
				$phone_number         = $is_test_mode_enabled === 'true'
					? get_option( 'messageflow-settings-test-from-phone' )
					: get_option( 'messageflow-settings-from-phone' );

				$new_status_message = $this->replace_variables( get_option( 'messageflow-settings-' . $status ), $order );
				if ( ! $new_status_message ) {
					$new_status_message = $this->replace_variables( get_option( 'messageflow-settings-default-message' ), $order );
				}
				if ( $new_status_message ) {
					$this->handle_sending_order_noti( $account_sid, $auth_token, $phone_number, $billing_phone, $new_status_message, $order );
				}
			}
		}
	}

	// Woocommerce checkout order subscription
	public function action_woocommerce_sms_subscription_checkbox( $checkout ) {
		?>
        <style>
            .sms-subscription__checkbox input {
                appearance: auto !important;
            }

            .sms-subscription__checkbox input[type=checkbox] {
                display: inline-block !important;
            }
        </style>
        <div class="sms-subscription__checkbox">
			<?php
			woocommerce_form_field( 'sms-subscription', array(
				'type'    => 'checkbox',
				'label'   => __( 'Receive update on your order with SMS notification', 'messageflow' ),
				'checked' => 'checked',
				'default' => 1
			), $checkout->get_value( 'sms-subscription' ) );
			?>
        </div>
		<?php
	}

	// Update the order meta with field value
	public function action_woocommerce_sms_subscription_order_meta( $order_id ) {
		$order = wc_get_order( $order_id );
		if ( $_POST['sms-subscription'] ) {
			$order->update_meta_data( 'messageflow_order_noti_is_subscribed', 1 );
		}
		$order->save();
	}
}
