<?php

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';

// Globa
const GLOBA_ALL_LIST = 10210245;
const GLOBA_DOI_LIST = 10210246;



	$servername = "localhost";
	$database = "socialsp_leads";
	$username = "socialsp_lead2";
	$password = "US;lZHn[[7@r";

	// Create connection
	$conn = mysqli_connect($servername, $username, $password, $database);
	// Check connection
	if (!$conn) {
		die("Connection failed: " . mysqli_connect_error());
	}
	
		$exist = 0;
		//echo $email;
		$result = mysqli_query($conn,"SELECT * FROM leads WHERE  `id` > 2802 and `id` < 3400 ORDER BY `id` "); 
		//$row = mysqli_fetch_array($result); 
		while($data = mysqli_fetch_assoc($result)){
			$i++;
		echo "$data[id] = $data[email] - $data[status] - $i" ;
		echo "<br>";
			mailjetSubscribe(GLOBA_ALL_LIST, $data['email'], $name, $data['date'], $data['geo'], $data['lng'], $data['link']);

		}
		
// **** MAILJET ****
function mailjetSubscribe($list, $email, $name, $date, $geo, $lng, $link) {

    // Load settings
    $credentials = parse_ini_file('mailjet.ini');
    $apiKey = $credentials['apiKey'];
    $apiSecret = $credentials['apiSecret'];

    // Mailjet client
    $mj = new \Mailjet\Client($apiKey, $apiSecret);

    $body = [
        'IsExcludedFromCampaigns' => "false",
        'Email' => $email,
        'Name' => $name
    ];
    $response = $mj->post(Resources::$Contact, ['body' => $body]);

    $response = $mj->get(Resources::$Contact, ['id' => urlencode($email)]);
    if ($response->success()) {
        $contact = $response->getData()[0];

        // Save additional data
        $body = [
            'Data' => [
                [
                    'Name' => "date",
                    'Value' => $date
                ],
                [
                    'Name' => "geo",
                    'Value' => $geo
                ],
                [
                    'Name' => "lng",
                    'Value' => $lng
                ],
                [
                    'Name' => "link",
                    'Value' => $link
                ]
              ]
        ];

        $response = $mj->put(Resources::$Contactdata, ['id' => $contact['ID'], 'body' => $body]);
        if ($response->success()) {

            // Add to list
            $body = [
                'ContactsLists' => [
                    [
                        'Action' => "addforce",
                        'ListID' => $list
                    ],
                
                ]
            ];
            $response = $mj->post(Resources::$ContactManagecontactslists, ['id' => $contact['ID'], 'body' => $body]);
        }
    }
}

?>


