<?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_LIST = 10210245;


// URL parameters
$email = $_GET['email'];
$name = $_GET['name'] ?? '';
$date = $_GET['date'] ?? (new DateTime())->format('d.m.Y');
$geo = $_GET['geo'] ?? '';
$lng = $_GET['lng'] ?? '';
$link = $_GET['link'] ?? '';



// Redirect url
const REDIRECT_URL = "https://www.7500.biz/email=dfdfd";

// Landing Page
const Landing_ID = "MX_9";

//PARAMS
const Zone_ID = "Test_Zone";
const Camp_ID = "Test_Camp";


// Example URL with parameters
// http://localhost/globa/api.php?email=klavdij.oberstar@gmail.com&name=Klavdij&date=1.2.2020&geo=MX&lng=ES&link=www.google.com

// Enable services
$aweber       = FALSE;
$mailjet      = FALSE;
$database     = TRUE;
$siteinject   = TRUE;
$imax         = TRUE;
$intermaxlist = TRUE;
$df           = TRUE;


header('Content-Type: application/json');

if ($email) {
    $json = debounceCheckEmail($email);
    $success = $json['success'];
    $result = $json['debounce'];
    if ($success != '0') {

        // Save to the list
        if ($result['code'] == '5') {

            processTracking();

            /*if ($aweber) {
                aweberSubscribe($email, $name, $date, $geo, $lng, $link);
            }

            if ($mailjet) {
                mailjetSubscribe(GLOBA_LIST, $email, $name, $date, $geo, $lng, $link);
            }*/

            if ($database) {
                $geo = "MX";
                $userid = saveToDB($email, $name, $date, $geo, $lng, $link);
            }
			
			if ($siteinject){
				
			$dataname = explode("@",$email);
			$name = $dataname[0];
			$username = $name;
			//$email = 'Angel@me15.com';
			rand(100000,99999999);
			$password = rand(100000,99999999);;

			$country = 'MX';
			$dobDay = '1';
			$dobMonth = '1';
			$dobYear = '1995';

			injecttosite($name, $username, $email, $password, $country, $dobDay, $dobMonth, $dobYear);
			}
			
			if($imax){
			$dataname = explode("@",$email);
			$name = $dataname[0];
			$username = $name;
			//$email = 'Angel@me15.com';
			rand(100000,99999999);
			$password = rand(100000,99999999);
			imax($username, $email, $password);
			}
			
			
			if($intermaxlist){
			$sex = "M";
			$response = intermaxlist($userid,$email,$username,$ip,$time,$link,$country,$sex);

			/*$to = "antonluki@gmail.com";
			 $subject = "Test Response";
			 
			 $message = "<b>the response was:</b>";
			 $message .= "<h1>$response</h1>";
			 
			 $header = "From:abc@somedomain.com \r\n";
			 $header .= "MIME-Version: 1.0\r\n";
			 $header .= "Content-type: text/html\r\n";
			 
			 $retval = mail ($to,$subject,$message,$header);*/
			}
			
			if($df){
			$siteurl = "datecity.com.mx";
			$dataname = explode("@",$email);
			$name = $dataname[0];
			$username = $name;
			//$email = 'Angel@me15.com';
			rand(100000,99999999);
			$sex = 1;
			$password = rand(100000,99999999);
			$dob        = "1995-1-1";
			callsite($email,$dob,$sex,$siteurl,$leadid,$password,$_SERVER['REMOTE_ADDR']);
			}
			
			
			
			

            $response = array(
                'success' => true,
               // 'redirect' => "https://www.datecity.co/go/?email=$email&sub=5507&type=0&tag=$tag&affid=$affid"
                 'redirect' => "https://pdgxl.imitrack1.com/c/b6848a59311fff08?s1=846&s2=125205&s3=$affid&s5=MX9&click_id=$email"
            );
            echo json_encode($response);
        } else {
            $response = array(
                'success' => false,
                'error' => $result['reason'],
            );
            http_response_code(400);
            echo json_encode($response);
        }
    } else {
        $response = array(
            'success' => false,
            'error' => $result['error'],
        );
        http_response_code(500);
        echo json_encode($response);
    }
} else {
    $response = array(
        'success' => false,
        'error' => 'No email provided',
    );
    http_response_code(400);
    echo json_encode($response);
}

