<?php
/*
Funciones:
- do_action: ejecuta el hook (normalmente wordpress los ejecuta)
- add_action: ejecuta la accion del hook, (qi ejecutamos el proceso de integracion)
Hooks:
actions:
- save_post

### Enviendo correo
$to = "jwong@gamanet,pe";
$subject = "Soporte";
$body = "Necesito ayuda sobre ...";
$headers = array('Content-Type: text/html; charset=UTF-8');
wp_mail($to, $subject, $body, headers);

*/

if ( ! defined( 'ABSPATH' ) ) {
	exit;
} // Exit if accessed directly

class GamaIntegrations {

	public $sms;
	public $date;
	public $options;
	public $cf7_data;

	public function __construct() {
		        global $wpdb; // Para acceso a db
                global $wpgamasms_option;
                global $gama_sms;
                
                $this->sms     = $gama_sms;
                $this->options = $wpgamasms_option;
                $this->date    = GAMASMS_CURRENT_DATE;
				$this->wpdb     = $wpdb;
				

		// Contact Form 7
		if ( isset( $this->options['cf7_metabox'] ) ) {
                    if($this->options['cf7_metabox']=="1"){
			add_filter( 'wpcf7_editor_panels', array( $this, 'cf7_editor_panels' ) );
			add_action( 'wpcf7_after_save', array( $this, 'wpcf7_save_form' ) );
			add_action( 'wpcf7_before_send_mail', array( $this, 'wpcf7_sms_handler' ) );
                    }
		}
		
		// WPForms
		if ( isset( $this->options['wpforms_process_complete'] ) ) {
                 if($this->options['wpforms_process_complete']=="1"){
			        add_action( 'wpforms_process_complete', array( $this, 'wpf_process_complete' ) );
                 }
		}

		// Woocommerce new order ( administrador )
		if ( isset( $this->options['wc_notif_new_order'] ) ) {
                 if($this->options['wc_notif_new_order']=="1"){
			         add_action( 'woocommerce_new_order', array( $this, 'wc_new_order' ), 10, 1 );
                 }
		}
		
		// Woocommerce new order ( usuario )
		if ( isset( $this->options['wc_notif_new_order_self'] ) ) {
                 if($this->options['wc_notif_new_order_self']=="1"){
			         add_action( 'woocommerce_new_order', array( $this, 'wc_new_order_self' ), 20, 1 );
                 }
		}

		// Woocommerce processing order ( usuario )
		if ( isset( $this->options['wc_notif_processing_order'] ) ) {
                 if($this->options['wc_notif_processing_order']=="1"){
			         add_action( 'woocommerce_order_status_changed', array( $this, 'wc_order_status_changed' ), 10, 2 );
                 }
		}


		// Woocommerce cancelled order ( usuario )
		if ( isset( $this->options['wc_notif_cancelled_order'] ) ) {
                 if($this->options['wc_notif_cancelled_order']=="1"){
			         add_action( 'woocommerce_order_status_changed', array( $this, 'wc_order_status_changed' ), 10, 2 );
                 }
		}
		
		// Woocommerce completed order ( usuario )
		if ( isset( $this->options['wc_notif_completed_order'] ) ) {
                 if($this->options['wc_notif_completed_order']=="1"){
			         add_action( 'woocommerce_order_status_changed', array( $this, 'wc_order_status_changed' ), 10, 2 );
                 }
		}

		// Woocommerce pending order ( usuario )
		if ( isset( $this->options['wc_notif_pending_order'] ) ) {
                 if($this->options['wc_notif_pending_order']=="1"){
			         add_action( 'woocommerce_order_status_changed', array( $this, 'wc_order_status_changed' ), 10, 2 );
                 }
		}
		
		// Woocommerce failed order ( usuario )
		if ( isset( $this->options['wc_notif_failed_order'] ) ) {
                 if($this->options['wc_notif_failed_order']=="1"){
			         add_action( 'woocommerce_order_status_changed', array( $this, 'wc_order_status_changed' ), 10, 2 );
                 }
		}
		
		// Woocommerce refunded order ( usuario )
		if ( isset( $this->options['wc_notif_refunded_order'] ) ) {
                 if($this->options['wc_notif_refunded_order']=="1"){
			         add_action( 'woocommerce_order_status_changed', array( $this, 'wc_order_status_changed' ), 10, 2 );
                 }
		}

		// Woocommerce new note order ( usuario )
		if ( isset( $this->options['wc_notif_note_order'] ) ) {
                 if($this->options['wc_notif_note_order']=="1"){
			         add_action( 'woocommerce_new_customer_note', array( $this, 'wc_order_new_note' ), 10, 2 );
                 }
		}

		// Woocommerce woocommerce_created_customer( administrador )
		if ( isset( $this->options['wc_notif_created_customer'] ) ) {
                if($this->options['wc_notif_created_customer']=="1"){
			        add_action( 'woocommerce_created_customer', array( $this, 'wc_created_customer' ), 10, 3 );
                }
		}
		
		// Woocommerce woocommerce_created_customer_self ( usuario )
		if ( isset( $this->options['wc_notif_created_customer_self'] ) ) {
                if($this->options['wc_notif_created_customer_self']=="1"){
			        add_action( 'woocommerce_created_customer', array( $this, 'wc_created_customer_self' ), 20, 3 );
                }
		}
		
		// Woocommerce woocommerce_created_customer add db
		if ( isset( $this->options['wc_notif_created_customer_add_db'] ) ) {
                if($this->options['wc_notif_created_customer_add_db']=="1"){
			        add_action( 'woocommerce_created_customer', array( $this, 'wc_created_customer_add_db' ));
					add_action( 'woocommerce_new_order', array( $this, 'wc_created_customer_add_db' ));
                }
		}

		// EDD
		if ( isset( $this->options['edd_notif_new_order'] ) ) {
                    if($this->options['edd_notif_new_order']=="1"){
			            add_action( 'edd_complete_purchase', array( $this, 'edd_new_order' ) );
                    }
		}
		
		// WordPress 
		if ( isset( $this->options['gamasms_publish_post'] ) ) {
			        if($this->options['gamasms_publish_post']=="1"){
                          add_action('publish_post',array( $this, 'gamasms_callback_publish_post' ),10,2); // Dispara cuando se graba un post 
					}
		}	

		// WordPress 
		if ( isset( $this->options['gamasms_comment_post'] ) ) {
				    if($this->options['gamasms_comment_post']=="1"){
                          add_action('comment_post',array( $this, 'gamasms_callback_comment_post' ),10,2); // Dispara cuando se comenta un post 
					}
		}

		// Gravity Forms
		/*
		if ( isset( $this->options['gform_pre_submission'] ) ) {
                 if($this->options['gform_pre_submission']=="1"){
			        add_action( 'gform_pre_submission', array( $this, 'gform_pre_submission_handler' ) );
                 }
		}
        */		

		// Gravity Forms
		if ( isset( $this->options['gform_after_submission'] ) ) {
                 if($this->options['gform_after_submission']=="1"){
			        add_action( 'gform_after_submission', array( $this, 'gform_after_submission_handler' ),10,2 );
                 }
		}			

	}
	
