<?php

ini_set('display_errors',0);
error_reporting(0);

$config_file="config.json";
$step_file="step.json";

/* ================= INSTALL PAGE ================= */

if(!file_exists($config_file)){

if(isset($_POST["install"])){

$config=[
"bot_token"=>$_POST["token"],
"api_url"=>rtrim($_POST["api"],"/"),
"username"=>$_POST["user"],
"password"=>$_POST["pass"],
"sudo_id"=>$_POST["sudo"]
];

file_put_contents($config_file,json_encode($config,JSON_PRETTY_PRINT));

$webhook="https://".$_SERVER["HTTP_HOST"].$_SERVER["PHP_SELF"];

file_get_contents("https://api.telegram.org/bot".$config["bot_token"]."/setWebhook?url=".$webhook);

echo "✅ نصب انجام شد";
exit;
}

?>

<html>
<head>
<meta charset="UTF-8">
<title>Marzban Bot Installer</title>
</head>

<body style="font-family:tahoma;background:#f5f5f5">

<center>

<h2>نصب ربات مرزبان</h2>

<form method="post">

<input name="token" placeholder="Bot Token" required><br><br>

<input name="api" placeholder="https://domain:2053" required><br><br>

<input name="user" placeholder="Admin Username" required><br><br>

<input name="pass" placeholder="Admin Password" required><br><br>

<input name="sudo" placeholder="Telegram ID" required><br><br>

<button name="install">Install</button>

</form>

</center>

</body>
</html>

<?php
exit;
}

/* ================= LOAD CONFIG ================= */

$config=json_decode(file_get_contents($config_file),true);

/* ================= STEP SYSTEM ================= */

if(!file_exists($step_file)){
file_put_contents($step_file,"{}");
}

$steps=json_decode(file_get_contents($step_file),true);

/* ================= GET UPDATE ================= */

$update=json_decode(file_get_contents("php://input"),true);

$message=$update["message"] ?? null;
$callback=$update["callback_query"] ?? null;

$chat_id=$message["chat"]["id"] ?? $callback["message"]["chat"]["id"];
$text=$message["text"] ?? null;
$data=$callback["data"] ?? null;

if($chat_id!=$config["sudo_id"]) exit;

/* ================= TELEGRAM FUNCTION ================= */

function bot($method,$data=[]){

global $config;

$url="https://api.telegram.org/bot".$config["bot_token"]."/".$method;

$ch=curl_init();

curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);

$res=curl_exec($ch);

curl_close($ch);

return $res;

}

/* ================= MARZBAN TOKEN ================= */

function marzban_token(){

global $config;

$ch=curl_init($config["api_url"]."/api/admin/token");

curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_POST,true);

curl_setopt($ch,CURLOPT_POSTFIELDS,http_build_query([
"username"=>$config["username"],
"password"=>$config["password"]
]));

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

$data=json_decode($res,true);

return $data["access_token"] ?? null;

}

/* ================= STEP HANDLER ================= */

if(isset($steps[$chat_id])){

$step=$steps[$chat_id]["step"];

/* دریافت یوزرنیم */

if($step=="admin_username"){

$steps[$chat_id]["username"]=$text;
$steps[$chat_id]["step"]="admin_password";

file_put_contents($step_file,json_encode($steps));

bot("sendMessage",[
"chat_id"=>$chat_id,
"text"=>"🔑 حالا پسورد ادمین را بفرست"
]);

exit;

}

/* دریافت پسورد */

if($step=="admin_password"){

$username=$steps[$chat_id]["username"];
$password=$text;

$token=marzban_token();

$ch=curl_init($config["api_url"]."/api/admin");

curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_POST,true);

curl_setopt($ch,CURLOPT_HTTPHEADER,[
"Authorization: Bearer ".$token,
"Content-Type: application/json"
]);

curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode([
"username"=>$username,
"password"=>$password,
"is_sudo"=>false
]));

curl_exec($ch);
curl_close($ch);

unset($steps[$chat_id]);

file_put_contents($step_file,json_encode($steps));

bot("sendMessage",[
"chat_id"=>$chat_id,
"text"=>"✅ ادمین ساخته شد\n\n👤 $username"
]);

exit;

}

/* حذف ادمین */