// **** DEBOUNCE ****
function debounceCheckEmail($email)
{
    $api = '6065b354dffec';
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, 'https://api.debounce.io/v1/?api=' . $api . '&email=' . strtolower($email));
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);

    $data = curl_exec($ch);
    curl_close($ch);

    return json_decode($data, true);
}

// **** TRACKING ****
function processTracking() {

    $affid = $_GET['affid'];
    $tag = $_GET['tag'];

    $value = 0.5;
    if ($affid == 6)  $pixel = "http://main.exoclick.com/tag.php?goal=bcd0049c35799cdf57d06eaf2eb3cff6&tag=$tag";
    if ($affid == 16) $pixel = "https://tsyndicate.com/api/v1/cpa/action/$tag?value=$value&key=WbCW2Vyncw1PD7iQHi74AxgQT04C6MzSO2DF";
    if ($affid == 3)  $pixel = "https://prprocess.com/conversion/?user_id=4055&click_id=$tag&currency=USD&payout=$value";
    if ($affid == 4)  $pixel = "https://ck.juicyads.com/ilikeitjuicy.php?u=11273&s2s=$tag&amount=$value&token=46bc9a3d4222fbcc9d88c7aa8ae7d1aa&data=52c69d19d4e4dc2a550005b33c960ad8";
    if ($affid == 7)  $pixel = "https://ero-analytics.com/tracking/conv.php?cid=$tag&conv_type=a";
    if ($affid == 13) $pixel = "http://ads.adamoads.com/goal_tracker.php?goal=bca82e41ee7b0833588399b1fcd177c7&code=$tag";
    if ($affid == 5)  $pixel = "http://serve.popads.net/cpixel.php?s2s=1&aid=d1919f5f6c957e762869ac492a113099&id=$tag&value=$value";
    if ($affid == 11) $pixel = "http://sconvtrk.com/conversion/20852100607f02aee0488298fc12ae8f5f56f335/?visitor_id=$tag&aid=104434";
    if ($affid == 22) $pixel = "http://ad.propellerads.com/conversion.php?aid=27243&pid=&tid=25202&visitor_id=$tag&value=$value";
    if ($affid == 23) $pixel = "http://main.exoclick.com/tag.php?goal=115fe3d68982c3c0b666ae3aaaa58213&tag=$tag";
    if ($affid == 24) $pixel = "http://peppx.ab4all.com/trackpixel/track?tid=$tag&amt=$value";
    if ($affid == 25) $pixel = "http://a.adskeeper.co.uk/postback?c=$tag&e=lead195446";
    if ($affid == 26) $pixel = "https://ct.popcash.net/click?aid=127826&clickid=$tag&payout=$value";
    if ($affid == 27) $pixel = "https://hilltopads.com/conversion/close/master?token=$tag";
    if ($affid == 226 || $affid == "") $pixel = "http://main.exoclick.com/tag.php?goal=41e61295266e16e43e52f7adc4debb71&tag=$tag";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $pixel);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_exec($ch);
    curl_close($ch);
}

// **** 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]
    ]);
}

// **** 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]);
        }
    }
}

// **** DATABASE ****
function saveToDB($email, $name, $date, $geo, $lng, $link)
{

    $servername = "localhost";
    $database = "datecity_main";
    $username = "datecity_user12";
    $password = ",pK@9acI^2=6";

    // Create connection
    $conn = mysqli_connect($servername, $username, $password, $database);

    // Check connection
    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }

    $exist = FALSE;

    $sql = "SELECT email FROM main WHERE email='$email'";
    $result = mysqli_query($conn, $sql);

    $exist = mysqli_num_rows($result) > 0;


    if (!$exist) {

        $ip   = $_SERVER['REMOTE_ADDR'];

        $sql = "INSERT INTO main (email,fname,lname,dob,geo,lng,ip,link,count) VALUES ('$email','$name','','1900-01-01','$geo','$lng','$ip','$link',0)";

        if (!mysqli_query($conn, $sql)) {
            $response = array(
                'success' => false,
                'error' => $sql . "<br>" . mysqli_error($conn),
            );
            http_response_code(500);
            echo json_encode($response);
			$last_id = $conn->insert_id;
			return $last_id;
        }
    } else {

        $sql = "UPDATE main SET count=count+1 WHERE email='$email'";

        if (!mysqli_query($conn, $sql)){
            $response = array(
                'success' => false,
                'error' => $sql . "<br>" . mysqli_error($conn),
            );
            http_response_code(500);
            echo json_encode($response);
        }
    }

    mysqli_close($conn);
}


