<?php
/*
endpoint] => https://fcm.googleapis.com/fcm/send/esM...
    [key] => ...
    [token] => ...
)
*/
ini_set('auto_detect_line_endings',TRUE);
define('YES_PUSH_SUBCRIBERS_FILE',__DIR__.'/subscriber.csv');
if(!is_file(YES_PUSH_SUBCRIBERS_FILE)){
	touch(YES_PUSH_SUBCRIBERS_FILE);
}
$subscription = json_decode(file_get_contents('php://input'), true);
$subscription_csv = implode("\t",$subscription);
function yes_delete_subscriber($subscription_csv){
	 $data = file(YES_PUSH_SUBCRIBERS_FILE);
	 $out = array();
	 foreach($data as $line) {
	     if(trim($line) != $subscription_csv and trim($line) != '') {
		 $out[] = $line;
	     }
	 }

	 $fp = fopen(YES_PUSH_SUBCRIBERS_FILE, "w+");
	 flock($fp, LOCK_EX);
	 foreach($out as $line) {
	     fwrite($fp, $line);
	 }
	 flock($fp, LOCK_UN);
	 fclose($fp);  
}

function yes_check_subscriber_exists($subscription){
	if (($handle = fopen(YES_PUSH_SUBCRIBERS_FILE, "r")) !== FALSE) {
	    while (($data = fgetcsv($handle, 1000, "\t")) !== FALSE) {
		if(sizeOf($data)<2){
			continue;
		}
		if($subscription['key'] == $data[1] and $subscription['token'] == $data[2] and $subscription['endpoint'] == $data[0]){
			return true;
		}
	    }
	    fclose($handle);
	}
	return false;
}

function yes_subscribe($string){
	$filename = YES_PUSH_SUBCRIBERS_FILE;

	// Sichergehen, dass die Datei existiert und beschreibbar ist.
	if (is_writable($filename)) {

	    // Wir öffnen $filename im "Anhänge" - Modus.
	    // Der Dateizeiger befindet sich am Ende der Datei, und
	    // dort wird $somecontent später mit fwrite() geschrieben.
	    if (!$handle = fopen($filename, "a")) {
		 print "Kann die Datei $filename nicht öffnen";
		 exit;
	    }

	    // Schreibe $somecontent in die geöffnete Datei.
	    if (!fwrite($handle, "\r\n".$string)) {
		print "Kann in die Datei $filename nicht schreiben";
		exit;
	    }
	    fclose($handle);
	} else {
	    print "Die Datei $filename ist nicht schreibbar";
	}
}
if (!isset($subscription['endpoint'])) {
    echo 'Error: not a subscription';
    return;
}

$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
    case 'POST':
        // create a new subscription entry in your database (endpoint is unique)

	if(!yes_check_subscriber_exists($subscription)){
		yes_subscribe($subscription_csv);
	}else{
		echo 'exists';
	}
        break;
    case 'PUT':
        // update the key and token of subscription corresponding to the endpoint
        break;
    case 'DELETE':
        // delete the subscription corresponding to the endpoint
	if(yes_check_subscriber_exists($subscription)){
		yes_delete_subscriber($subscription_csv);
	}else{
		echo 'no delete - unknown';
	}
        break;
    default:
        echo "Error: method not handled";
        return;
}