if($step=="delete_admin"){

$user=$text;

$token=marzban_token();

$ch=curl_init($config["api_url"]."/api/admin/".$user);

curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_CUSTOMREQUEST,"DELETE");

curl_setopt($ch,CURLOPT_HTTPHEADER,[
"Authorization: Bearer ".$token
]);

curl_exec($ch);
curl_close($ch);

unset($steps[$chat_id]);

file_put_contents($step_file,json_encode($steps));

bot("sendMessage",[
"chat_id"=>$chat_id,
"text"=>"✅ ادمین حذف شد"
]);

exit;

}

}

/* ================= MENU ================= */

$menu=json_encode([
"inline_keyboard"=>[
[
["text"=>"📊 آمار سرور","callback_data"=>"stats"]
],
[
["text"=>"👨‍💻 لیست ادمین ها","callback_data"=>"admins"]
],
[
["text"=>"📈 مصرف ادمین‌ها","callback_data"=>"admins_usage"]
],
[
["text"=>"➕ ساخت ادمین","callback_data"=>"add_admin"]
],
[
["text"=>"❌ حذف ادمین","callback_data"=>"delete_admin"]
]
]
]);

/* ================= START ================= */

if($text=="/start"){

bot("sendMessage",[
"chat_id"=>$chat_id,
"text"=>"حاج احسان خوش اومدی به بات ❤️\n\nخودت نوکرتیم 🌹"
]);

bot("sendMessage",[
"chat_id"=>$chat_id,
"text"=>"منوی مدیریت:",
"reply_markup"=>$menu
]);

}

/* ================= SERVER STATS ================= */

if($data=="stats"){

$token=marzban_token();

$ch=curl_init($config["api_url"]."/api/system");

curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);

curl_setopt($ch,CURLOPT_HTTPHEADER,[
"Authorization: Bearer ".$token
]);

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

$s=json_decode($res,true);

$msg="📊 آمار سرور\n\n";

$msg.="👤 کاربران: ".$s["users_total"]."\n";
$msg.="✅ فعال: ".$s["users_active"]."\n";
$msg.="📥 دانلود: ".$s["traffic_received"]."\n";
$msg.="📤 آپلود: ".$s["traffic_sent"]."\n";

bot("sendMessage",[
"chat_id"=>$chat_id,
"text"=>$msg
]);

}

/* ================= ADMIN LIST ================= */

if($data=="admins"){

$token=marzban_token();

$ch=curl_init($config["api_url"]."/api/admins");

curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);

curl_setopt($ch,CURLOPT_HTTPHEADER,[
"Authorization: Bearer ".$token
]);

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

$list=json_decode($res,true);

$msg="👨‍💻 لیست ادمین ها\n\n";

foreach($list as $a){
$msg.="• ".$a["username"]."\n";
}

bot("sendMessage",[
"chat_id"=>$chat_id,
"text"=>$msg
]);

}

/* ================= ADMINS USAGE ================= */

if($data=="admins_usage"){

$token=marzban_token();

$ch=curl_init($config["api_url"]."/api/admins");

curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);

curl_setopt($ch,CURLOPT_HTTPHEADER,[
"Authorization: Bearer ".$token
]);

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

$admins=json_decode($res,true);

$msg="📈 مصرف کل ادمین‌ها\n\n";

foreach($admins as $a){

$gb=round($a["total_usage"]/1024/1024/1024,2);

$msg.="👤 ".$a["username"]." → ".$gb." GB\n";

}

bot("sendMessage",[
"chat_id"=>$chat_id,
"text"=>$msg
]);

}

/* ================= ADD ADMIN ================= */

if($data=="add_admin"){

$steps[$chat_id]=[
"step"=>"admin_username"
];

file_put_contents($step_file,json_encode($steps));

bot("sendMessage",[
"chat_id"=>$chat_id,
"text"=>"👤 یوزرنیم ادمین را بفرست"
]);

}

/* ================= DELETE ADMIN ================= */

if($data=="delete_admin"){

$steps[$chat_id]=[
"step"=>"delete_admin"
];

file_put_contents($step_file,json_encode($steps));

bot("sendMessage",[
"chat_id"=>$chat_id,
"text"=>"نام ادمین را ارسال کن"
]);

}