// **** Inject to https://datecity.co/ ****
function injecttosite($name, $username, $email, $password, $country, $dobDay, $dobMonth, $dobYear)
{

     set_time_limit(0);

    $url_info = "https://datecity.co/signup";

    $channel = curl_init();

    curl_setopt_array($channel, [
        CURLOPT_URL => $url_info,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => [
            'register-form[sex]' => '1', // male
            'register-form[dobDay]' => $dobDay,
            'register-form[dobMonth]' => $dobMonth,
            'register-form[dobYear]' => $dobYear,
            'register-form[name]' => $name,
            'register-form[username]' => $username,
            'register-form[country]' => $country,
            'register-form[password]' => $password,
            'register-form[email]' => $email,
        ],
    ]);

    curl_exec($channel);

    if (curl_error($channel)) {
        echo 'error:' . curl_error($channel);
    } 
    
    curl_close($channel);
    return;
}

// Imax API SIGN-UP
function imax($username, $email, $password){
	
$affid    = $_GET['affid'];
$tag      = $_GET['tag'];
$campid   = $_GET['campid'];
$zid      = $_GET['zid'];
$subid    = 1;
$lpid     = Landing_ID;

$parameters = [
   'name' => "$username",
   'email' => "$email",
   'password' => "$password",
   'aff' => [
       'entry' => [
           'afid' => 7973,
           'ofid' => 13947,
           'source' => "$affid",
           'aff_sub' => "$lpid",
           'aff_sub1' => "$campid",
           'aff_sub2' => "$zid",
           'aff_sub3' => "",
           'aff_sub4' => "",
           'aff_sub5' => "",
           'ext_id' => "$tag"
       ]
   ]
];
$url = "https://mx.datecity.net/api/rest/v1/de/member-registration";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, [
   'Accept: application/json',
   'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_POST, null);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($parameters));
$resultCurl = curl_exec($ch);
curl_close($ch);
$result = json_decode($resultCurl, true);

return $result;	
}


//DF singup 
function callsite($email,$dob,$sex,$siteurl,$leadid,$password,$ip){
$url = 'http://www.'.$siteurl.'/remote/registration/';
$myvars = 'email=' . $email . '&password=' . $password . '&memberRemoteIP=' . $_SERVER['REMOTE_ADDR'] . '&birthDate=' . $dob . '&sexId=' . $sex. '&refId=DVD-91270&subId='.$leadid;
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $myvars);
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt( $ch, CURLOPT_MAXREDIRS, 2);
curl_setopt( $ch, CURLOPT_HEADER, 0);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec( $ch );
$a = explode("|",$response);	
return $a;	
}


//intermax-ag Email List  
function intermaxlist($id,$email,$username,$ip,$time,$portal,$geo,$sex){
    
    if ($username == "")$username = explode("@",$email);
    if ($ip == "")$ip = $_SERVER['REMOTE_ADDR'];
    if ($time == "") $time = date('Y-m-d h:i:s', time()); 
   
	$url =	'https://central.intermax-ag.com/remote/tools/1.0/log/external-user/';
	$myvars = 'id='.$id.'&email='.$email.'&username='.$username[0].'&ip='.$ip.'&time='.$time.'&portal='.$portal.'&company=300&country='.$geo.'&gender='.$sex;


	$ch = curl_init( $url );
	curl_setopt( $ch, CURLOPT_POST, 1);
	curl_setopt( $ch, CURLOPT_POSTFIELDS, $myvars);
	curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 0);
	curl_setopt( $ch, CURLOPT_MAXREDIRS, 2);
	curl_setopt( $ch, CURLOPT_HEADER, 0);
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);
	$response = curl_exec( $ch );

 return $response;	
}
