<?php
function getLocationInfoByIp($ip) {
    $ip_data = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=" . $ip));

    if ($ip_data && $ip_data->geoplugin_countryName != null) {
        return $ip_data->geoplugin_city . ', ' . $ip_data->geoplugin_countryCode;
    }

    return 'Unknown';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // Form fields
    $name     = stripslashes(trim($_POST['name']));
    $email    = stripslashes(trim($_POST['email']));
    $phone    = stripslashes(trim($_POST['phone']));
    $countryCode = stripslashes(trim($_POST['countryCode']));
    $services = stripslashes(trim($_POST['services']));
    $message  = stripslashes(trim($_POST['message']));
    $url      = isset($_POST['url']) ? $_POST['url'] : '';

    // Tracking info
    $ip       = $_SERVER['REMOTE_ADDR'];
    $referrer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : 'Direct Visit';

    // Email config
    $emailTo = 'info@penguinglobalpublisher.com';
    $subject = "New Form Submission - Penguin Global Publisher";

    // Email body
    $body = "
        <h2>New Form Submission</h2>

        <p><strong>Name:</strong> {$name}</p>
        <p><strong>Email:</strong> {$email}</p>
        <p><strong>Phone:</strong> {$countryCode} {$phone}</p>
        <p><strong>Interested In:</strong> {$services}</p>
        <p><strong>Message:</strong><br>" . nl2br($message) . "</p>

        <hr>

        <p><strong>Page URL:</strong> {$url}</p>
        <p><strong>Submitted From:</strong> {$referrer}</p>
        <p><strong>IP Address:</strong> {$ip}</p>
        <p><strong>Location:</strong> " . getLocationInfoByIp($ip) . "</p>
    ";

    // Headers
    $headers  = "MIME-Version: 1.0\r\n";
    $headers .= "Content-type: text/html; charset=UTF-8\r\n";
    $headers .= "From: Penguin Global Publisher <admin@penguinglobalpublisher.com>\r\n";
    $headers .= "Reply-To: {$email}\r\n";

    // Send Email
    if (mail($emailTo, $subject, $body, $headers)) {

        header('Location: https://penguinglobalpublisher.com/thankyou/');
        exit();

    } else {

        echo "Error: Message could not be sent.";

    }

} else {

    header('Location: https://penguinglobalpublisher.com/');
    exit();

}
?>