<?php
require_once 'db_connection.php';

// تابع تبدیل UTM به Lat/Lon برای Zone 39N
function utmToLatLon($x, $y, $zone = 39) {
    $a = 6378137.0;
    $e = 0.081819191;
    $e1sq = 0.006739497;
    $k0 = 0.9996;
    $x -= 500000.0;
    $y = floatval($y);

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

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

    $N1 = $a / sqrt(1 - pow($e * sin($phi1Rad), 2));
    $T1 = pow(tan($phi1Rad), 2);
    $C1 = $eccPrimeSquared * pow(cos($phi1Rad), 2);
    $R1 = $a * (1 - $e * $e) / 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 * $eccPrimeSquared) * pow($D,4)/24
        + (61 + 90 * $T1 + 298 * $C1 + 45 * $T1 * $T1 - 252 * $eccPrimeSquared - 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 * $eccPrimeSquared + 24 * $T1 * $T1) * pow($D,5)/120) / cos($phi1Rad);

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

// تابع ساخت فایل KML
function createKML($lat, $lon, $name, $date, $id) {
    $filename = "kml_files/{$id}_{$date}.kml";
    $kml = <<<KML
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
  <Placemark>
    <name><![CDATA[$name - $date]]></name>
    <description><![CDATA[موقعیت بازدید در تاریخ $date]]></description>
    <Point>
      <coordinates>$lon,$lat,0</coordinates>
    </Point>
  </Placemark>
</kml>
KML;

    file_put_contents($filename, $kml);
    return $filename;
}

// پوشه ذخیره‌سازی KML
if (!is_dir("kml_files")) {
    mkdir("kml_files", 0777, true);
}

// اجرای کوئری
$query = $conn->query("SELECT * FROM karshenasan");
while($row = $query->fetch_assoc()) {
    $name = $row['first_name'] . ' ' . $row['last_name'];
    $id = $row['id'];
    $x = $row['x'];
    $y = $row['y'];

    // فقط اگر مختصات معتبر باشد
    if (!empty($x) && !empty($y)) {
        $coords = utmToLatLon($x, $y);

        // بررسی تاریخ‌های مرحله‌ای
        for ($i = 1; $i <= 10; $i++) {
            $dateField = 'date' . $i;
            if (!empty($row[$dateField])) {
                $date = $row[$dateField];
                $kmlPath = createKML($coords['lat'], $coords['lon'], $name, $date, $id . "_$i");
                echo "<p>$name - تاریخ مرحله $i ($date): <a href='$kmlPath' target='_blank'>دانلود KML</a></p>";
            }
        }
    }
}
?>
