<?php

// include 'check_ip.php';
$apiToken = $_GET['api_token'];

function createServer($apiToken, $serverName, $serverType, $image, $loc , $port) {
    $url = 'https://api.hetzner.cloud/v1/servers';
    
    $data = array(
        'name' => $serverName,
        'server_type' => $serverType,
        'labels' => ['email' => ''],
        'image' => $image,
        'location' => $loc,
    );
    
    $headers = array(
        'Authorization: Bearer '.$apiToken,
        'Content-Type: application/json',
    );
    
    $ch = curl_init();
    
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    $response = curl_exec($ch);
    
    if(curl_errno($ch)) {
        echo 'Error: '.curl_error($ch);
    }
    
    curl_close($ch);
    
    return json_decode($response);
}
function updateServer($apiToken, $serverID, $newServerName) {
    $url = 'https://api.hetzner.cloud/v1/servers/'.$serverID;
    
    $data = array(
        'name' => $newServerName
    );
    
    $headers = array(
        'Authorization: Bearer '.$apiToken,
        'Content-Type: application/json',
    );
    
    $ch = curl_init();
    
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    $response = curl_exec($ch);
    
    if(curl_errno($ch)) {
        echo 'Error: '.curl_error($ch);
    }
    
    curl_close($ch);
    
    return json_decode($response);
}

function deleteServer($apiToken, $serverId) {
    $url = 'https://api.hetzner.cloud/v1/servers/'.$serverId;
    
    $headers = array(
        'Authorization: Bearer '.$apiToken,
        'Content-Type: application/json',
    );
    
    $ch = curl_init();
    
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    $response = curl_exec($ch);
    
    if(curl_errno($ch)) {
        echo 'Error: '.curl_error($ch);
    }
    
    curl_close($ch);
    
    return json_decode($response);
}

function getServersList($apiToken) {
    $totalPages = 6;
    $servers = [];

    for ($page = 1; $page <= $totalPages; $page++) {
        $url = 'https://api.hetzner.cloud/v1/servers?per_page=50&page=' . $page;
        
        $headers = array(
            'Authorization: Bearer '.$apiToken,
            'Content-Type: application/json',
        );
        
        $ch = curl_init();
        
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        
        $response = curl_exec($ch);
        
        if(curl_errno($ch)) {
            echo 'Error: '.curl_error($ch);
            continue;
        }
        
        curl_close($ch);
        
        $serversListPage = json_decode($response);
        
        
        
        foreach ($serversListPage->servers as $server) {
            $targetDate = strtotime($server->created);
            $currentDate = time();
            $difference = $currentDate - $targetDate;
            $daysAgo = floor($difference / (60 * 60 * 24));
            $servers[] = ['name' => $server->name, 'ipv4' => $server->public_net->ipv4->ip,'ipv_id' => $server->public_net->ipv4->id,'ipv6' => $server->public_net->ipv6->ip,'id'=>$server->id,'model' => $server->server_type->name,'day' => $daysAgo];
        }
    }
    
    return json_encode($servers);
}

function power($apiToken, $server_id , $power) {
    $url = "https://api.hetzner.cloud/v1/servers/{$server_id}/actions/$power";
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Authorization: Bearer {$apiToken}",
        "Content-Type: application/json"
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    $response = curl_exec($ch);
    curl_close($ch);
    return json_decode($response);
}

function get_data($apiToken, $server_id) {
    $url = "https://api.hetzner.cloud/v1/servers/{$server_id}";
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Authorization: Bearer {$apiToken}",
        "Content-Type: application/json"
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    $data = json_decode($response, true);
    if (isset($data['server'])) {
        

        return $data;
    } else {
        return false;
    }
}

function rebuild($apiToken, $server_id , $os) {
    $url = "https://api.hetzner.cloud/v1/servers/{$server_id}/actions/rebuild";
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Authorization: Bearer {$apiToken}",
        "Content-Type: application/json"
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
        "image" => $os,
        'labels' => ['email' => '']
    ]));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    $result = json_decode($response, true);
    return $result;
}