	public function db_add_suscription( $name, $mobile, $groupid ) {
		
		$table = "{$this->wpdb->prefix}gamasms_subscribes";
				
        $sql2 = "select * from $table where mobile like '%".$mobile."' order by id asc";
        $list_subscribes = $this->wpdb->get_results($sql2,ARRAY_A);
        // Si no hay registros con ese campo, agregar
        if(empty($list_subscribes)){ 
             $data = [
               'id' => null,
               'creationdate' => null,
               'name' => $name,
               'mobile' => $mobile,
               'status' => '1',
               'activate_key' => null,
               'group_id' => $groupid
            ];
		  
		    $result = $this->wpdb->insert($table,$data);
		  
        }

	}

	public function cf7_editor_panels( $panels ) {
		$new_page = array(
			'gamasms' => array(
				'title'    => __( 'GAMA Notificacion', 'gamasms' ),
				'callback' => array( $this, 'cf7_setup_form' )
			)
		);

		$panels = array_merge( $panels, $new_page );

		return $panels;
	}


	public function cf7_setup_form( $form ) {
		$cf7_options       = get_option( 'wpcf7_gamasms_' . $form->id() );
		$cf7_options_field = get_option( 'wpcf7_gamasms_form' . $form->id() );

		if ( ! isset( $cf7_options['phone'] ) ) {
			$cf7_options['phone'] = '';
		}
		if ( ! isset( $cf7_options['message'] ) ) {
			$cf7_options['message'] = '';
		}
		if ( ! isset( $cf7_options_field['phone'] ) ) {
			$cf7_options_field['phone'] = '';
		}
		if ( ! isset( $cf7_options_field['message'] ) ) {
			$cf7_options_field['message'] = '';
		}

		include_once GAMASMS_DIR . "templates/wpcf7-form.php";
	}

	public function wpcf7_save_form( $form ) {
		update_option( 'wpcf7_gamasms_' . $form->id(), $_POST['wpcf7-gamasms'] );
		update_option( 'wpcf7_gamasms_form' . $form->id(), $_POST['wpcf7-gamasms-form'] );
	}

