<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class WPC_SMS_Notification {
	public function __construct() {
		add_action( 'wpc_add_sms_notification', array( $this, 'wpc_notification_hook' ), 10 );
		add_action( 'wpc_add_sms_shipment_history', array( $this, 'wpc_notification_hook' ), 10 );
		add_filter( 'wp_mail_content_type', array( $this, 'wpcargo_set_content_type_sms' ) );
	}
	public function wpc_notification_hook( $post_id ) {
		$options = get_option('wpcargo_sms_settings');
		if(!empty($options['wpcargo_active_sms'])) {

			$current_status	= isset($_REQUEST['status']) ? $_REQUEST['status'] : '';
			$last_status 	= get_option('wpcargo_status_req');
			$wpcargo_tn		= get_the_title($post_id);
			$shipper_email  = get_post_meta($post_id, 'wpcargo_shipper_email', true);
			$receiver_email = get_post_meta($post_id, 'wpcargo_receiver_email', true);
			$shipper_phone  = get_post_meta($post_id, 'wpcargo_shipper_phone', true);
			$receiver_phone = get_post_meta($post_id, 'wpcargo_receiver_phone', true);
			$shipper_name   = get_post_meta($post_id, 'wpcargo_shipper_name', true);
			$receiver_name  = get_post_meta($post_id, 'wpcargo_receiver_name', true);
			$status         = get_post_meta($post_id, 'status', true);	
			$location       = get_post_meta($post_id, 'location', true);	
			$site_name      = get_bloginfo('name');	
			$site_url      	= get_bloginfo('url');	
			$admin_email    = get_option('admin_email');
			
			if( $current_status != $last_status || $current_status != $status ) {
				$str_find       = array_keys( wpcargo_email_shortcodes_list() );
				$str_replce     = wpcargo_email_replace_shortcodes_list( $post_id );
				
				$api_username = $options['wpcargo_api_username'];
				$api_password = $options['wpcargo_api_password'];
				$sender_id = str_replace($str_find, $str_replce, $options['wpcargo_mail_sender_id']);	
				$send_sms_to = str_replace($str_find, $str_replce, $options['wpcargo_send_to_message']);		
				$sms_message = str_replace($str_find, $str_replce, $options['wpcargo_sms_message']);

				if( $options['wpcargo_choose_sms_gateway'] == 'one-way-sms' ) {
					$send_this = $this->wpcargo_get_onewaysms_access($api_username, $api_password, $sender_id, $send_sms_to, $sms_message);
				}elseif( $options['wpcargo_choose_sms_gateway'] == 'twilio' ) {
					$explode_sms_num = explode(",", $send_sms_to);					
					if(is_array($explode_sms_num)) {						
						foreach($explode_sms_num as $send_to_num){
							$send_this = $this->wpcargo_get_twilio_access($api_username, $api_password, $sender_id, $send_to_num, $sms_message, $post_id);
						}
					}else{
						$send_this = $this->wpcargo_get_twilio_access($api_username, $api_password, $sender_id, $send_sms_to, $sms_message, $post_id);
					}
				}
				else{
					$send_this = '';
				}
				return $send_this;
			}
		}
	}
	public function wpcargo_get_onewaysms_access( $user, $pass, $sms_from, $sms_to, $sms_msg ) {    
		if( !is_numeric( $sms_from ) || !is_numeric( $sms_to ) ){
			return false;
		}       
		$sms_from 		= preg_replace('/[^0-9]/', '', $sms_from);
		$sms_to 		= preg_replace('/[^0-9]/', '', $sms_to);
		$query_string = "api.aspx?apiusername=".$user."&apipassword=".$pass;
		$query_string .= "&senderid=".rawurlencode($sms_from)."&mobileno=".rawurlencode($sms_to);
		$query_string .= "&message=".rawurlencode(stripslashes($sms_msg)) . "&languagetype=1";        
		$url = "http://gateway80.onewaysms.ph/api2.aspx/".$query_string;       
		$fd = @implode ('', file ($url));
		if ($fd) {                       
			if ($fd > 0) {
				// Success
			}else{
				$_POST['oneway-error'] = $fd;
				add_action( 'before_wpcfe_shipment_form_fields', function( ){
					echo '<div class="col-md-12 mb-3">';
						echo '<div class="alert alert-danger col-md-12 mb-3" role="alert">';
							echo esc_html__( 'Sending SMS message failed.', 'wpcargo-sms' ).'</br>';
							if( isset( $_POST['oneway-error'] ) ){
								echo 'ONE WAY SMS error code: '.$_POST['oneway-error'];
							}
						echo '</div>';
					echo '</div>';
					unset( $_POST['oneway-error'] );
				} );
			}
		}else{  
			$_POST['oneway-error'] = $fd;
			add_action( 'before_wpcfe_shipment_form_fields', function( ){
				echo '<div class="col-md-12 mb-3">';
					echo '<div class="alert alert-danger col-md-12 mb-3" role="alert">';
						echo esc_html__( 'Sending SMS message failed.', 'wpcargo-sms' ).'</br>';
						if( isset( $_POST['oneway-error'] ) ){
							echo 'ONE WAY SMS error code: '.$_POST['oneway-error'];
						}
					echo '</div>';
				echo '</div>';
				unset( $_POST['oneway-error'] );
			} );      
		}
	}
	public function wpcargo_get_twilio_access( $account_sid, $account_authtoken, $from_phone, $phone_to, $message, $shipment_id ) {
		if( !is_numeric( $from_phone ) || !is_numeric( $phone_to ) ){
			return false;
		}
		require_once ( WPCARGO_SMS_FIELD_PATH.'admin/Services/Twilio/autoload.php');
		$sid    		= $account_sid;
		$token  		= $account_authtoken;
		$from_phone 	= preg_replace('/[^0-9]/', '', $from_phone);
		$phone_to 		= preg_replace('/[^0-9]/', '', $phone_to);
		$twilio 		= new Twilio\Rest\Client($account_sid, $account_authtoken);
		try	{
			$message = $twilio->messages->create($phone_to,
				array(
					"body" => $message,
					"from" => $from_phone
				)
			);
		} catch (Exception $e) {
			if( is_admin() ){
				echo $e->getMessage();
				echo '<p><a href="'.home_url('/wp-admin/post.php?post='.$shipment_id.'&action=edit').'">Return to previous page.</a></p>';
			}else{
				$error = $e->getMessage();
				$_POST['twilio-error'] = $error;
				add_action( 'before_wpcfe_shipment_form_fields', function( ){
					echo '<div class="col-md-12 mb-3">';
						echo '<div class="alert alert-danger col-md-12 mb-3" role="alert">';
							echo esc_html__( 'Sending SMS message failed.', 'wpcargo-sms' ).'</br>';
							if( isset( $_POST['twilio-error'] ) ){
								echo $_POST['twilio-error'];
							}
						echo '</div>';
					echo '</div>';
					unset( $_POST['twilio-error'] );
				} );
			}
			
		}
	} 
	public function wpcargo_set_content_type_sms( $content_type ) {
		return 'text/html';
	}
}
$wpc_sms_notification = new WPC_SMS_Notification;