function resetServerPassword($apiToken, $serverId) {
    $url = "https://api.hetzner.cloud/v1/servers/{$serverId}/actions/reset_password";

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        "Authorization: Bearer {$apiToken}",
        "Content-Type: application/json"
    ));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

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

    $result = json_decode($response, true);
    return $result;
}
function enable_rescue($apiToken, $serverId) {
    $url = "https://api.hetzner.cloud/v1/servers/{$serverId}/actions/enable_rescue";

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        "Authorization: Bearer {$apiToken}",
        "Content-Type: application/json"
    ));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

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

    $result = json_decode($response, true);
    return $result;
}
function disable_rescue($apiToken, $serverId) {
    $url = "https://api.hetzner.cloud/v1/servers/{$serverId}/actions/disable_rescue";

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        "Authorization: Bearer {$apiToken}",
        "Content-Type: application/json"
    ));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

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

    $result = json_decode($response, true);
    return $result;
}
function reboot($apiToken, $serverId) {
    $url = "https://api.hetzner.cloud/v1/servers/{$serverId}/actions/reboot";

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        "Authorization: Bearer {$apiToken}",
        "Content-Type: application/json"
    ));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

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

    $result = json_decode($response, true);
    return $result;
}
function resets($apiToken, $serverId) {
    $url = "https://api.hetzner.cloud/v1/servers/{$serverId}/actions/reset";

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        "Authorization: Bearer {$apiToken}",
        "Content-Type: application/json"
    ));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

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

    $result = json_decode($response, true);
    return $result;
}
function float_add($apiToken, $serverId , $name , $loc){
    $data = array(
        'name' => $name,
        'server' => $serverId,
        'home_location' => $loc,
        'type' => 'ipv4'
    );
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://api.hetzner.cloud/v1/floating_ips');
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Authorization: Bearer ' . $apiToken
    ));
    
    curl_exec($ch);
    curl_close($ch);
}

function float_list($apiToken) {
    $totalPages = 2;
    $servers = [];
    for ($page = 1; $page <= $totalPages; $page++) {
        $url = 'https://api.hetzner.cloud/v1/floating_ips?per_page=50&page=' . $page;
        $headers = array(
            'Authorization: Bearer '.$apiToken,
            'Content-Type: application/json',
        );
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        if(curl_errno($ch)) {
            echo 'Error: '.curl_error($ch);
        }
        curl_close($ch);
        $serversListPage = json_decode($response);
        foreach ($serversListPage->floating_ips as $server) {
            $servers[] = ['name' => $server->name, 'ipv4' => $server->ip,'id'=>$server->id];
        }
    }
    
    return json_encode($servers);
}
function float_del($apiToken , $serverId){
    $ch = curl_init();
    
    curl_setopt($ch, CURLOPT_URL, "https://api.hetzner.cloud/v1/floating_ips/".$serverId);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Authorization: Bearer ' . $apiToken
    ));
    
    $result = curl_exec($ch);
    if (curl_errno($ch)) {
        echo 'Error:' . curl_error($ch);
    }
    curl_close ($ch);
    
    return $result;
}