	public function wpcf7_sms_handler( $form ) {
		$cf7_options       = get_option( 'wpcf7_gamasms_' . $form->id() );
		$cf7_options_field = get_option( 'wpcf7_gamasms_form' . $form->id() );
		$this->set_cf7_data();

		if ( $cf7_options['message'] && $cf7_options['phone'] ) {
			//$this->sms->smsnumber = explode( ',', $cf7_options['phone'] );
                        $this->sms->smsnumber = $cf7_options['phone'];

			$this->sms->smstext = preg_replace_callback( '/%([a-zA-Z0-9._-]+)%/', function ( $matches ) {
				foreach ( $matches as $item ) {
					if ( isset( $this->cf7_data[ $item ] ) ) {
						return $this->cf7_data[ $item ];
					}
				}
			}, $cf7_options['message'] );

		    $this->sms->SendMsg(true); // mute true
		}

		if ( $cf7_options_field['message'] && $cf7_options_field['phone'] ) {
		        $to = preg_replace_callback( '/%([a-zA-Z0-9._-]+)%/', function ( $matches ) {
		                foreach ( $matches as $item ) {
					if ( isset( $this->cf7_data[ $item ] ) ) {
						return $this->cf7_data[ $item ];
					}
				}
			}, $cf7_options_field['phone'] );

                        // Check the type of field is select.
                        foreach ($form->scan_form_tags() as $scan_form_tag) {
                             if($scan_form_tag['basetype'] == 'select') {
                                foreach ($scan_form_tag['raw_values'] as $raw_value) {
                                      $option = explode('|', $raw_value);

                                      if(isset($option[0]) and $option[0] == $to) {
                                           $to = $option[1];
                                      }
                                }
                             }
                        }

                        //$this->sms->smsnumber = array( $to );
                        $this->sms->smsnumber = $to;

			$this->sms->smstext = preg_replace_callback( '/%([a-zA-Z0-9._-]+)%/', function ( $matches ) {
			    foreach ( $matches as $item ) {
					if ( isset( $this->cf7_data[ $item ] ) ) {
						return $this->cf7_data[ $item ];
					}
				}
			}, $cf7_options_field['message'] );
		    $this->sms->SendMsg(true); // mute true
		}
	}

	private function set_cf7_data() {
		foreach ( $_POST as $index => $key ) {
			if ( is_array( $key ) ) {
				$this->cf7_data[ $index ] = implode( ', ', $key );
			} else {
				$this->cf7_data[ $index ] = $key;
			}
		}
	}
	
	public function wpf_process_complete( $fields ) {
		global $wpdb;
		$table3  = "{$wpdb->prefix}gamasms_subscribes";
		
		$data = array();
	
		//var_dump($fields);
		
		foreach($fields as $key=>$arr) { 
		/*
			   echo "key: ". $key. "<br>";
			   echo "type: " . $arr['type']." ";  // para filtrar
			   echo "name: " . $arr['name']." ";
			   echo "value: " . $arr['value']." ";	// valor
			   echo "<br>";
		*/
			   if($arr['type'] == "name"){
				   $data['name'] = $arr['value'];
			   }
			   if($arr['type'] == "email"){
				   $data['email'] = $arr['value'];
			   }
			   if($arr['type'] == "textarea"){
				   $data['textarea'] = $arr['value'];
			   }
			   if($arr['type'] == "text"){
				   $data['text'] = $arr['value'];
			   }
        }
		
		if($this->options['wpforms_process_complete_send_to']=="admin"){
		    $this->sms->smsnumber  = $this->options['admin_mobile_number'];
		}else{
		    if($this->options['wpforms_process_complete_send_to']=="subscribes_group"){
				  
                  $send_to_subscribes_group_id = $_POST['wpforms_process_complete_send_to_subscribes_group_id'];

                  if($send_to_subscribes_group_id >= 0){
                          $sql5 = "select * from $table3 where group_id='$send_to_subscribes_group_id' and status='1'";
                          $list_subscribes = $wpdb->get_results($sql5,ARRAY_A);
                  }else{ // all
                          $sql5 = "select * from $table3 where status='1'";
                          $list_subscribes = $wpdb->get_results($sql5,ARRAY_A);
                  }

                  // Para que no se produzcan errores cuando no hay datos
                  if(empty($list_subscribes)){ 
                          $list_subscribes = array();
                  }

                  foreach($list_subscribes as $key => $value){
                         $mobile = $value['mobile'];
                         $fields_string .= $mobile.',';  
                  }
				  
                  $fields_string = rtrim($fields_string,',');
                  $sms_numbers = $fields_string;
				  $this->sms->smsnumber = $sms_numbers;
			}else{
				return;  // No hay informacion de destinatarios
			}
			
		}

		$template_vars  = array(
			'%name%' => $data['name'],
			'%email%' => $data['email'],
			'%textarea%' => $data['textarea'],
		    '%text%' => $data['text'],
		);
		
		$message = str_replace( array_keys( $template_vars ), array_values( $template_vars ), $this->options['wpforms_process_complete_template'] );
		$this->sms->smstext = $message;

		$this->sms->SendMsg(true); // mute true
		
	}

