<!DOCTYPE html>
<html lang="fa">
<head>
    <meta charset="UTF-8">
    <title>تبدیل مختصات به Google Maps</title>
</head>
<body>
    <h2>تبدیل مختصات UTM به لینک Google Maps</h2>
    <form method="post">
        <label>مقدار X (Easting):</label>
        <input type="number" name="x" required><br><br>
        <label>مقدار Y (Northing):</label>
        <input type="number" name="y" required><br><br>
        <input type="submit" value="تبدیل و مشاهده موقعیت">
    </form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['x']) && isset($_POST['y'])) {
    $x = floatval($_POST['x']);
    $y = floatval($_POST['y']);

    function utm_to_latlon($easting, $northing, $zoneNumber = 39, $northernHemisphere = true) {
        $a = 6378137;
        $e = 0.081819191;
        $k0 = 0.9996;

        $x = $easting - 500000;
        $y = $northing;
        if (!$northernHemisphere) {
            $y -= 10000000;
        }

        $longOrigin = ($zoneNumber - 1) * 6 - 180 + 3;

        $e1 = (1 - sqrt(1 - $e * $e)) / (1 + sqrt(1 - $e * $e));
        $M = $y / $k0;
        $mu = $M / ($a * (1 - pow($e, 2)/4 - 3*pow($e,4)/64 - 5*pow($e,6)/256));

        $phi1Rad = $mu
            + (3 * $e1 / 2 - 27 * pow($e1,3) / 32) * sin(2 * $mu)
            + (21 * pow($e1,2) / 16 - 55 * pow($e1,4) / 32) * sin(4 * $mu)
            + (151 * pow($e1,3) / 96) * sin(6 * $mu)
            + (1097 * pow($e1,4) / 512) * sin(8 * $mu);

        $N1 = $a / sqrt(1 - pow($e * sin($phi1Rad), 2));
        $T1 = pow(tan($phi1Rad), 2);
        $C1 = pow($e, 2) / (1 - pow($e, 2)) * pow(cos($phi1Rad), 2);
        $R1 = $a * (1 - pow($e, 2)) / pow(1 - pow($e * sin($phi1Rad), 2), 1.5);
        $D = $x / ($N1 * $k0);

        $lat = $phi1Rad - ($N1 * tan($phi1Rad) / $R1) *
            ($D * $D / 2 - (5 + 3 * $T1 + 10 * $C1 - 4 * $C1 * $C1 - 9 * pow($e,2)) * pow($D, 4) / 24
            + (61 + 90 * $T1 + 298 * $C1 + 45 * $T1 * $T1 - 252 * pow($e,2) - 3 * $C1 * $C1) * pow($D, 6) / 720);
        
        $lon = deg2rad($longOrigin) + ($D - (1 + 2 * $T1 + $C1) * pow($D, 3) / 6
            + (5 - 2 * $C1 + 28 * $T1 - 3 * $C1 * $C1 + 8 * pow($e,2) + 24 * $T1 * $T1) * pow($D, 5) / 120) / cos($phi1Rad);

        return [
            'lat' => rad2deg($lat),
            'lng' => rad2deg($lon)
        ];
    }

    $coords = utm_to_latlon($x, $y);
    $google_maps_url = "https://www.google.com/maps?q={$coords['lat']},{$coords['lng']}";

    echo "<p><strong>لینک موقعیت روی نقشه:</strong><br>
          <a href='$google_maps_url' target='_blank'>$google_maps_url</a></p>";
}
?>
</body>
</html>
