<?php
/*
Original code by Pross found here https://gist.github.com/Pross/3ff9f68fea20dcdc8845919dc51de90d
//-------------------------------------------------------------------------------------//
Version 1.0.0
bdacus01 2020 found here https://gist.github.com/bdacus01/84171d9454e7ab4152be2edc65855c21
Improvements to code: added api key, firstname, and customer filter list.
If new account doesn't have the first_name filled in pull it from the registration POST.  
user_register does not write out to the database until after registration is complete. 
This code is for WC Customers.  We are assuming they bought products or created an account.
We dont bypass double opt in or set gdpr.  That could be added as needed.
//-------------------------------------------------------------------------------------//
Copyright (C) 2020 bdacus01 
This program is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option)
any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of  MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
this program.  If not, see <http://www.gnu.org/licenses/>.
//-------------------------------------------------------------------------------------//
*/
add_action('user_register', 'add_user_to_sendy_list', 20);

function add_user_to_sendy_list($user_id)
{
  //-------------------------- You need to set these --------------------------//
  $api_key = 'Your API Key';
  $list = 'Your List ID';
  $url  = 'Your sendy install url/subscribe';
  //-------------------------- End Here --------------------------//
  //Get User info on user passed in from registration via user_id
  $user_info = get_userdata($user_id);
  $name = $user_info->first_name;
  $email = $user_info->user_email;
  //Get role on user passed in from registration via user_id.  Not needed for Sendy only for filter code below.
  $role = $user_info->roles;

  /* If new account doesn't have the first_name filled in pull it from the registraion POST.  
  user_register doesnt write out to the database until after registration is complete. */
  if (isset($_POST['first_name'])) {
    $name = $_POST['first_name'];
  }

  $args = array(
    'body' => array(
      'name'  => $name,
      'email' => $email,
      'list'    => $list,
      'api_key' => $api_key,
      'boolean' => true
    )
  );
  // If new account doesn't have the 'customer' role don't do anything.  If you want all roles to go comment this out.
  if (!in_array('customer', $role)) {
    return;
  }

  $result = wp_remote_post($url, $args);
}