	public function wc_new_order( $order_id ) {
		$order          = new \WC_Order( $order_id );
		//$this->sms->smsnumber  = array( $this->options['admin_mobile_number'] );
                $this->sms->smsnumber  = $this->options['admin_mobile_number'];

		$template_vars  = array(
			'%order_id%' => $order_id,
			'%status%' => $order->get_status(),
			'%total%' => $order->get_total(),
			'%order_number%' => $order->get_order_number(),
			'%billing_company%' => $order->get_billing_company(),
			'%billing_first_name%' => $order->get_billing_first_name(),
			'%billing_phone%' => $order->get_billing_phone(),
			'%billing_address_1%' => $order->get_billing_address_1(),
		);
		
		$message = str_replace( array_keys( $template_vars ), array_values( $template_vars ), $this->options['wc_notif_new_order_template'] );
		$this->sms->smstext = $message;

		$this->sms->SendMsg(true); // mute true
	}
	
	public function wc_new_order_self( $order_id ) {
		$order          = new \WC_Order( $order_id );
		$phone_self = $order->get_billing_phone();
		
		if(is_numeric($phone_self)){
		    $this->sms->smsnumber = $phone_self;
		}else{
		    return;	
		}
		
		$template_vars  = array(
			'%order_id%' => $order_id,
			'%status%' => $order->get_status(),
			'%total%' => $order->get_total(),
			'%order_number%' => $order->get_order_number(),
			'%billing_company%' => $order->get_billing_company(),
			'%billing_first_name%' => $order->get_billing_first_name(),
			'%billing_phone%' => $order->get_billing_phone(),
			'%billing_address_1%' => $order->get_billing_address_1(),
		);
		
		$message = str_replace( array_keys( $template_vars ), array_values( $template_vars ), $this->options['wc_notif_new_order_self_template'] );
		$this->sms->smstext = $message;

		$this->sms->SendMsg(true); // mute true
	}

    // Se ejecuta cuando cambia el estado de la orden
	public function wc_order_status_changed( $order_id, $temporizador = false  ) {
		$order          = new \WC_Order( $order_id );
		$phone_self = $order->get_billing_phone();
		$status   = is_callable( [ $order, 'get_status' ] ) ? $order->get_status() : $order->status;
		
		if(is_numeric($phone_self)){
		    $this->sms->smsnumber = $phone_self;
		}else{
		    return;	
		}
		
		$template_vars  = array(
			'%order_id%' => $order_id,
			'%status%' => $order->get_status(),
			'%total%' => $order->get_total(),
			'%order_number%' => $order->get_order_number(),
			'%billing_company%' => $order->get_billing_company(),
			'%billing_first_name%' => $order->get_billing_first_name(),
			'%billing_phone%' => $order->get_billing_phone(),
			'%billing_address_1%' => $order->get_billing_address_1(),
		);
		
		if ( $status == 'processing' && $this->options['wc_notif_processing_order_template'] != ''){
			$message = str_replace( array_keys( $template_vars ), array_values( $template_vars ), $this->options['wc_notif_processing_order_template'] );
		}else if($status == 'cancelled' && $this->options['wc_notif_cancelled_order_template'] != ''){
			$message = str_replace( array_keys( $template_vars ), array_values( $template_vars ), $this->options['wc_notif_cancelled_order_template'] );
		}else if($status == 'completed' && $this->options['wc_notif_completed_order_template'] != ''){
			$message = str_replace( array_keys( $template_vars ), array_values( $template_vars ), $this->options['wc_notif_completed_order_template'] );
		}else if($status == 'pending' && $this->options['wc_notif_pending_order_template'] != ''){
			$message = str_replace( array_keys( $template_vars ), array_values( $template_vars ), $this->options['wc_notif_pending_order_template'] );
		}else if($status == 'failed' && $this->options['wc_notif_failed_order_template'] != ''){
			$message = str_replace( array_keys( $template_vars ), array_values( $template_vars ), $this->options['wc_notif_failed_order_template'] );
		}else if($status == 'refunded' && $this->options['wc_notif_refunded_order_template'] != ''){
			$message = str_replace( array_keys( $template_vars ), array_values( $template_vars ), $this->options['wc_notif_refunded_order_template'] );
		}else{
			return;
		}
		

		
		$this->sms->smstext = $message;

		$this->sms->SendMsg(true); // mute true
	}
	