function change_plan($apiToken, $serverId , $plan){
    $data = array(
        'server_type' => $plan,
        'upgrade_disk' => true
    );
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://api.hetzner.cloud/v1/servers/$serverId/actions/change_type");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Authorization: Bearer ' . $apiToken,
        'Content-Type: application/json'
    ));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    $response = curl_exec($ch);
    curl_close($ch);
    echo $response;
}
function get_snapshot($api_key,$id,$name){
    $data = array(
        "description" => "$name"
    );
    
    $ch = curl_init();
    
    curl_setopt($ch, CURLOPT_URL, "https://api.hetzner.cloud/v1/servers/$id/actions/create_image");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    
    $headers = array();
    $headers[] = "Content-Type: application/json";
    $headers[] = "Authorization: Bearer $api_key";
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    
    $result = curl_exec($ch);
    
    if (curl_errno($ch)) {
        echo 'Error:' . curl_error($ch);
    } else {
        echo $result;
    }
    
    curl_close($ch);
}
function list_snapshot($api_key){
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, "https://api.hetzner.cloud/v1/images?type=snapshot");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    
    $headers = array();
    $headers[] = "Authorization: Bearer {$api_key}";
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    
    $result = curl_exec($ch);
    
    if (curl_errno($ch)) {
        echo 'Error:' . curl_error($ch);
    } else {
        echo $result;
    }
    
    curl_close($ch);
}
function del_snapshot($api_key,$id){
    $url = "https://api.hetzner.cloud/v1/images/$id";

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
    $headers = array(
        "Authorization: Bearer " . $api_key
    );
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    if ($response === false) {
        echo "خطا در ارسال درخواست: " . curl_error($ch);
    }
    curl_close($ch);
    
    echo $response;
}

