<?php
$blacklist = array(
	'http://agri.abcde.biz/yes/',
	'https://webmail.df.eu/',
	'http://yes-websolutions.de',
	'http://ticket.yes-websolutions.de',
	'http://yes-a378134.de',
	'http://yes-demo.de/',
	'http://now-yes.de'
);
chdir('/kunden/177922_22359/webseiten/yes');
if(isset($_GET['challenge_code'])){
	$content = json_decode(file_get_contents("php://input"));
	$challenge_code = $_GET['challenge_code'];
	$hash = hash_init('sha256');
	$verificationToken = 'YES4TRADEHH889089393839486471109384A';
	$endpoint = 'https://yes-a177922.de/ebay_marketplace_account_deletion_endpoint.php';

	hash_update($hash, $challenge_code);
	hash_update($hash, $verificationToken);
	hash_update($hash, $endpoint);

	$responseHash = hash_final($hash);
	header('Content-Type: application/json');
	mail('m.aspeleiter@yes-websolutions.de', 'Challenge Code', sprintf(
		"Challenge Code empfangen am %s\r\nCode: %s\r\nGenerated Hash: %s", date('Y-m-d H:i:s'),$challenge_code,$responseHash
	));
	echo json_encode([
		'challengeResponse'=>$responseHash
	]);
	exit;
}


if(!isset($_SERVER['HTTP_X_EBAY_SIGNATURE'])){

	// aktuelles Datum: Wird fortlaufend geschrieben
	// Datum gestern: Wird von den Kundensystemen heruntergeladen
	// Datum vorgestern: Muss geloescht werden
	
	$fn = sprintf('../../secure_files/ebay_deleted_user-%s.csv',date('Y-m-d',time()-(60*60*24*2)));
	if(is_file($fn)){
		printf("Loesche alte Datei %s\r\n",basename($fn));
		if(is_file($fn)){
			//unlink($fn);
			echo "Eigentlich alte Datei ".$fn." loeschen\n";
		}
	}
	$dir    = '../../secure_files';
	$files = scandir($dir, SCANDIR_SORT_ASCENDING);
	$fn = '';
	foreach($files as $file){
		if(strpos($file,'ebay_deleted_user-20')>-1){
			$parts = explode('ebay_deleted_user-', $file);
			$date = substr($parts[1],0,-4);
			if($date == date('Y-m-d')){
				continue;
			}
			$fn = $dir.DIRECTORY_SEPARATOR.$file;		
			break;
		}
	}
	if(empty($fn)){
		die('Es sind keine Dateien zum abarbeiten vorhanden');
	}
	
	if(is_file($fn)){
		$data = array(
			'AUTH'=>'YES4TRADEEBAYNOTIFICATION',
			'EBAY_DELETED_USER'=>file_get_contents($fn)
		);
	}else{
		mail('m.aspeleiter@yes-websolutions.de','Error @'.basename(__FILE__), "Script says ".$fn." is not a file. Current DIR: ".getcwd());
		$data = [];
		die(basename($fn).' is not a file');
	}
	$urls = array();
	$admin_messages = array();
	try {
	    $dbh = new PDO('mysql:host=mysql;dbname=db177922_1', 'db177922_1', '1CdQ2X3n');
	    foreach($dbh->query('SELECT * FROM server_client WHERE server_id != 11') as $row) {
	    	if(in_array($row['url'], $blacklist)){
	    		continue;
		}
		$urls[] = $row['url'];
	    }
	    $dbh = null;
	} catch (PDOException $e) {
		mail('m.aspeleiter@yes-websolutions.de','Error @'.basename(__FILE__),'DB Connection failed '.$e->getMessage());
		die('Error @'.basename(__FILE__).' DB Connection failed '.$e->getMessage());
	}
	
	foreach($urls as $_url){
		$url = $_url.'/ebay_account_delete.php';
		if(strlen($data['EBAY_DELETED_USER'])>1){
			$content = json_encode($data);

			$curl = curl_init($url);
			curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
			curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
			curl_setopt($curl, CURLOPT_HEADER, false);
			curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($curl, CURLOPT_HTTPHEADER,
				array("Content-type: application/json"));
			curl_setopt($curl, CURLOPT_POST, true);
			curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
			try{
				$json_response = curl_exec($curl);

				$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
				curl_close($curl);
				if ( $status != 200 ) {
					$msg = sprintf("Beim System %s konnten die aktuellen eBay Account Delete Daten nicht abgeglichen werden. Status: %s, Error: %s",$url,$status,curl_error($curl));
					$admin_messages[] = $msg;
					echo $msg."\r\n";
					//die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
					continue;
				}else{
					$response = json_decode($json_response);
					if(!isset($response->MSG) or empty($response->MSG)){
						$admin_messages[] = sprintf("Beim System %s konnte kein JSON response empfangen werden",$url);
						continue;
					}
					echo $response->MSG;
					$admin_messages[] = sprintf('Fuer System %s wurden die Datensaetze (%d Zeichen) zum loeschen gesendet. Response: %s',
						$url, strlen($data['EBAY_DELETED_USER']),
						$response->MSG
					);
				}
			}catch( Exception $e){
				mail('m.aspeleiter@yes-websolutions.de','Error dev@'.basename(__FILE__),'Curl to '.$url.' failed '.$e->getMessage());
			}
		}else{
			$admin_messages[] = "Es wurden keine Daten empfangen";
		}
	}
	unlink($fn);
	if(sizeOf($admin_messages)){
//		mail('m.aspeleiter@yes-websolutions.de','Result @'.basename(__FILE__),"File: ".basename($fn)."\n\n".implode("\r\n",$admin_messages));
	}
	die("\n\nDone - ".basename($fn)." deleted.\n");
}


$content = json_decode(file_get_contents("php://input"));
$file = '../../secure_files/ebay_deleted_user-'.date('Y-m-d').'.csv';
if(!is_file($file)){
	touch($file);
}
$save_file_content .= sprintf("%s\n",$content->notification->data->username);
file_put_contents($file, $save_file_content, FILE_APPEND | LOCK_EX);
//$header = ['MIME-Version: 1.0'];
//$header[] = 'Content-type: text/html; charset=iso-8859-1';
//mail('m.aspeleiter@yes-websolutions.de','eBay Account Deletion',$string,implode("\r\n", $header));
header("HTTP/1.1 200 OK");