    // Se ejecuta cuando hay una nueva nota de la orden
	public function wc_order_new_note( $data  ) {
		
		$order_id		= $data[ 'order_id' ];
		$order          = new \WC_Order( $order_id );
		$phone_self = $order->get_billing_phone();
		$status   = is_callable( [ $order, 'get_status' ] ) ? $order->get_status() : $order->status;
		
		if(is_numeric($phone_self)){
		    $this->sms->smsnumber = $phone_self;
		}else{
		    return;	
		}
		
		$template_vars  = array(
			'%order_id%' => $order_id,
			'%status%' => $order->get_status(),
			'%total%' => $order->get_total(),
			'%order_number%' => $order->get_order_number(),
			'%billing_company%' => $order->get_billing_company(),
			'%billing_first_name%' => $order->get_billing_first_name(),
			'%billing_phone%' => $order->get_billing_phone(),
			'%billing_address_1%' => $order->get_billing_address_1(),
		);
		
		if ( $status == 'processing' && $this->options['wc_notif_processing_order_template'] != ''){
			$message = str_replace( array_keys( $template_vars ), array_values( $template_vars ), $this->options['wc_notif_processing_order_template'] );
		}else if($status == 'cancelled' && $this->options['wc_notif_cancelled_order_template'] != ''){
			$message = str_replace( array_keys( $template_vars ), array_values( $template_vars ), $this->options['wc_notif_cancelled_order_template'] );
		}else if($status == 'completed' && $this->options['wc_notif_completed_order_template'] != ''){
			$message = str_replace( array_keys( $template_vars ), array_values( $template_vars ), $this->options['wc_notif_completed_order_template'] );
		}else if($status == 'pending' && $this->options['wc_notif_pending_order_template'] != ''){
			$message = str_replace( array_keys( $template_vars ), array_values( $template_vars ), $this->options['wc_notif_pending_order_template'] );
		}else if($status == 'failed' && $this->options['wc_notif_failed_order_template'] != ''){
			$message = str_replace( array_keys( $template_vars ), array_values( $template_vars ), $this->options['wc_notif_failed_order_template'] );
		}else if($status == 'refunded' && $this->options['wc_notif_refunded_order_template'] != ''){
			$message = str_replace( array_keys( $template_vars ), array_values( $template_vars ), $this->options['wc_notif_refunded_order_template'] );
		}else{
			return;
		}
		

		
		$this->sms->smstext = $message;

		$this->sms->SendMsg(true); // mute true
	}
	

	public function wc_created_customer( $customer_id, $new_customer_data, $password_generated ) {

		$this->sms->smsnumber  = $this->options['admin_mobile_number'];
		
		$user_email = "";
		$user_login = "";
		$billing_phone = "";
		
		if (isset($new_customer_data['user_email'])) {
			$user_email = $new_customer_data['user_email'];
		
        }
		
		if (isset($new_customer_data['user_login'])) {
			$user_login = $new_customer_data['user_login'];
		
        }
		
		// se trata de encontrar el telefono  del cliente
		if (isset($_POST['billing_phone'])) {
			$billing_phone = $_POST['billing_phone'];
		
        }
		
		if (isset($_POST['user_phone'])) {
			$billing_phone = $_POST['user_phone'];
        }
		
		if (isset($_POST['phone'])) {
			$billing_phone = $_POST['phone'];
        }
		
		$template_vars  = array(
			'%customer_id%' => $customer_id,
			'%user_email%' => $user_email,
			'%user_login%' => $user_login,
			'%billing_phone%' => $billing_phone,
		);
		
		$message = str_replace( array_keys( $template_vars ), array_values( $template_vars ), $this->options['wc_notif_created_customer_template'] );
		$this->sms->smstext = $message;

		$this->sms->SendMsg(true); // mute true
	}

	public function wc_created_customer_self( $customer_id, $new_customer_data, $password_generated ) {

		
		$user_email = "";
		$user_login = "";
		$billing_phone = "";
		
		// se trata de encontrar el telefono  del cliente
		if (isset($_POST['billing_phone'])) {
			$billing_phone = $_POST['billing_phone'];
        }
		
		if (isset($_POST['user_phone'])) {
			$billing_phone = $_POST['user_phone'];
        }
		
		if (isset($_POST['phone'])) {
			$billing_phone = $_POST['phone'];
        }
		
		// Busca en cada campo un telefono
		if(strlen($billing_phone)<=0){
		    foreach ($_POST as $key => $value) {
               //echo "key". $key;
			   //echo "value".$value;
			
			   if(is_numeric($value)){
				    if(strlen($value) == 9 || strlen($value) == 11){
					    if(strncmp($value,"9",1) == 0 || strncmp($value,"519",3)){
						   //echo "celular encontrado: ".$value;
						    $billing_phone = $value;
					    }
				    }
			   }
           }
		}
		
		if(strlen($billing_phone)<=0){
			return;
		}else{
		     $this->sms->smsnumber  = $billing_phone;
		}
		
		if (isset($new_customer_data['user_email'])) {
			$user_email = $new_customer_data['user_email'];
		
        }
		
		if (isset($new_customer_data['user_login'])) {
			$user_login = $new_customer_data['user_login'];
		
        }
		
		
		$template_vars  = array(
			'%customer_id%' => $customer_id,
			'%user_email%' => $user_email,
			'%user_login%' => $user_login,
			'%billing_phone%' => $billing_phone,
		);
		
		$message = str_replace( array_keys( $template_vars ), array_values( $template_vars ), $this->options['wc_notif_created_customer_self_template'] );
		$this->sms->smstext = $message;

		$this->sms->SendMsg(true); // mute true
	}
	