function actions($api_key,$id){
    $url = "https://api.hetzner.cloud/v1/servers/$id/actions";

    $ch = curl_init($url);
    $headers = array(
        "Authorization: Bearer " . $api_key
    );
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    if ($response === false) {
        echo "خطا در ارسال درخواست: " . curl_error($ch);
    }
    curl_close($ch);
    
    echo $response;
}
function get_newip($api_key,$name,$loc){
    $url = "https://api.hetzner.cloud/v1/primary_ips";

    $data = array(
        "datacenter" => $loc,
        "assignee_type" => "server",
        "name" => $name,
        "type" => "ipv4"
    );
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Authorization: Bearer $api_key",
        "Content-Type: application/json",
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    
    $response = curl_exec($ch);
    
    if(curl_errno($ch)){
        echo 'خطا: ' . curl_error($ch);
    } else {
        echo $response;
    }
    
    curl_close($ch);
}
function delete_ipv($api_key,$id){
    $url = "https://api.hetzner.cloud/v1/primary_ips/$id";
        
    $headers = array(
        'Authorization: Bearer '.$api_key,
        'Content-Type: application/json',
    );
        
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        
    $response = curl_exec($ch);
        
    if(curl_errno($ch)) {
        echo 'Error: '.curl_error($ch);
    }
        
    curl_close($ch);
    echo $response;
}
function list_ipv4($api_key){
    $totalPages = 10;
    $servers = [];

    for ($page = 1; $page <= $totalPages; $page++) {
        $ch = curl_init();
    
        curl_setopt($ch, CURLOPT_URL, "https://api.hetzner.cloud/v1/primary_ips?per_page=50&page=$page");
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            "Authorization: Bearer $api_key"
        ));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        
        $response = curl_exec($ch);
        
        if(curl_errno($ch)){
            echo 'Error: ' . curl_error($ch);
        }
        
        curl_close($ch);
        $serversListPage = json_decode($response);
        foreach ($serversListPage->primary_ips as $server) {
            $servers[] = ['name' => $server->name, 'ipv4' => $server->ip,'ipv_id' => $server->assignee_id,'id'=>$server->id];
        }
        
    }
    echo json_encode($servers);
}
function update_ipv4s($api_key,$id1,$id2){

    $data = array(
        'assignee_id' => $id2,
        'assignee_type' => 'server'
    );
    
    $ch = curl_init();
    
    curl_setopt($ch, CURLOPT_URL, "https://api.hetzner.cloud/v1/primary_ips/" . $id1 . "/actions/assign");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        "Authorization: Bearer $api_key",
        "Content-Type: application/json"
    ));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    
    $response = curl_exec($ch);
    
    if (curl_errno($ch)) {
        echo 'Error: ' . curl_error($ch);
    }
    
    curl_close($ch);
    
    echo $response;
}
if(isset($_GET['create'])){
    $createdServer = createServer($apiToken, $_GET['name'], $_GET['server_type'], $_GET['os'],$_GET['loc'],$_GET['port']);
    echo json_encode($createdServer);
    
}
if(isset($_GET['delete'])){
    $deletedServer = deleteServer($apiToken, $_GET['id']);
    echo json_encode($deletedServer);
}
if(isset($_GET['list_all'])){
    echo getServersList($apiToken);
}
if(isset($_GET['poweroff'])){
    $deletedServer = power($apiToken, $_GET['id'] , 'poweroff');
    echo json_encode($deletedServer,true);
}
if(isset($_GET['poweron'])){
    $deletedServer = power($apiToken, $_GET['id'] , 'poweron');
    echo json_encode($deletedServer,true);
}
if(isset($_GET['data'])){
    $deletedServer = get_data($apiToken, $_GET['id']);
    $server_info = $deletedServer['server'];
    $ip = $server_info['public_net']['ipv4']['ip'];

// Get the OS name directly
$osName = $imageInfo['name'];
    echo json_encode(['outgoing_traffic' => $server_info['outgoing_traffic'],'loc' => $server_info['datacenter']['location']['country'],'image' => $server_info['image']['name'],'city' => $server_info['datacenter']['location']['city'],'name' => $server_info['name'],'ram'=>$server_info['server_type']['memory'],'cpu'=>$server_info['server_type']['cores'],'disk'=>$server_info['server_type']['disk'], 'ipv4' => $server_info['public_net']['ipv4']['ip'],'ipv6' => $server_info['public_net']['ipv6']['ip'],'status'=>$server_info['status']]);
}
if(isset($_GET['rebuild'])){
    $deletedServer = rebuild($apiToken, $_GET['id'] , $_GET['os']);
    echo json_encode($deletedServer,true);
}
if(isset($_GET['reset'])){
    $deletedServer = resetServerPassword($apiToken,$_GET['id']);
    echo json_encode(['root_password' => $deletedServer['root_password']]);
}if(isset($_GET['enable_rescue'])){
    $enable = enable_rescue($apiToken,$_GET['id']);
    echo json_encode(['root_password' => $enable['root_password']]);
}if(isset($_GET['reboot'])){
    $enable = reboot($apiToken,$_GET['id']);
    echo json_encode($enable,true);
}if(isset($_GET['resets'])){
    $enable = resets($apiToken,$_GET['id']);
    echo json_encode($enable,true);
}if(isset($_GET['disable_rescue'])){
    $enable = disable_rescue($apiToken,$_GET['id']);
    echo $enable;
}if(isset($_GET['update'])){
    $enable = updateServer($apiToken,$_GET['id'],$_GET['name']);
    echo $enable;
}if(isset($_GET['float'])){
    float_add($apiToken,$_GET['id'],$_GET['name'],$_GET['loc']);
}if(isset($_GET['float_list'])){
    $enable = float_list($apiToken);
    echo $enable;
}if(isset($_GET['float_del'])){
    $enable = float_del($apiToken,$_GET['id']);
    echo $enable;
}if(isset($_GET['plan'])){
    $enable = change_plan($apiToken,$_GET['id'],$_GET['plan']);
    echo $enable;
}if(isset($_GET['list_snapshot'])){
    list_snapshot($apiToken);
}if(isset($_GET['get_snapshot'])){
    get_snapshot($apiToken,$_GET['id'],$_GET['name']);
}if(isset($_GET['del_snapshot'])){
    del_snapshot($apiToken,$_GET['id']);
}if(isset($_GET['actions'])){
    actions($apiToken,$_GET['id']);
}elseif(isset($_GET['list_ipv4'])){
    list_ipv4($apiToken);
}elseif(isset($_GET['get_newip'])){
    get_newip($apiToken,$_GET['name'],$_GET['loc']);
}elseif(isset($_GET['delete_ipv'])){
    delete_ipv($apiToken,$_GET['id']);
}elseif(isset($_GET['update_ipv4s'])){
    update_ipv4s($apiToken,$_GET['id1'],$_GET['id2']);
}

?>