<?

require 'vendor/autoload.php';
use GuzzleHttp\Client;
use \Mailjet\Resources;

// Aweber
const AWEBER_LIST_URL = 'https://api.aweber.com/1.0/accounts/1014494/lists/5820541/subscribers';
const AWEBER_TOKEN_URL = 'https://auth.aweber.com/oauth2/token';



// **** AWEBER ****
function getCollection($client, $accessToken, $url) {
    $collection = array();
    while (isset($url)) {
        $request = $client->get($url,
            ['headers' => ['Authorization' => 'Bearer ' . $accessToken]]
        );
        $body = $request->getBody();
        $page = json_decode($body, true);
        $collection = array_merge($page['entries'], $collection);
        $url = isset($page['next_collection_link']) ? $page['next_collection_link'] : null;
    }
    return $collection;
}

function aweberRefresToken($client) {
    $credentials = parse_ini_file('credentials.ini');
    $clientId = $credentials['clientId'];
    $clientSecret = $credentials['clientSecret'];
    $response = $client->post(
        AWEBER_TOKEN_URL, [
            'auth' => [
                $clientId, $clientSecret
            ],
            'json' => [
                'grant_type' => 'refresh_token',
                'refresh_token' => $credentials['refreshToken']
            ]
        ]
    );
    $body = $response->getBody();
    $newCreds = json_decode($body, true);
    $accessToken = $newCreds['access_token'];
    $refreshToken = $newCreds['refresh_token'];

    $fp = fopen('credentials.ini', 'wt');
    fwrite($fp,
    "clientId = {$clientId}
    clientSecret = {$clientSecret}
    accessToken = {$accessToken}
    refreshToken = {$refreshToken}");
    fclose($fp);
    chmod('credentials.ini', 0600);
}

function aweberSubscribe($email, $name, $date, $geo, $lng, $link) {

    // Create a Guzzle client
	$client = new GuzzleHttp\Client();
	
	// Refresh token
    aweberRefresToken($client);

    // Load credentials
    $credentials = parse_ini_file('credentials.ini');
    $accessToken = $credentials['accessToken']; 
       
    $data = array(
        'email' => $email,
        'name' => $name,
        'update_existing' => "true",
        'custom_fields' => array(
            'date' => $date,
            'geo' => $geo,
            'lng' => $lng,
            'link' => $link,
        ),
    );
    $client->post(AWEBER_LIST_URL, [
        'json' => $data, 
        'headers' => ['Authorization' => 'Bearer ' . $accessToken]
    ]);
}



$email = "burata@me15.com";



aweberSubscribe($email, "burata", date("Y-m-d H:i:s"), "testgeo", "he", "http://google.com");



?>