	// Agregamos a la base de suscriptores
	public function wc_created_customer_add_db( ) {
		
		$billing_name = "";
		$billing_phone = "";
		$groupid = $this->options['wc_notif_created_customer_add_db_group_id'];

		if (isset($_POST['billing_first_name'])) {
			    $billing_name = $_POST['billing_first_name'];
        }	
	
		if (isset($_POST['billing_last_name'])) {
			    if(strlen($billing_name)>=3) $billing_name .= " ";
			    $billing_name .= $_POST['billing_last_name'];
        }	
		
		// se trata de encontrar el telefono  del cliente
		if (isset($_POST['billing_phone'])) {
			$billing_phone = $_POST['billing_phone'];
        }
		
		if (isset($_POST['user_phone'])) {
			$billing_phone = $_POST['user_phone'];
        }
		
		if (isset($_POST['phone'])) {
			$billing_phone = $_POST['phone'];
        }
		
		// Si los datos no son vacios proceder a suscribirlos 
		if(strlen($billing_phone)>=9 && strlen($billing_name)>=5){
			
			$this->db_add_suscription( $billing_name, $billing_phone, $groupid );
			
		}
		
	}
	

	public function edd_new_order() {
		//$this->sms->smsnumber  = array( $this->options['admin_mobile_number'] );
                $this->sms->smsnumber  = $this->options['admin_mobile_number'];
		$this->sms->smstext = $this->options['edd_notif_new_order_template'];
		$this->sms->SendMsg(true); // mute true
	}

	public function gamasms_callback_publish_post($post_id,$post) {
		global $wpdb;
		$table3  = "{$wpdb->prefix}gamasms_subscribes";
		
		// Si el post es un borrador o revision no enviamos mensaje
		if(wp_is_post_revision($post_id)){
			return;
		}
	
		$author_id = $post->post_author;
		$author_name = get_the_author_meta('display_name',$author_id);
		$author_email = get_the_author_meta('user_email',$author_id);
		$title = get_the_title($post_id);
		$permalink = get_permalink($post_id);
		//$message = sprintf("Nuevo Post: %s , Autor: %s , URL: %s", $title, $author_name, $permalink);

		$template_vars  = array(
			'%post_id%' => $post_id,
			'%author_id%' => $author_id,
			'%author_name%' => $author_name,
			'%author_email%' => $author_email,
			'%title%' => $title,
			'%permalink%' => $permalink,
		);
		
		$message = str_replace( array_keys( $template_vars ), array_values( $template_vars ), $this->options['gamasms_publish_post_template'] );
		
		if($this->options['gamasms_publish_post_send_to']=="admin"){
		    $this->sms->smsnumber  = $this->options['admin_mobile_number'];
		}else{
		    if($this->options['gamasms_publish_post_send_to']=="subscribes_group"){
				  
                  $send_to_subscribes_group_id = $this->options['gamasms_publish_post_send_to_subscribes_group_id'];

                  if($send_to_subscribes_group_id >= 0){
                          $sql5 = "select * from $table3 where group_id='$send_to_subscribes_group_id' and status='1'";
                          $list_subscribes = $wpdb->get_results($sql5,ARRAY_A);
                  }else{ // all
                          $sql5 = "select * from $table3 where status='1'";
                          $list_subscribes = $wpdb->get_results($sql5,ARRAY_A);
                  }

                  // Para que no se produzcan errores cuando no hay datos
                  if(empty($list_subscribes)){ 
                          $list_subscribes = array();
                  }

                  foreach($list_subscribes as $key => $value){
                         $mobile = $value['mobile'];
                         $fields_string .= $mobile.',';  
                  }
				  
                  $fields_string = rtrim($fields_string,',');
                  $sms_numbers = $fields_string;
				  $this->sms->smsnumber = $sms_numbers;
			}else{
				return;  // No hay informacion de destinatarios
			}
			
		}
		
		$this->sms->smstext = $message;
		$this->sms->SendMsg(true); // mute true
		
		// Mandar correo
		// $headers = [];
		//wp_mail($para,$asunto,$mensaje,$headers);

	}
	
