<?php
declare(strict_types=1);
require_once __DIR__ . '/../../conexion.php';
require_once __DIR__ . '/../../_helpers.php';
require_once __DIR__ . '/../../auth/guard.php';
$u = require_login();
require_admin($u);
$in = read_input();
$data = $in['data'] ?? null;
if (!is_array($data)) json_response(["ok"=>false, "message"=>"Datos inválidos."], 400);
$out = [];
foreach ($data as $key => $area) {
  $id = trim((string)$key);
  if ($id === '' || !is_array($area)) continue;
  $name = trim((string)($area['name'] ?? $id));
  $label = trim((string)($area['label'] ?? $name));
  $type = trim((string)($area['type'] ?? ''));

  if ($type === 'polygon') {
    $coords = $area['coordinates'] ?? [];
    if (!is_array($coords) || count($coords) < 3) continue;
    $clean = [];
    foreach ($coords as $pair) {
      if (!is_array($pair) || count($pair) < 2) continue;
      $lat = isset($pair[0]) ? (float)$pair[0] : null;
      $lng = isset($pair[1]) ? (float)$pair[1] : null;
      if (!is_finite($lat) || !is_finite($lng)) continue;
      $clean[] = [round($lat, 6), round($lng, 6)];
    }
    if (count($clean) < 3) continue;
    $out[$id] = [
      'id' => $id,
      'name' => $name,
      'label' => $label,
      'type' => 'polygon',
      'coordinates' => $clean,
      'updated_at' => date('c'),
      'updated_by' => $u['rut'] ?? null,
    ];
    continue;
  }

  // compatibilidad con formato antiguo centro + radio
  $lat = isset($area['lat']) ? (float)$area['lat'] : null;
  $lng = isset($area['lng']) ? (float)$area['lng'] : null;
  $radius = isset($area['radius']) ? max(50, (int)$area['radius']) : 450;
  if (!is_finite($lat) || !is_finite($lng)) continue;
  $out[$id] = [
    'id' => $id,
    'name' => $name,
    'label' => $label,
    'lat' => round($lat, 6),
    'lng' => round($lng, 6),
    'radius' => $radius,
    'updated_at' => date('c'),
    'updated_by' => $u['rut'] ?? null,
  ];
}
$file = __DIR__ . '/data/sectores_mapa.json';
if (!is_dir(dirname($file))) mkdir(dirname($file), 0775, true);
if (file_put_contents($file, json_encode($out, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)) === false) {
  json_response(["ok"=>false, "message"=>"No se pudo guardar el mapa de sectores."], 500);
}
fp_log_activity($pdo, $u, 'Configuración', 'Guardar mapa oficial', 'Se actualizó el mapa oficial de sectores.', 'mapa_sector', 'oficial');
json_response(["ok"=>true, "data"=>$out]);
