<?php
require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/../config/db.php';

$msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!empty($_FILES['kml_csv']['name'])) {
        $tmp  = $_FILES['kml_csv']['tmp_name'];
        $name = $_FILES['kml_csv']['name'];
        $ext  = strtolower(pathinfo($name, PATHINFO_EXTENSION));
        $zone = $_POST['zone'] ?? '0-300m';

        if ($ext === 'kml') {
            $result = importKml($pdo, $tmp, $zone);
            $msg = "success:{$result} parcels added/updated from KML.";
        } elseif ($ext === 'csv') {
            $swap   = !empty($_POST['swap_cols']);
            $result = importCsv($pdo, $tmp, $zone, $swap);
            $msg = "success:{$result} rows updated from CSV.";
        } else {
            $msg = 'error:Only KML or CSV files accepted.';
        }
    }
}

function importKml(PDO $pdo, string $file, string $zone): int {
    $doc = new DOMDocument();
    $doc->load($file);
    $placemarks = $doc->getElementsByTagName('Placemark');
    $count = 0;
    foreach ($placemarks as $pm) {
        $kmlId = $pm->getAttribute('id');
        $sheet = ''; $parcel = ''; $area = 0.0; $grid = 0; $coords = '';
        $sds = $pm->getElementsByTagName('SimpleData');
        foreach ($sds as $sd) {
            switch ($sd->getAttribute('name')) {
                case 'Sheet_Numb': $sheet  = trim($sd->textContent); break;
                case 'Parcel_No':  $parcel = trim($sd->textContent); break;
                case 'Shape_Area': $area   = (float)trim($sd->textContent); break;
                case 'Grid_map_p': $grid   = (int)trim($sd->textContent); break;
            }
        }
        $coordNodes = $pm->getElementsByTagName('coordinates');
        if ($coordNodes->length > 0) {
            $coordText = trim($coordNodes->item(0)->textContent);
            $coords = $coordText;
            $parts = preg_split('/\s+/', $coordText);
            $lats = []; $lngs = [];
            foreach ($parts as $p) {
                $xyz = explode(',', $p);
                if (count($xyz) >= 2) { $lngs[] = (float)$xyz[0]; $lats[] = (float)$xyz[1]; }
            }
            $centLat = $lats ? array_sum($lats) / count($lats) : 0;
            $centLng = $lngs ? array_sum($lngs) / count($lngs) : 0;
        } else { $centLat = 0; $centLng = 0; }

        $pdo->prepare('INSERT INTO parcels (kml_id, zone, sheet_number, parcel_no, shape_area_sqm, grid_map_page, polygon_coords, centroid_lat, centroid_lng)
                       VALUES (?,?,?,?,?,?,?,?,?)
                       ON DUPLICATE KEY UPDATE zone=VALUES(zone), sheet_number=VALUES(sheet_number), parcel_no=VALUES(parcel_no),
                       shape_area_sqm=VALUES(shape_area_sqm), polygon_coords=VALUES(polygon_coords), centroid_lat=VALUES(centroid_lat), centroid_lng=VALUES(centroid_lng)')
            ->execute([$kmlId, $zone, $sheet, $parcel, $area, $grid, $coords, $centLat, $centLng]);
        $count++;
    }
    return $count;
}

function importCsv(PDO $pdo, string $file, string $zone, bool $swapCols): int {
    $rows = array_map('str_getcsv', file($file));
    $count = 0;
    foreach ($rows as $i => $row) {
        if ($i === 0) continue;
        if ($swapCols && isset($row[1], $row[2])) [$row[1], $row[2]] = [$row[2], $row[1]];
        $parcelNo = trim($row[1] ?? '');
        $grid = (int)($row[3] ?? 0);
        if (!$parcelNo) continue;
        $pdo->prepare('UPDATE parcels SET grid_map_page = ? WHERE parcel_no = ? AND zone = ?')
            ->execute([$grid, $parcelNo, $zone]);
        $count++;
    }
    return $count;
}

$isSuccess = str_starts_with($msg, 'success:');
$isError   = str_starts_with($msg, 'error:');
$msgText   = $msg ? substr($msg, strpos($msg, ':') + 1) : '';
?>

<div class="mb-6">
  <h2 class="text-xl font-bold text-slate-800">Import KML / CSV Data</h2>
  <p class="text-sm text-slate-500 mt-0.5">Upload KML files to import parcels, or CSV to update grid map pages</p>
</div>

<?php if ($isSuccess): ?>
<div class="mb-5 flex items-center gap-3 px-4 py-3 bg-green-50 border border-green-200 rounded-xl text-green-700 text-sm">
  ✅ <?= htmlspecialchars($msgText) ?>
</div>
<?php elseif ($isError): ?>
<div class="mb-5 flex items-center gap-3 px-4 py-3 bg-red-50 border border-red-200 rounded-xl text-red-700 text-sm">
  ⚠️ <?= htmlspecialchars($msgText) ?>
</div>
<?php endif ?>

<div class="grid grid-cols-1 md:grid-cols-2 gap-6">

  <!-- Upload form -->
  <div class="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
    <h3 class="font-semibold text-slate-700 mb-5">Upload File</h3>
    <form method="post" enctype="multipart/form-data" class="space-y-5">

      <div>
        <label class="block text-xs font-medium text-slate-600 mb-1.5">Zone</label>
        <select name="zone"
                class="w-full px-3 py-2.5 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 bg-gray-50">
          <option value="0-300m">0–300m (Red zone)</option>
          <option value="300-400m">300–400m (Orange zone)</option>
          <option value="400-900m">400–900m (Blue zone)</option>
        </select>
      </div>

      <div>
        <label class="block text-xs font-medium text-slate-600 mb-1.5">File (KML or CSV)</label>
        <div class="border-2 border-dashed border-gray-200 rounded-xl p-6 text-center hover:border-blue-300 transition-colors">
          <div class="text-3xl mb-2">📁</div>
          <p class="text-sm text-slate-500 mb-3">Drop file here or click to browse</p>
          <input type="file" name="kml_csv" accept=".kml,.csv" required
                 class="block mx-auto text-sm text-slate-500 file:mr-3 file:py-1.5 file:px-4
                        file:rounded-lg file:border-0 file:text-sm file:font-medium
                        file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100">
        </div>
      </div>

      <label class="flex items-center gap-3 cursor-pointer select-none">
        <input type="checkbox" name="swap_cols" value="1"
               class="w-4 h-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500">
        <div>
          <div class="text-sm font-medium text-slate-700">Swap columns 2 &amp; 3</div>
          <div class="text-xs text-slate-400">Required for 900m.csv format</div>
        </div>
      </label>

      <button type="submit"
              class="w-full py-3 bg-blue-600 hover:bg-blue-700 text-white font-semibold text-sm rounded-xl transition-colors shadow-sm">
        Import File
      </button>
    </form>
  </div>

  <!-- Guide -->
  <div class="space-y-4">
    <div class="bg-blue-50 border border-blue-100 rounded-2xl p-5">
      <h4 class="font-semibold text-blue-800 text-sm mb-3">📄 KML Import</h4>
      <ul class="text-xs text-blue-700 space-y-1.5">
        <li>• Imports parcel boundaries and attributes</li>
        <li>• Reads: Sheet_Numb, Parcel_No, Shape_Area, Grid_map_p</li>
        <li>• Calculates centroid automatically</li>
        <li>• Existing parcels updated (ON DUPLICATE KEY)</li>
      </ul>
    </div>
    <div class="bg-amber-50 border border-amber-100 rounded-2xl p-5">
      <h4 class="font-semibold text-amber-800 text-sm mb-3">📊 CSV Import</h4>
      <ul class="text-xs text-amber-700 space-y-1.5">
        <li>• Updates grid map page numbers only</li>
        <li>• Format: ID, Parcel_No, Sheet, Grid_Page</li>
        <li>• Enable "Swap columns" for 400–900m.csv</li>
        <li>• Matches by Parcel_No + Zone</li>
      </ul>
    </div>
    <div class="bg-slate-50 border border-slate-100 rounded-2xl p-5">
      <h4 class="font-semibold text-slate-700 text-sm mb-2">🗺 Zone colors</h4>
      <div class="space-y-1.5 text-xs">
        <div class="flex items-center gap-2"><span class="w-3 h-3 rounded-full bg-red-500 flex-shrink-0"></span><span class="text-slate-600">0–300m — Critical zone</span></div>
        <div class="flex items-center gap-2"><span class="w-3 h-3 rounded-full bg-orange-500 flex-shrink-0"></span><span class="text-slate-600">300–400m — High zone</span></div>
        <div class="flex items-center gap-2"><span class="w-3 h-3 rounded-full bg-blue-500 flex-shrink-0"></span><span class="text-slate-600">400–900m — Standard zone</span></div>
      </div>
    </div>
  </div>

</div>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