	public function gamasms_callback_comment_post($comment_ID,$comment_approved) {
		global $wpdb;
		$table3  = "{$wpdb->prefix}gamasms_subscribes";
		// Si el comentario no fue aprovado salir
		if( $comment_approved !== 1){
			return;
		}
		
		$comment = get_comment($comment_ID);
		
		$author_id = $comment ->post_author;
		$post_id = $comment->comment_post_ID;
		$post = get_post($post_id);
		$author_name = get_comment_author($comment_ID);
		$author_email = get_comment_author_email($comment_ID);
		$title = get_the_title($post_id);
		$permalink = get_comment_link($comment);
		//$message = sprintf("Nuevo Post: %s , Autor: %s , URL: %s", $title, $author_name, $permalink);
		
		
		$template_vars  = array(
			'%comment_id%' => $comment_ID,
			'%author_id%' => $author_id,
			'%author_name%' => $author_name,
			'%author_email%' => $author_email,
			'%title%' => $title,
			'%permalink%' => $permalink,
		);
		
		$message = str_replace( array_keys( $template_vars ), array_values( $template_vars ), $this->options['gamasms_comment_post_template'] );
		
		if($this->options['gamasms_comment_post_send_to']=="admin"){
		    $this->sms->smsnumber  = $this->options['admin_mobile_number'];
		}else{
		    if($this->options['gamasms_comment_post_send_to']=="subscribes_group"){
				  
                  $send_to_subscribes_group_id = $this->options['gamasms_comment_post_send_to_subscribes_group_id'];

                  if($send_to_subscribes_group_id >= 0){
                          $sql5 = "select * from $table3 where group_id='$send_to_subscribes_group_id' and status='1'";
                          $list_subscribes = $wpdb->get_results($sql5,ARRAY_A);
                  }else{ // all
                          $sql5 = "select * from $table3 where status='1'";
                          $list_subscribes = $wpdb->get_results($sql5,ARRAY_A);
                  }

                  // Para que no se produzcan errores cuando no hay datos
                  if(empty($list_subscribes)){ 
                          $list_subscribes = array();
                  }

                  foreach($list_subscribes as $key => $value){
                         $mobile = $value['mobile'];
                         $fields_string .= $mobile.',';  
                  }
				  
                  $fields_string = rtrim($fields_string,',');
                  $sms_numbers = $fields_string;
				  $this->sms->smsnumber = $sms_numbers;
			}else{
				return;  // No hay informacion de destinatarios
			}
			
		}
		
		$this->sms->smstext = $message;
        //$this->sms->smsnumber  = $this->options['admin_mobile_number'];
		$this->sms->SendMsg(true); // mute true
		// Mandar correo
		// $headers = [];
		//wp_mail($para,$asunto,$mensaje,$headers);
	}
	
	/*
	public function gform_pre_submission_handler( $fields ) {
		global $wpdb;
		$table3  = "{$wpdb->prefix}gamasms_subscribes";
		
		$data = array();
						   
		$data['name'] = "";
		$data['email'] = "";
		$data['textarea'] = "";
		$data['text'] = "";
	
		//var_dump($fields); 
		
		foreach($fields as $key=>$arr) { 
		       if(isset($arr['type'])){
				   if($arr['type'] == "name"){
					   $data['name'] = $arr['value'];
				   }
				   if($arr['type'] == "email"){
					   $data['email'] = $arr['value'];
				   }
				   if($arr['type'] == "textarea"){
					   $data['textarea'] = $arr['value'];
				   }
				   if($arr['type'] == "text"){
					   $data['text'] = $arr['value'];
				   }	   				   
			   }	   
        }
		if(isset($fields['title'])){
		     $data['title'] = $fields['title'];
		}else{
			 $data['title'] = "";
		}
		
		if($this->options['gform_pre_submission_send_to']=="admin"){
		    $this->sms->smsnumber  = $this->options['admin_mobile_number'];
		}else{
		    if($this->options['gform_pre_submission_send_to']=="subscribes_group"){
				  
                  $send_to_subscribes_group_id = $_POST['gform_pre_submission_send_to_subscribes_group_id'];

                  if($send_to_subscribes_group_id >= 0){
                          $sql5 = "select * from $table3 where group_id='$send_to_subscribes_group_id' and status='1'";
                          $list_subscribes = $wpdb->get_results($sql5,ARRAY_A);
                  }else{ // all
                          $sql5 = "select * from $table3 where status='1'";
                          $list_subscribes = $wpdb->get_results($sql5,ARRAY_A);
                  }

                  // Para que no se produzcan errores cuando no hay datos
                  if(empty($list_subscribes)){ 
                          $list_subscribes = array();
                  }

                  foreach($list_subscribes as $key => $value){
                         $mobile = $value['mobile'];
                         $fields_string .= $mobile.',';  
                  }
				  
                  $fields_string = rtrim($fields_string,',');
                  $sms_numbers = $fields_string;
				  $this->sms->smsnumber = $sms_numbers;
			}else{
				return;  // No hay informacion de destinatarios
			}
			
		}

		$template_vars  = array(
			'%title%' => $data['title'],
		);
		
		$message = str_replace( array_keys( $template_vars ), array_values( $template_vars ), $this->options['gform_pre_submission_template'] );
		$this->sms->smstext = $message;

		$this->sms->SendMsg(true); // mute true
		
	}
   */
   
