<?php

$config = [
    'cloudflare' => [
        'api_token' => 'your_cloudflare_api_token',
        'zone_id' => 'your_zone_id',
        'api_url' => 'https://api.cloudflare.com/client/v4/zones/',
    ],
    'url_to_check' => 'https://www.example.com/ping',
    'hostname' => 'example.com',
    'ip_pool' => ['1.1.1.1', '2.2.2.2', '3.3.3.3'],
    'telegram' => [
        'bot_token' => 'your_bot_token',
        'chat_id' => 'your_chat_id',
    ],
];

function sendRequest(string $url, ?array $payload = null): ?int {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_USERAGENT, 'PrivateFlareUtility');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);

    if ($payload) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    }

    curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return $httpCode;
}

function cfHeaders(array $cfg): array {
    return [
        'X-Auth-Email: ' . $cfg['cloudflare']['email'],
        'X-Auth-Key: ' . $cfg['cloudflare']['api_key'],
        'Content-Type: application/json',
    ];
}

function getCloudflareRecords(array $cfg): array {
    $url = $cfg['cloudflare']['api_url'] . $cfg['cloudflare']['zone_id'] . '/dns_records?type=A&name=' . $cfg['hostname'];
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, cfHeaders($cfg));

    $result = curl_exec($ch);
    curl_close($ch);
    $data = json_decode($result, true);
    return $data['result'] ?? [];
}

function updateCloudflareRecord(array $cfg, string $recordId, string $newIp): void {
    $url = $cfg['cloudflare']['api_url'] . $cfg['cloudflare']['zone_id'] . '/dns_records/' . $recordId;

    $payload = json_encode([
        'type' => 'A',
        'name' => $cfg['hostname'],
        'content' => $newIp,
        'ttl' => 120,
        'proxied' => true,
    ]);

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, cfHeaders($cfg));

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

function notifyTelegram(array $cfg, string $message): void {
    $url = "https://api.telegram.org/bot" . $cfg['telegram']['bot_token'] . "/sendMessage";
    $data = [
        'chat_id' => $cfg['telegram']['chat_id'],
        'text' => $message,
        'parse_mode' => 'Markdown',
    ];

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_exec($ch);
    curl_close($ch);
}

// ---- main logic ----
$responseCode = sendRequest($config['url_to_check']);

if (!in_array($responseCode, [200, 301, 302])) {
    $records = getCloudflareRecords($config);

    foreach ($records as $record) {
    $currentIp = $record['content'];
    $recordId = $record['id'];

    $pool = $config['ip_pool'];
    $currentIndex = array_search($currentIp, $pool);

    if ($currentIndex === false) {
        // IP не найден в пуле — берем первый
        $newIp = $pool[0];
    } else {
        // Берем следующий по кругу
        $newIndex = ($currentIndex + 1) % count($pool);
        $newIp = $pool[$newIndex];
    }

    if ($newIp !== $currentIp) {
        updateCloudflareRecord($config, $recordId, $newIp);
        notifyTelegram($config, "🚨 PrivateFlare automation triggered 🚨\n {$config['hostname']} IP changed from {$currentIp} to {$newIp}");
    }
}
}