   	public function gform_after_submission_handler( $entry, $form ) {
		global $wpdb;
		$table3  = "{$wpdb->prefix}gamasms_subscribes";
		$gform_after_submission_forms = $this->options['gform_after_submission_forms'];
		$gform_after_submission_forms_ids = $this->options['gform_after_submission_forms_ids'];
		$form_id = $entry['form_id'];
		$nofification = "no";
		
		// si el status es spam no mandar notificacion
		if ( rgar( $entry, 'status' ) === 'spam' ) {
           return;
        }
		
		// Se dispara solo con algunos formularios asignados
		if($gform_after_submission_forms == "1"){
			$forms_ids = str_replace(";",",",$gform_after_submission_forms_ids);
			$forms_ids_array = preg_split("/[\s,]+/",$forms_ids,-1,PREG_SPLIT_NO_EMPTY);
			if ( is_array( $forms_ids_array ) ) {
              foreach ( $forms_ids_array as $elem ) {
				  if($elem == $form_id){
					  $nofification = "yes";
				  }
			  }
			}
			if($nofification == "no") return;
		}
		
		
		$data = array();
		$data['url'] = $entry['source_url'];
		$data['form_id'] = $entry['form_id'];
		$data['form_title'] = $form['title'];
		// Los numeros 1.3 , 3,2 , etc son relativos y no sirven para un formulario complejo
		$data['name'] = rgar( $entry, '1.3' ). " ".rgar( $entry, '1.6' );
		$data['phone'] = rgar( $entry, '2' );
		$data['address'] = rgar( $entry, '3.1' )." ".rgar( $entry, '3.2' )." ".rgar( $entry, '3.3' )." ".rgar( $entry, '3.4' )." ".rgar( $entry, '3.5' )." ".rgar( $entry, '3.6' );
		$data['product'] = rgar( $entry, '4.1' )." ".rgar( $entry, '4.2' ).rgar( $entry, '4.3' );
		$data['number'] = rgar( $entry, '5' );
		$data['singlelinetext'] = rgar( $entry, '6' );
		$data['quantity'] = rgar( $entry, '8' );
		$data['paragraphtext'] = rgar( $entry, '9' );
		
		
		// capturando todas las entradas all_inputs
		$string_add = '';
		
		foreach ( $form['fields'] as $field ) {
           $inputs = $field->get_entry_inputs();
           if ( is_array( $inputs ) ) {
              foreach ( $inputs as $input ) {
                $value = rgar( $entry, (string) $input['id'] );
                // do something with the value
				$string_add = $string_add." \n".$input['id'].": ".$value;
              }
           } else {
              $value = rgar( $entry, (string) $field->id );
              // do something with the value
			  $string_add = $string_add." \n".$field->id.": ".$value;
           }
        }
		
		$data['all_inputs'] = substr($string_add,0,480);
	
		//var_dump($entry); 
		
		
		if($this->options['gform_after_submission_send_to']=="admin"){
		    $this->sms->smsnumber  = $this->options['admin_mobile_number'];
		}else{
		    if($this->options['gform_after_submission_send_to']=="subscribes_group"){
				  
                  $send_to_subscribes_group_id = $_POST['gform_after_submission_send_to_subscribes_group_id'];

                  if($send_to_subscribes_group_id >= 0){
                          $sql5 = "select * from $table3 where group_id='$send_to_subscribes_group_id' and status='1'";
                          $list_subscribes = $wpdb->get_results($sql5,ARRAY_A);
                  }else{ // all
                          $sql5 = "select * from $table3 where status='1'";
                          $list_subscribes = $wpdb->get_results($sql5,ARRAY_A);
                  }

                  // Para que no se produzcan errores cuando no hay datos
                  if(empty($list_subscribes)){ 
                          $list_subscribes = array();
                  }

                  foreach($list_subscribes as $key => $value){
                         $mobile = $value['mobile'];
                         $fields_string .= $mobile.',';  
                  }
				  
                  $fields_string = rtrim($fields_string,',');
                  $sms_numbers = $fields_string;
				  $this->sms->smsnumber = $sms_numbers;
			}else{
				return;  // No hay informacion de destinatarios
			}
			
		}

		$template_vars  = array(
			'%url%' => $data['url'],
			'%form_id%' => $data['form_id'],
			'%form_title%' => $data['form_title'],
			'%name%' => $data['name'],
			'%phone%' => $data['phone'],
			'%address%' => $data['address'],
			'%productname%' => $data['productname'],
			'%number%' => $data['number'],
			'%singlelinetext%' => $data['singlelinetext'],
			'%quantity%' => $data['quantity'],
			'%paragraphtext%' => $data['paragraphtext'],
			'%all_inputs%' => $data['all_inputs'],
		);
		
		$message = str_replace( array_keys( $template_vars ), array_values( $template_vars ), $this->options['gform_after_submission_template'] );
		$this->sms->smstext = $message;

		$this->sms->SendMsg(true); // mute true
		
	}
}

new GamaIntegrations();