<?php
// cliente_form.php — Cadastrar / Editar cliente (LAYOUT REFORMULADO 2026 - KML FINAL v6)
$pageActive = 'clientes';
require_once __DIR__ . '/functions.php';
require_once __DIR__ . '/auth.php';
requireLogin();

$id      = (int)($_GET['id'] ?? 0);
$cliente = $id ? getClienteById($id) : null;
$erros   = [];
$sucesso = '';
$pageTitle = $id ? 'Editar Cliente' : 'Novo Cliente';

function pastaCliente(int $cid): string {
    $dir = __DIR__ . "/uploads/clientes/{$cid}";
    if (!is_dir($dir)) mkdir($dir, 0755, true);
    return $dir;
}

function salvarFoto(array $file, int $cid, string $tipo): ?string {
    $ext = strtolower(pathinfo($file['name'] ?? '', PATHINFO_EXTENSION));
    if ($ext === '' || strlen($ext) > 5) {
        $mimeMap = ['image/jpeg'=>'jpg','image/jpg'=>'jpg','image/png'=>'png',
                    'image/webp'=>'webp','image/gif'=>'gif','image/heic'=>'jpg','image/heif'=>'jpg'];
        $ext = $mimeMap[$file['type'] ?? ''] ?? '';
    }
    if ($ext === 'jpeg') $ext = 'jpg';
    if (!in_array($ext, ['jpg','png','webp','gif'])) {
        $h = @fopen($file['tmp_name'], 'rb');
        $m = $h ? bin2hex(fread($h, 4)) : '';
        if ($h) fclose($h);
        if (str_starts_with($m,'ffd8ff'))       $ext = 'jpg';
        elseif (str_starts_with($m,'89504e47')) $ext = 'png';
        elseif (str_starts_with($m,'52494646')) $ext = 'webp';
        else return null;
    }
    if (($file['size'] ?? 0) > 8*1024*1024) return null;
    if (!is_uploaded_file($file['tmp_name'] ?? '')) return null;
    $dir  = pastaCliente($cid);
    $nome = $tipo . '_' . date('YmdHis') . '_' . mt_rand(1000,9999) . '.' . $ext;
    return move_uploaded_file($file['tmp_name'], "$dir/$nome")
        ? "uploads/clientes/$cid/$nome"
        : null;
}

// ═══════════════════ SALVAR TELEFONES ADICIONAIS ═══════════════════
function salvarTelefonesAdicionais(int $clienteId, array $telefones, array $tipos): void {
    // Remove telefones existentes
    pdo()->prepare("DELETE FROM cliente_contatos WHERE cliente_id = ?")->execute([$clienteId]);
    
    // Insere os novos
    $stmt = pdo()->prepare("INSERT INTO cliente_contatos (cliente_id, telefone, tipo, ordem) VALUES (?, ?, ?, ?)");
    foreach ($telefones as $i => $tel) {
        $tel = trim($tel);
        if ($tel === '') continue;
        $tipo = trim($tipos[$i] ?? 'Celular');
        $stmt->execute([$clienteId, $tel, $tipo, $i]);
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCsrf($_POST['csrf_token'] ?? '')) die('CSRF inválido');
    $destino = trim($_POST['destino_pos_salvar'] ?? 'editar');
    $data = [
        'nome'                 => mb_convert_case(trim($_POST['nome'] ?? ''), MB_CASE_TITLE, 'UTF-8'),
        'documento'            => trim($_POST['documento'] ?? ''),
        'telefone'             => trim($_POST['telefone'] ?? ''),
        'email'                => trim($_POST['email'] ?? ''),
        'endereco_cep'         => trim($_POST['endereco_cep'] ?? ''),
        'endereco_logradouro'  => trim($_POST['endereco_logradouro'] ?? ''),
        'endereco_numero'      => trim($_POST['endereco_numero'] ?? ''),
        'endereco_complemento' => trim($_POST['endereco_complemento'] ?? ''),
        'endereco_bairro'      => trim($_POST['endereco_bairro'] ?? ''),
        'endereco_cidade'      => trim($_POST['endereco_cidade'] ?? ''),
        'latitude'             => trim($_POST['latitude'] ?? '') ?: null,
        'longitude'            => trim($_POST['longitude'] ?? '') ?: null,
        'vlan'                 => trim($_POST['vlan'] ?? ''),
        'cod_conexao'          => trim($_POST['cod_conexao'] ?? '') ?: null,
        'pppoe_usuario'        => trim($_POST['pppoe_usuario'] ?? ''),
        'pppoe_senha'          => trim($_POST['pppoe_senha'] ?? ''),
        'wifi_ssid_2g'         => trim($_POST['wifi_ssid_2g'] ?? ''),
        'wifi_senha_2g'        => trim($_POST['wifi_senha_2g'] ?? ''),
        'wifi_ssid_5g'         => trim($_POST['wifi_ssid_5g'] ?? ''),
        'wifi_senha_5g'        => trim($_POST['wifi_senha_5g'] ?? ''),
        'plano'                => trim($_POST['plano'] ?? ''),
        'possui_roteador'      => isset($_POST['possui_roteador']) ? 1 : 0,
        'modelo_roteador'      => trim($_POST['modelo_roteador'] ?? '') ?: null,
        'password_equipamento' => trim($_POST['password_equipamento'] ?? ''),
        'possui_repetidor'     => isset($_POST['possui_repetidor']) ? 1 : 0,
        'modelo_repetidor'     => trim($_POST['modelo_repetidor'] ?? '') ?: null,
        'qtd_repetidor'        => max(0,(int)($_POST['qtd_repetidor'] ?? 0)),
        'possui_cameras'       => isset($_POST['possui_cameras']) ? 1 : 0,
        'camera_local'         => trim($_POST['camera_local'] ?? ''),
        'ativo'                => isset($_POST['ativo']) ? 1 : 0,
        'bloqueado'            => isset($_POST['bloqueado']) ? 1 : 0,
        'observacoes'          => trim($_POST['observacoes'] ?? ''),
        'cto_nome'             => trim($_POST['cto_nome'] ?? '') ?: null,
        'olt_gps'              => trim($_POST['olt_gps']  ?? '') ?: null,
        'marcacao_kml_nome'    => trim($_POST['marcacao_kml_nome'] ?? '') ?: null,
        'marcacao_kml_tipo'    => trim($_POST['marcacao_kml_tipo'] ?? '') ?: null,
        'marcacao_kml_lat'     => trim($_POST['marcacao_kml_lat'] ?? '') ?: null,
        'marcacao_kml_lng'     => trim($_POST['marcacao_kml_lng'] ?? '') ?: null,
        'marcacao_kml_dist'    => trim($_POST['marcacao_kml_dist'] ?? '') ?: null,
    ];
    $colsExistentes = [];
    try { $cols = pdo()->query("SHOW COLUMNS FROM clientes")->fetchAll(PDO::FETCH_COLUMN); $colsExistentes = array_flip($cols); } catch (PDOException $e) {}
    if (isset($colsExistentes['mac_key'])) $data['mac_key'] = trim($_POST['mac_key'] ?? '');
    foreach (['cto_nome','olt_gps','marcacao_kml_nome','marcacao_kml_tipo','marcacao_kml_lat','marcacao_kml_lng','marcacao_kml_dist'] as $col) {
        if (!isset($colsExistentes[$col])) unset($data[$col]);
    }
    if (!$data['nome']) $erros[] = 'Nome é obrigatório.';
    if (empty($data['modelo_repetidor'])) $data['qtd_repetidor'] = 0;
    if (empty($erros)) {
        try {
            if ($id) {
                $sets = implode(',', array_map(fn($k) => "`$k` = :$k", array_keys($data)));
                $data['id'] = $id;
                pdo()->prepare("UPDATE clientes SET $sets WHERE id = :id")->execute($data);
                // Salva telefones adicionais
                salvarTelefonesAdicionais($id, $_POST['telefones_extra'] ?? [], $_POST['telefones_tipo'] ?? []);
                
                if (!empty($_FILES['foto_fachada']['name'])) {
                    $arqF = ['name'=>$_FILES['foto_fachada']['name'],'tmp_name'=>$_FILES['foto_fachada']['tmp_name'],'size'=>$_FILES['foto_fachada']['size'],'type'=>$_FILES['foto_fachada']['type']??''];
                    $cam = salvarFoto($arqF, $id, 'fachada');
                    if ($cam) pdo()->prepare("INSERT INTO clientes_fotos (cliente_id,caminho_arquivo,descricao,tipo) VALUES (?,?,'Fachada da residência','INSTALACAO')")->execute([$id,$cam]);
                }
                $sucesso = 'Cliente atualizado com sucesso!';
                $cliente = getClienteById($id);
            } else {
                $data['data_cadastro'] = date('Y-m-d H:i:s');
                $cols = implode(',', array_map(fn($k) => "`$k`", array_keys($data)));
                $vals = implode(',', array_map(fn($k) => ":$k", array_keys($data)));
                pdo()->prepare("INSERT INTO clientes ($cols) VALUES ($vals)")->execute($data);
                $newId = (int)pdo()->lastInsertId();
                // Salva telefones adicionais
                salvarTelefonesAdicionais($newId, $_POST['telefones_extra'] ?? [], $_POST['telefones_tipo'] ?? []);
                
                if (!empty($_FILES['foto_fachada']['name'])) {
                    $arqF = ['name'=>$_FILES['foto_fachada']['name'],'tmp_name'=>$_FILES['foto_fachada']['tmp_name'],'size'=>$_FILES['foto_fachada']['size'],'type'=>$_FILES['foto_fachada']['type']??''];
                    $cam = salvarFoto($arqF, $newId, 'fachada');
                    if ($cam) pdo()->prepare("INSERT INTO clientes_fotos (cliente_id,caminho_arquivo,descricao,tipo) VALUES (?,?,'Fachada da residência','INSTALACAO')")->execute([$newId,$cam]);
                }
                switch ($destino) {
                    case 'os':   header("Location: os_form.php?cliente_id=$newId"); break;
                    case 'geo':  header("Location: geocalizacao.php?id=$newId"); break;
                    case 'infra':header("Location: infraestrutura.php?id=$newId"); break;
                    default:     header("Location: cliente_detalhe.php?id=$newId&msg=Cliente+cadastrado+com+sucesso!"); break;
                }
                exit;
            }
        } catch (PDOException $e) { $erros[] = 'Erro ao salvar: ' . $e->getMessage(); }
    }
}

// ═══════════════════ BUSCAR TELEFONES ADICIONAIS ═══════════════════
$telefonesAdicionais = [];
if ($id) {
    try {
        $stmtTel = pdo()->prepare("SELECT telefone, tipo FROM cliente_contatos WHERE cliente_id = ? ORDER BY ordem ASC");
        $stmtTel->execute([$id]);
        $telefonesAdicionais = $stmtTel->fetchAll();
    } catch (PDOException $e) {}
}

$fotosExistentes = [];
if ($id) {
    $stmtF = pdo()->prepare("SELECT * FROM clientes_fotos WHERE cliente_id = ? ORDER BY data_envio DESC");
    $stmtF->execute([$id]);
    $fotosExistentes = $stmtF->fetchAll();
}
$fotoFachada = null;
foreach ($fotosExistentes as $f) {
    if ($f['tipo']==='INSTALACAO' && str_contains($f['caminho_arquivo'],'fachada')) { $fotoFachada=$f; break; }
}
$fotosCamera = array_filter($fotosExistentes, fn($f) => $f['tipo']==='CAMERA');

// Verificar se o cliente tem marcação KML salva
$marcacaoSalva = $v['marcacao_kml_nome'] ?? ($cliente['marcacao_kml_nome'] ?? '');
$clienteTemMarcacao = !empty($marcacaoSalva);

// Buscar clientes vinculados a esta caixa
$clientesNaCaixa = [];
if ($marcacaoSalva && $id) {
    try {
        $stmtC = pdo()->prepare("SELECT id, nome, plano, endereco_cidade FROM clientes WHERE (cto_nome = ? OR marcacao_kml_nome = ?) AND id != ? LIMIT 20");
        $stmtC->execute([$marcacaoSalva, $marcacaoSalva, $id]);
        $clientesNaCaixa = $stmtC->fetchAll();
    } catch (PDOException $e) {}
}

$v = $cliente ?? array_fill_keys(['nome','documento','telefone','email','endereco_cep',
    'endereco_logradouro','endereco_numero','endereco_complemento','endereco_bairro',
    'endereco_cidade','latitude','longitude','vlan','cod_conexao','pppoe_usuario',
    'pppoe_senha','wifi_ssid_2g','wifi_senha_2g','wifi_ssid_5g','wifi_senha_5g',
    'mac_key','plano','possui_roteador','modelo_roteador','password_equipamento',
    'possui_repetidor','modelo_repetidor','qtd_repetidor','possui_cameras','camera_local',
    'ativo','bloqueado','observacoes','cto_nome','olt_gps','marcacao_kml_nome','marcacao_kml_tipo',
    'marcacao_kml_lat','marcacao_kml_lng','marcacao_kml_dist'], '');
if (!$id) $v['ativo'] = 1;

$planos     = ['50 MB','100 MB','150 MB','200 MB','250 MB','300 MB','350 MB','400 MB','450 MB','500 MB','550 MB','600 MB','650 MB','700 MB','750 MB','800 MB','850 MB','900 MB','950 MB','1000 MB'];
$roteadores = ['Zyxel','Huawei','Huawei 4','TP-Link','ONU'];
$repetidores= ['Zyxel Mesh','Huawei Mesh','TP-Link Mesh'];
$cidades    = ['Jales','Paranapuã','Santa Albertina','Mesópolis','Populina','Dirce Reis'];

require_once __DIR__ . '/includes/header.php';
?>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.min.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css"/>

<style>
:root {
    --kml-cx: #00d4ff; --kml-cto: #0ea5e9; --kml-poste: #94a3b8;
    --kml-ceo: #ec4899; --kml-fo: #a855f7; --kml-torre: #ef4444;
    --kml-reserva: #fb923c; --kml-emenda: #f59e0b; --kml-pop: #eab308;
    --kml-ptp: #22c55e; --kml-cr: #8b5cf6; --kml-outro: #94a3b8;
    --kml-feeder: #ff4444; --kml-ramal: #ffaa7f; --kml-drop: #ff7700;
    --kml-cabo: #ff2222; --kml-splitter: #6366f1; --kml-dio: #14b8a6;
    --kml-nap: #f472b6; --kml-cep: #84cc16;
}

.form-card{background:var(--card);border:1px solid var(--border);border-radius:10px;padding:12px 16px;margin-bottom:10px}
.form-section-title{font-size:12px;font-weight:700;color:var(--cyan);margin-bottom:8px;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:8px}
.form-grid{display:grid;grid-template-columns:1fr 1fr;gap:8px}
.form-grid.cols3{grid-template-columns:1fr 1fr 1fr;gap:8px}
.form-grid.cols4{grid-template-columns:1fr 1fr 1fr 1fr;gap:8px}
@media(max-width:767px){.form-grid,.form-grid.cols3,.form-grid.cols4{grid-template-columns:1fr}}
.form-group.full{grid-column:1/-1}
.form-label{display:block;font-size:10px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:.5px;margin-bottom:4px}
.form-input,.form-select,.form-textarea{width:100%;padding:7px 10px;background:var(--card2);border:1px solid var(--border);border-radius:8px;color:var(--text);font-family:var(--ui);font-size:13px;transition:border .15s}
.form-input:focus,.form-select:focus,.form-textarea:focus{outline:none;border-color:var(--cyan);box-shadow:0 0 0 3px rgba(0,212,255,.08)}
.form-select{appearance:none;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%234a6a8a' d='M6 8L1 3h10z'/%3E%3C/svg%3E");background-repeat:no-repeat;background-position:right 10px center;padding-right:30px}
.form-textarea{resize:vertical;min-height:70px}
.form-hint{font-size:9px;color:var(--muted);margin-top:3px;display:block}
.upload-zone{border:2px dashed var(--border2);border-radius:10px;padding:22px 16px;text-align:center;cursor:pointer;transition:.2s;position:relative}
.upload-zone:hover,.upload-zone.over{border-color:var(--cyan);background:rgba(0,212,255,.04)}
.upload-zone input[type=file]{position:absolute;inset:0;opacity:0;cursor:pointer;width:100%;height:100%}
.upload-zone-icon{font-size:26px;margin-bottom:6px}
.upload-zone-label{font-size:12px;color:var(--muted)}
.upload-zone-label b{color:var(--text)}
.upload-zone-hint{font-size:10px;color:var(--muted);margin-top:3px;font-family:var(--mono)}
.fotos-grid{display:flex;flex-wrap:wrap;gap:8px;margin-top:10px}
.foto-card{width:90px;height:90px;border-radius:8px;overflow:hidden;border:1px solid var(--border);position:relative;flex-shrink:0}
.foto-card img{width:100%;height:100%;object-fit:cover;display:block}
.foto-card-del{position:absolute;top:3px;right:3px;background:rgba(239,68,68,.88);border:none;border-radius:4px;color:#fff;font-size:10px;cursor:pointer;padding:2px 6px;line-height:1}
.cameras-section{display:none}
.cameras-section.show{display:block}
.btn-gps{background:rgba(16,185,129,.1);border:1px solid var(--green);color:var(--green);font-weight:600;transition:.15s;white-space:nowrap;font-size:11px;padding:6px 12px;border-radius:8px;cursor:pointer}
.btn-gps:hover{background:var(--green);color:#050e1a}
.btn-gps:disabled{opacity:.5;cursor:not-allowed}
.btn-gps .pulse{display:inline-block;width:8px;height:8px;border-radius:50%;background:var(--green);margin-right:6px;animation:pulse-anim 1.5s infinite}
@keyframes pulse-anim{0%,100%{opacity:1}50%{opacity:.3}}
.geo-status{padding:8px 14px;border-radius:8px;font-size:11px;font-family:var(--mono);display:flex;align-items:center}
.geo-status.ok{background:rgba(16,185,129,.1);color:var(--green)}
.geo-status.loading{background:rgba(0,212,255,.08);color:var(--cyan)}
.geo-status.err{background:rgba(239,68,68,.08);color:var(--red)}

.cliente-badge-fixa{background:var(--card);border:1px solid var(--border);border-radius:10px;padding:12px 14px;margin-top:12px;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px}
.cliente-badge-info{flex:1;min-width:200px}
.cliente-badge-nome{font-size:13px;font-weight:700;color:var(--text);margin-bottom:2px}
.cliente-badge-endereco{font-size:11px;color:var(--muted);font-family:var(--mono);word-break:break-word;line-height:1.4}
.cliente-badge-links{display:flex;gap:6px}
.cliente-badge-links a{width:28px;height:28px;border-radius:5px;display:flex;align-items:center;justify-content:center;text-decoration:none;font-size:10px;font-weight:800}
.caixa-link-maps{background:#4285F4;color:#fff}
.caixa-link-waze{background:#33ccff;color:#000}
.caixa-link-sv{background:#F4B400;color:#000}

@keyframes pulse-map{0%,100%{transform:scale(1);opacity:.6}50%{transform:scale(1.6);opacity:0}}

/* ═══════ LOADING ═══════ */
.mapa-loading{position:absolute;top:0;left:0;right:0;bottom:0;z-index:1000;background:rgba(10,18,32,.9);display:flex;align-items:center;justify-content:center;border-radius:12px;flex-direction:column;gap:12px}
.mapa-loading-spinner{width:40px;height:40px;border:3px solid var(--border);border-top-color:var(--cyan);border-radius:50%;animation:spin .8s linear infinite}
.mapa-loading-text{font-size:11px;color:var(--cyan);font-family:var(--mono)}

/* ═══════ TELEFONES ═══════ */
.telefones-extra{margin-top:6px}
.telefone-row{display:flex;gap:6px;margin-bottom:4px;align-items:center}
.telefone-row input{flex:1}
.telefone-row select{width:90px;flex-shrink:0}
.btn-add-tel{display:inline-flex;align-items:center;gap:4px;padding:4px 10px;background:rgba(0,212,255,.08);border:1px dashed var(--cyan);border-radius:6px;color:var(--cyan);font-size:10px;cursor:pointer;margin-top:4px;font-weight:600}
.btn-add-tel:hover{background:rgba(0,212,255,.15)}
.btn-rem-tel{width:24px;height:24px;border-radius:4px;background:rgba(239,68,68,.15);border:1px solid rgba(239,68,68,.3);color:var(--red);cursor:pointer;font-size:12px;display:flex;align-items:center;justify-content:center;flex-shrink:0}
.btn-rem-tel:hover{background:rgba(239,68,68,.3)}

/* ═══════ BARRA DE FILTROS KML ═══════ */
.kml-filtros-bar{width:100%;margin:6px 0;display:none}
.kml-filtros-inner{background:var(--card);border:1px solid var(--border);border-radius:10px;padding:8px 10px}
.kml-filtros-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:6px;flex-wrap:wrap;gap:6px}
.kml-filtros-titulo{font-size:10px;color:var(--muted);font-family:var(--mono);letter-spacing:1px}
.kml-filtros-scroll{display:flex;gap:5px;overflow-x:auto;overflow-y:hidden;scroll-behavior:smooth;-webkit-overflow-scrolling:touch;padding-bottom:4px}
.kml-filtros-scroll::-webkit-scrollbar{height:3px}
.kml-filtros-scroll::-webkit-scrollbar-track{background:var(--card2);border-radius:2px}
.kml-filtros-scroll::-webkit-scrollbar-thumb{background:var(--border2);border-radius:2px}
.kml-chip{flex:0 0 auto;padding:4px 9px;border-radius:12px;font-size:8px;font-weight:700;font-family:var(--mono);cursor:pointer;border:1px solid var(--border);background:var(--card2);color:var(--muted);white-space:nowrap;transition:all .15s;display:flex;align-items:center;gap:4px;user-select:none}
.kml-chip:hover{opacity:.85}
.kml-chip.on{border-width:2px}
.kml-chip-dot{width:5px;height:5px;border-radius:50%;flex-shrink:0}
/* Cores por tipo */
.kml-chip-cx.on{background:rgba(0,212,255,.12);color:var(--kml-cx);border-color:var(--kml-cx)}.kml-chip-cx .kml-chip-dot{background:var(--kml-cx)}
.kml-chip-cto.on{background:rgba(14,165,233,.12);color:var(--kml-cto);border-color:var(--kml-cto)}.kml-chip-cto .kml-chip-dot{background:var(--kml-cto)}
.kml-chip-poste.on{background:rgba(148,163,184,.12);color:var(--kml-poste);border-color:var(--kml-poste)}.kml-chip-poste .kml-chip-dot{background:var(--kml-poste)}
.kml-chip-ceo.on{background:rgba(236,72,153,.12);color:var(--kml-ceo);border-color:var(--kml-ceo)}.kml-chip-ceo .kml-chip-dot{background:var(--kml-ceo)}
.kml-chip-fo.on{background:rgba(168,85,247,.12);color:var(--kml-fo);border-color:var(--kml-fo)}.kml-chip-fo .kml-chip-dot{background:var(--kml-fo)}
.kml-chip-torre.on{background:rgba(239,68,68,.12);color:var(--kml-torre);border-color:var(--kml-torre)}.kml-chip-torre .kml-chip-dot{background:var(--kml-torre)}
.kml-chip-reserva.on{background:rgba(251,146,60,.12);color:var(--kml-reserva);border-color:var(--kml-reserva)}.kml-chip-reserva .kml-chip-dot{background:var(--kml-reserva)}
.kml-chip-emenda.on{background:rgba(245,158,11,.12);color:var(--kml-emenda);border-color:var(--kml-emenda)}.kml-chip-emenda .kml-chip-dot{background:var(--kml-emenda)}
.kml-chip-pop.on{background:rgba(234,179,8,.12);color:var(--kml-pop);border-color:var(--kml-pop)}.kml-chip-pop .kml-chip-dot{background:var(--kml-pop)}
.kml-chip-ptp.on{background:rgba(34,197,94,.12);color:var(--kml-ptp);border-color:var(--kml-ptp)}.kml-chip-ptp .kml-chip-dot{background:var(--kml-ptp)}
.kml-chip-cr.on{background:rgba(139,92,246,.12);color:var(--kml-cr);border-color:var(--kml-cr)}.kml-chip-cr .kml-chip-dot{background:var(--kml-cr)}
.kml-chip-feeder.on{background:rgba(255,68,68,.12);color:var(--kml-feeder);border-color:var(--kml-feeder)}.kml-chip-feeder .kml-chip-dot{background:var(--kml-feeder)}
.kml-chip-ramal.on{background:rgba(255,170,127,.12);color:var(--kml-ramal);border-color:var(--kml-ramal)}.kml-chip-ramal .kml-chip-dot{background:var(--kml-ramal)}
.kml-chip-drop.on{background:rgba(255,119,0,.12);color:var(--kml-drop);border-color:var(--kml-drop)}.kml-chip-drop .kml-chip-dot{background:var(--kml-drop)}
.kml-chip-cabo.on{background:rgba(255,34,34,.12);color:var(--kml-cabo);border-color:var(--kml-cabo)}.kml-chip-cabo .kml-chip-dot{background:var(--kml-cabo)}
.kml-chip-splitter.on{background:rgba(99,102,241,.12);color:var(--kml-splitter);border-color:var(--kml-splitter)}.kml-chip-splitter .kml-chip-dot{background:var(--kml-splitter)}
.kml-chip-dio.on{background:rgba(20,184,166,.12);color:var(--kml-dio);border-color:var(--kml-dio)}.kml-chip-dio .kml-chip-dot{background:var(--kml-dio)}
.kml-chip-nap.on{background:rgba(244,114,182,.12);color:var(--kml-nap);border-color:var(--kml-nap)}.kml-chip-nap .kml-chip-dot{background:var(--kml-nap)}
.kml-chip-cep.on{background:rgba(132,204,22,.12);color:var(--kml-cep);border-color:var(--kml-cep)}.kml-chip-cep .kml-chip-dot{background:var(--kml-cep)}
.kml-chip-outro.on{background:rgba(148,163,184,.12);color:var(--kml-outro);border-color:var(--kml-outro)}.kml-chip-outro .kml-chip-dot{background:var(--kml-outro)}

/* ═══════ PAINEL DA MARCAÇÃO ═══════ */
.painel-marcacao{display:none;background:var(--card);border:1px solid var(--border);border-radius:10px;padding:12px 14px;margin-top:8px}
.painel-marcacao-nome{font-size:14px;font-weight:800;line-height:1.2}
.painel-marcacao-dist{font-size:20px;font-weight:800;font-family:var(--mono);color:var(--green)}
.painel-marcacao-info{font-size:10px;color:var(--muted);font-family:var(--mono);margin:6px 0}
.painel-marcacao-botoes{display:flex;gap:4px;flex-wrap:wrap}
.painel-marcacao-botoes a,.painel-marcacao-botoes button{flex:1;min-width:55px;padding:5px 8px;border-radius:6px;font-size:9px;font-weight:700;text-align:center;text-decoration:none;cursor:pointer;border:none;display:flex;align-items:center;justify-content:center;gap:3px}
.btn-pm-maps{background:#4285F4;color:#fff}
.btn-pm-waze{background:#33ccff;color:#000}
.btn-pm-sv{background:#F4B400;color:#000}
.btn-pm-salvar{background:rgba(16,185,129,.15);color:var(--green);border:1px solid rgba(16,185,129,.35)!important}

/* ═══════ CLIENTE ATUAL NA CAIXA ═══════ */
.cliente-atual-caixa{margin-top:10px;padding-top:10px;border-top:1px solid var(--border)}
.cliente-atual-caixa-titulo{font-size:9px;color:var(--muted);font-family:var(--mono);letter-spacing:1px;margin-bottom:6px;text-transform:uppercase}
.cliente-atual-card{display:flex;align-items:center;justify-content:space-between;padding:8px 10px;background:rgba(0,212,255,.06);border:1px solid rgba(0,212,255,.2);border-radius:7px}
.cliente-atual-nome{font-size:12px;font-weight:700;color:var(--cyan)}
.cliente-atual-info{font-size:9px;color:var(--muted);margin-top:2px}

/* ═══════ MAPA ═══════ */
.mapa-container{position:relative}
#olt-mini-map{width:100%;height:350px;border-radius:12px;border:1px solid var(--border);margin:0 0 14px 0;overflow:hidden;display:none;position:relative}
@media(min-width:768px){#olt-mini-map{height:400px}}
@media(min-width:1200px){#olt-mini-map{height:450px}}
.leaflet-container{background:#0a1220!important}
.leaflet-popup-content-wrapper{background:var(--card)!important;border:1px solid var(--border)!important;border-radius:8px!important;box-shadow:0 6px 18px rgba(0,0,0,.5)!important}
.leaflet-popup-content{font-family:var(--ui)!important;color:var(--text)!important;margin:5px 7px!important;font-size:10px!important;line-height:1.4!important}
.leaflet-popup-tip{background:var(--card)!important}
.leaflet-popup-close-button{color:var(--muted)!important;font-size:14px!important;top:2px!important;right:4px!important}
.leaflet-popup-close-button:hover{color:var(--text)!important}

@keyframes spin{to{transform:rotate(360deg)}}
#cep-loader{animation:spin .8s linear infinite}
</style>

<div class="topbar">
    <button class="btn-hamburger" onclick="abrirDrawer()" aria-label="Menu">&#9776;</button>
    <div>
        <div class="page-title"><?= $id ? '✎ Editar Cliente' : '+ Cadastrar Novo Cliente' ?></div>
        <div class="page-sub"><?= $id ? e($cliente['nome']) : 'Preencha os dados do novo cliente' ?></div>
    </div>
    <div class="topbar-actions">
        <a href="<?= $id ? "cliente_detalhe.php?id=$id" : 'clientes.php' ?>" class="btn btn-ghost">← Voltar</a>
    </div>
</div>

<div class="content">
<?php if ($erros): ?><div class="alert alert-danger"><?= implode('<br>', array_map('e',$erros)) ?></div><?php endif; ?>
<?php if ($sucesso): ?><div class="alert alert-success"><?= e($sucesso) ?></div><?php endif; ?>

<form method="post" id="form-cliente" action="" enctype="multipart/form-data">
<input type="hidden" name="csrf_token" value="<?= csrfToken() ?>"/>
<?php if (!$id): ?><input type="hidden" name="destino_pos_salvar" id="destino_pos_salvar" value="editar"/><?php endif; ?>

<input type="hidden" name="cto_nome" id="h-cto-nome" value="<?= e($v['cto_nome'] ?? '') ?>"/>
<input type="hidden" name="olt_gps" id="h-olt-gps" value="<?= e($v['olt_gps'] ?? '') ?>"/>
<input type="hidden" name="marcacao_kml_nome" id="h-kml-nome" value="<?= e($v['marcacao_kml_nome'] ?? '') ?>"/>
<input type="hidden" name="marcacao_kml_tipo" id="h-kml-tipo" value="<?= e($v['marcacao_kml_tipo'] ?? '') ?>"/>
<input type="hidden" name="marcacao_kml_lat"  id="h-kml-lat"  value="<?= e($v['marcacao_kml_lat'] ?? '') ?>"/>
<input type="hidden" name="marcacao_kml_lng"  id="h-kml-lng"  value="<?= e($v['marcacao_kml_lng'] ?? '') ?>"/>
<input type="hidden" name="marcacao_kml_dist" id="h-kml-dist" value="<?= e($v['marcacao_kml_dist'] ?? '') ?>"/>

<!-- ═══════ IDENTIFICAÇÃO ═══════ -->
<div class="form-card">
    <div class="form-section-title">◎ IDENTIFICAÇÃO</div>
    <div class="form-grid">
        <div class="form-group full"><label class="form-label">NOME COMPLETO *</label><input class="form-input" type="text" name="nome" id="nome" value="<?= e($v['nome']) ?>" required placeholder="Nome do cliente"/></div>
        <div class="form-group"><label class="form-label">CPF / CNPJ</label><input class="form-input" type="text" name="documento" value="<?= e($v['documento']) ?>" placeholder="000.000.000-00"/></div>
        <div class="form-group"><label class="form-label">TELEFONE PRINCIPAL</label><input class="form-input" type="text" name="telefone" id="telefone_principal" value="<?= e($v['telefone']) ?>" placeholder="(17) 99999-9999"/></div>
        
        <!-- ═══════ TELEFONES ADICIONAIS ═══════ -->
        <div class="form-group full">
            <label class="form-label">TELEFONES ADICIONAIS / CONTATOS</label>
            <div id="telefones-container" class="telefones-extra">
                <?php if (!empty($telefonesAdicionais)): ?>
                    <?php foreach ($telefonesAdicionais as $i => $tel): ?>
                    <div class="telefone-row">
                        <input class="form-input" type="text" name="telefones_extra[]" value="<?= e($tel['telefone']) ?>" placeholder="(17) 99999-9999" style="font-size:12px"/>
                        <select class="form-select" name="telefones_tipo[]" style="font-size:11px;padding:5px 8px">
                            <option value="Celular" <?= ($tel['tipo'] ?? '') === 'Celular' ? 'selected' : '' ?>>Celular</option>
                            <option value="WhatsApp" <?= ($tel['tipo'] ?? '') === 'WhatsApp' ? 'selected' : '' ?>>WhatsApp</option>
                            <option value="Residencial" <?= ($tel['tipo'] ?? '') === 'Residencial' ? 'selected' : '' ?>>Residencial</option>
                            <option value="Comercial" <?= ($tel['tipo'] ?? '') === 'Comercial' ? 'selected' : '' ?>>Comercial</option>
                            <option value="Recado" <?= ($tel['tipo'] ?? '') === 'Recado' ? 'selected' : '' ?>>Recado</option>
                            <option value="Outro" <?= ($tel['tipo'] ?? '') === 'Outro' ? 'selected' : '' ?>>Outro</option>
                        </select>
                        <button type="button" class="btn-rem-tel" onclick="removerTelefone(this)" title="Remover">✕</button>
                    </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
            <button type="button" class="btn-add-tel" onclick="adicionarTelefone()">+ Adicionar telefone</button>
        </div>
        
        <div class="form-group"><label class="form-label">E-MAIL</label><input class="form-input" type="email" name="email" value="<?= e($v['email']) ?>" placeholder="cliente@email.com"/></div>
        <div class="form-group"><label class="form-label">STATUS</label>
            <div style="display:flex;gap:16px;padding-top:8px">
                <label style="font-size:13px;cursor:pointer;display:flex;align-items:center;gap:6px"><input type="checkbox" name="ativo" value="1" <?= $v['ativo']?'checked':'' ?>/> Ativo</label>
                <label style="font-size:13px;cursor:pointer;display:flex;align-items:center;gap:6px"><input type="checkbox" name="bloqueado" value="1" <?= $v['bloqueado']?'checked':'' ?>/> Bloqueado</label>
            </div>
        </div>
    </div>
</div>

<!-- ═══════ ENDEREÇO + GEO ═══════ -->
<div class="form-card">
    <div class="form-section-title">
        <span>◉ ENDEREÇO E GEOLOCALIZAÇÃO</span>
        <button type="button" id="btn-gps" onclick="obterLocalizacaoGPS()" class="btn btn-gps"><span class="pulse"></span>📍 Obter Localização Atual</button>
    </div>
    <div class="form-grid" style="margin-bottom:12px">
        <div class="form-group full"><label class="form-label">LOGRADOURO</label><input class="form-input" type="text" name="endereco_logradouro" id="endereco_logradouro" value="<?= e($v['endereco_logradouro']) ?>" placeholder="Ex: Avenida Lucia" oninput="onEnderecoChange()"/></div>
        <div class="form-group"><label class="form-label">NÚMERO</label><input class="form-input" type="text" name="endereco_numero" id="endereco_numero" value="<?= e($v['endereco_numero']) ?>" placeholder="3361" oninput="atualizarBadgeEndereco()"/></div>
        <div class="form-group"><label class="form-label">COMPLEMENTO</label><input class="form-input" type="text" name="endereco_complemento" value="<?= e($v['endereco_complemento']) ?>" placeholder="Apto, Bloco..."/></div>
    </div>
    <div class="form-grid cols4">
        <div class="form-group"><label class="form-label">BAIRRO</label><input class="form-input" type="text" name="endereco_bairro" id="endereco_bairro" value="<?= e($v['endereco_bairro']) ?>" placeholder="Centro" oninput="onEnderecoChange()"/></div>
        <div class="form-group"><label class="form-label">CIDADE</label><select class="form-select" name="endereco_cidade" id="endereco_cidade" onchange="onCidadeChange(this); onEnderecoChange(); atualizarMapaDinamico();"><option value="">Selecione...</option><?php foreach ($cidades as $c): ?><option value="<?= e($c) ?>" <?= $v['endereco_cidade']===$c?'selected':'' ?>><?= e($c) ?></option><?php endforeach; ?></select></div>
        <div class="form-group"><label class="form-label">VLAN</label><input class="form-input" type="text" name="vlan" id="vlan" value="<?= e($v['vlan']) ?>" readonly placeholder="—"/></div>
        <div class="form-group"><label class="form-label">CEP</label><div style="position:relative"><input class="form-input" type="text" name="endereco_cep" id="endereco_cep" value="<?= e($v['endereco_cep']) ?>" placeholder="00000-000" oninput="onCepInput(this)" maxlength="9" style="padding-right:34px"/><span id="cep-loader" style="display:none;position:absolute;right:10px;top:50%;transform:translateY(-50%);font-size:13px;color:var(--cyan)">⟳</span></div></div>
    </div>
    <input type="hidden" name="latitude" id="latitude" value="<?= e($v['latitude'] ?? '') ?>"/>
    <input type="hidden" name="longitude" id="longitude" value="<?= e($v['longitude'] ?? '') ?>"/>

    <div style="display:flex;align-items:center;gap:10px;margin-top:10px;flex-wrap:wrap">
        <div id="geo-status" class="geo-status <?= $v['latitude']?'ok':'' ?>" style="<?= $v['latitude']?'':'display:none' ?>;flex:1"><?= $v['latitude'] ? "✓ Localizado: {$v['latitude']}, {$v['longitude']}" : '' ?></div>
    </div>

    <div class="cliente-badge-fixa" id="cliente-badge" style="display:<?= ($v['latitude'] && $v['longitude']) ? 'flex' : 'none' ?>">
        <div class="cliente-badge-info">
            <div class="cliente-badge-nome" id="cliente-nome-exib"><?= e($v['nome'] ?: 'Cliente') ?></div>
            <div class="cliente-badge-endereco" id="cliente-endereco-exib"><?php $end = trim(($v['endereco_logradouro']??'') . ', ' . ($v['endereco_numero']??'') . ' - ' . ($v['endereco_bairro']??'') . ', ' . ($v['endereco_cidade']??'')); echo e($end ?: 'Endereço não informado'); ?></div>
        </div>
        <div class="cliente-badge-links">
            <?php
              $bLat = $v['latitude'] ?? ''; $bLng = $v['longitude'] ?? '';
              $mapsHref = ($bLat && $bLng) ? "https://maps.google.com/?q={$bLat},{$bLng}" : '#';
              $wazeHref = ($bLat && $bLng) ? "https://waze.com/ul?ll={$bLat},{$bLng}&navigate=yes" : '#';
              $svHref   = ($bLat && $bLng) ? "https://www.google.com/maps/@?api=1&map_action=pano&viewpoint={$bLat},{$bLng}" : '#';
            ?>
            <a href="<?= $mapsHref ?>" target="_blank" class="caixa-link-maps" title="Google Maps">M</a>
            <a href="<?= $wazeHref ?>" target="_blank" class="caixa-link-waze" title="Waze">W</a>
            <a href="<?= $svHref ?>" target="_blank" class="caixa-link-sv" title="Street View">SV</a>
        </div>
    </div>
</div>

<!-- ═══════ PAINEL DA MARCAÇÃO SELECIONADA ═══════ -->
<div class="painel-marcacao" id="painel-marcacao">
    <div style="display:flex;align-items:flex-start;justify-content:space-between;gap:8px;margin-bottom:4px">
        <div class="painel-marcacao-nome" id="pm-nome">—</div>
        <div class="painel-marcacao-dist" id="pm-dist">—</div>
    </div>
    <div class="painel-marcacao-info" id="pm-info">—</div>
    <div class="painel-marcacao-botoes">
        <a id="pm-maps" href="#" target="_blank" class="btn-pm-maps">◉ Maps</a>
        <a id="pm-waze" href="#" target="_blank" class="btn-pm-waze">🔵 Waze</a>
        <a id="pm-sv" href="#" target="_blank" class="btn-pm-sv">📷 Street</a>
        <button type="button" onclick="salvarMarcacaoNoCliente()" class="btn-pm-salvar">💾 Salvar</button>
    </div>
    <!-- Cliente atual nesta caixa -->
    <div class="cliente-atual-caixa" id="cliente-atual-caixa" style="display:none">
        <div class="cliente-atual-caixa-titulo">📋 CLIENTE ATUAL NESTA CAIXA</div>
        <div id="cliente-atual-card"></div>
    </div>
</div>

<!-- ═══════ BARRA DE FILTROS KML ═══════ -->
<div class="kml-filtros-bar" id="kml-filtros-bar">
    <div class="kml-filtros-inner">
        <div class="kml-filtros-header">
            <span class="kml-filtros-titulo">📍 FILTROS DE REDE (clique para mostrar/ocultar)</span>
            <button type="button" class="btn btn-ghost btn-sm" onclick="centralizarCliente()" style="font-size:9px;padding:3px 8px">🎯 Centralizar</button>
        </div>
        <div class="kml-filtros-scroll" id="kml-filtros-scroll">
            <button type="button" class="kml-chip kml-chip-cx" data-tipo="cx" onclick="toggleVisibilidadeKML('cx',this)"><span class="kml-chip-dot"></span>CX</button>
            <button type="button" class="kml-chip kml-chip-cto" data-tipo="cto" onclick="toggleVisibilidadeKML('cto',this)"><span class="kml-chip-dot"></span>CTO</button>
            <button type="button" class="kml-chip kml-chip-cr" data-tipo="cr" onclick="toggleVisibilidadeKML('cr',this)"><span class="kml-chip-dot"></span>CR</button>
            <button type="button" class="kml-chip kml-chip-poste" data-tipo="poste" onclick="toggleVisibilidadeKML('poste',this)"><span class="kml-chip-dot"></span>Postes</button>
            <button type="button" class="kml-chip kml-chip-ceo" data-tipo="ceo" onclick="toggleVisibilidadeKML('ceo',this)"><span class="kml-chip-dot"></span>CEO</button>
            <button type="button" class="kml-chip kml-chip-fo" data-tipo="fo" onclick="toggleVisibilidadeKML('fo',this)"><span class="kml-chip-dot"></span>FO</button>
            <button type="button" class="kml-chip kml-chip-feeder" data-tipo="feeder" onclick="toggleVisibilidadeKML('feeder',this)"><span class="kml-chip-dot"></span>Feeder</button>
            <button type="button" class="kml-chip kml-chip-ramal" data-tipo="ramal" onclick="toggleVisibilidadeKML('ramal',this)"><span class="kml-chip-dot"></span>Ramal</button>
            <button type="button" class="kml-chip kml-chip-drop" data-tipo="drop" onclick="toggleVisibilidadeKML('drop',this)"><span class="kml-chip-dot"></span>Drop</button>
            <button type="button" class="kml-chip kml-chip-cabo" data-tipo="cabo" onclick="toggleVisibilidadeKML('cabo',this)"><span class="kml-chip-dot"></span>Cabo</button>
            <button type="button" class="kml-chip kml-chip-splitter" data-tipo="splitter" onclick="toggleVisibilidadeKML('splitter',this)"><span class="kml-chip-dot"></span>Splitter</button>
            <button type="button" class="kml-chip kml-chip-dio" data-tipo="dio" onclick="toggleVisibilidadeKML('dio',this)"><span class="kml-chip-dot"></span>DIO</button>
            <button type="button" class="kml-chip kml-chip-nap" data-tipo="nap" onclick="toggleVisibilidadeKML('nap',this)"><span class="kml-chip-dot"></span>NAP</button>
            <button type="button" class="kml-chip kml-chip-torre" data-tipo="torre" onclick="toggleVisibilidadeKML('torre',this)"><span class="kml-chip-dot"></span>Torres</button>
            <button type="button" class="kml-chip kml-chip-reserva" data-tipo="reserva" onclick="toggleVisibilidadeKML('reserva',this)"><span class="kml-chip-dot"></span>Reserva</button>
            <button type="button" class="kml-chip kml-chip-emenda" data-tipo="emenda" onclick="toggleVisibilidadeKML('emenda',this)"><span class="kml-chip-dot"></span>Emendas</button>
            <button type="button" class="kml-chip kml-chip-pop" data-tipo="pop" onclick="toggleVisibilidadeKML('pop',this)"><span class="kml-chip-dot"></span>POP</button>
            <button type="button" class="kml-chip kml-chip-ptp" data-tipo="ptp" onclick="toggleVisibilidadeKML('ptp',this)"><span class="kml-chip-dot"></span>PTP</button>
            <button type="button" class="kml-chip kml-chip-cep" data-tipo="cep" onclick="toggleVisibilidadeKML('cep',this)"><span class="kml-chip-dot"></span>CEP/CEL</button>
            <button type="button" class="kml-chip kml-chip-outro" data-tipo="outro" onclick="toggleVisibilidadeKML('outro',this)"><span class="kml-chip-dot"></span>Outros</button>
        </div>
    </div>
</div>

<!-- ═══════ MAPA ═══════ -->
<div class="mapa-container">
    <div id="olt-mini-map">
        <div class="mapa-loading" id="mapa-loading">
            <div class="mapa-loading-spinner"></div>
            <div class="mapa-loading-text">Carregando mapa e marcações KML...</div>
        </div>
    </div>
</div>

<!-- ═══════ FOTO DA FACHADA ═══════ -->
<div class="form-card">
    <div class="form-section-title">🏠 FOTO DA FACHADA DA RESIDÊNCIA</div>
    <p style="font-size:12px;color:var(--muted);margin-bottom:12px">Registre a frente da residência.</p>
    <?php if ($fotoFachada): ?>
    <div style="margin-bottom:14px;display:flex;align-items:center;gap:12px">
        <div class="foto-card"><img src="<?= e($fotoFachada['caminho_arquivo']) ?>" alt="Fachada"/><a href="ajax/deletar_foto.php?id=<?= $fotoFachada['id'] ?>&cliente_id=<?= $id ?>" class="foto-card-del" onclick="return confirm('Excluir foto da fachada?')">✕</a></div>
        <span style="font-size:12px;color:var(--green)">✓ Fachada registrada. Envie uma nova para substituir.</span>
    </div>
    <?php endif; ?>
    <div class="upload-zone" id="zone-fachada" ondragover="this.classList.add('over');event.preventDefault()" ondragleave="this.classList.remove('over')" ondrop="dropFoto(event,'preview-fachada','zone-fachada')">
        <input type="file" name="foto_fachada" accept="image/*" onchange="previewUm(this,'preview-fachada')"/>
        <div class="upload-zone-icon">🏠</div>
        <div class="upload-zone-label"><b>Clique ou arraste</b> a foto da fachada</div>
        <div class="upload-zone-hint">JPG · PNG · WEBP · Máx. 8 MB</div>
    </div>
    <div id="preview-fachada" class="fotos-grid"></div>
</div>

<!-- ═══════ CONEXÃO ═══════ -->
<div class="form-card">
    <div class="form-section-title">⬡ DADOS DE CONEXÃO</div>
    <div class="form-grid cols3">
        <div class="form-group"><label class="form-label">PLANO</label><select class="form-select" name="plano"><option value="">Selecione...</option><?php foreach ($planos as $p): ?><option value="<?= e($p) ?>" <?= $v['plano']===$p?'selected':'' ?>><?= e($p) ?></option><?php endforeach; ?></select></div>
        <div class="form-group"><label class="form-label">PPPoE USUÁRIO</label><input class="form-input" type="text" name="pppoe_usuario" value="<?= e($v['pppoe_usuario']) ?>" placeholder="usuario@mkt"/></div>
        <div class="form-group"><label class="form-label">PPPoE SENHA</label><input class="form-input" type="text" name="pppoe_senha" value="<?= e($v['pppoe_senha']) ?>" placeholder="senha"/></div>
        <div class="form-group"><label class="form-label">CÓD. CONEXÃO</label><input class="form-input" type="text" name="cod_conexao" value="<?= e($v['cod_conexao']) ?>" placeholder="CONEXAO001"/></div>
        <div class="form-group"><label class="form-label">MAC KEY</label><input class="form-input" type="text" name="mac_key" value="<?= e($v['mac_key']) ?>" placeholder="MAC address"/></div>
    </div>
    <div style="margin-top:16px;padding-top:16px;border-top:1px solid var(--border)">
        <div style="font-size:10px;font-family:var(--mono);color:var(--muted);letter-spacing:1.5px;margin-bottom:12px">WI-FI</div>
        <div class="form-grid cols4">
            <div class="form-group"><label class="form-label">SSID 2.4GHz</label><input class="form-input" type="text" name="wifi_ssid_2g" value="<?= e($v['wifi_ssid_2g']) ?>" placeholder="MKT-Nome-2G"/></div>
            <div class="form-group"><label class="form-label">SENHA 2.4GHz</label><input class="form-input" type="text" name="wifi_senha_2g" value="<?= e($v['wifi_senha_2g']) ?>" placeholder="wifi2024"/></div>
            <div class="form-group"><label class="form-label">SSID 5GHz</label><input class="form-input" type="text" name="wifi_ssid_5g" value="<?= e($v['wifi_ssid_5g']) ?>" placeholder="MKT-Nome-5G"/></div>
            <div class="form-group"><label class="form-label">SENHA 5GHz</label><input class="form-input" type="text" name="wifi_senha_5g" value="<?= e($v['wifi_senha_5g']) ?>" placeholder="wifi2024"/></div>
        </div>
    </div>
</div>

<!-- ═══════ EQUIPAMENTOS ═══════ -->
<div class="form-card">
    <div class="form-section-title">▣ EQUIPAMENTOS</div>
    <div class="form-grid">
        <div class="form-group"><label class="form-label">ROTEADOR / ONT</label><select class="form-select" name="modelo_roteador" onchange="onRoteadorChange(this)"><option value="">Sem roteador</option><?php foreach ($roteadores as $r): ?><option value="<?= e($r) ?>" <?= $v['modelo_roteador']===$r?'selected':'' ?>><?= e($r) ?></option><?php endforeach; ?></select></div>
        <div class="form-group"><label class="form-label">SENHA EQUIPAMENTO</label><input class="form-input" type="text" name="password_equipamento" id="password_equipamento" value="<?= e($v['password_equipamento']) ?>" readonly/><span class="form-hint">Zyxel=Mbc80480# | Outros=mbc80480#</span></div>
        <div class="form-group">
          <label class="form-label">REPETIDOR / MESH</label>
          <div style="display:flex;gap:6px">
            <select class="form-select" name="modelo_repetidor" id="modelo_repetidor" style="flex:1" onchange="onRepetidorChange(this)">
              <option value="">Sem repetidor</option>
              <?php foreach ($repetidores as $r): ?>
              <option value="<?= e($r) ?>" <?= $v['modelo_repetidor']===$r?'selected':'' ?>><?= e($r) ?></option>
              <?php endforeach; ?>
            </select>
            <input class="form-input" type="number" name="qtd_repetidor" id="qtd_repetidor_input" value="<?= (int)($v['qtd_repetidor'] ?? 1) ?>" min="0" max="10" style="width:60px;text-align:center;font-family:var(--mono);font-weight:700;flex-shrink:0"/>
          </div>
          <span class="form-hint" id="repetidor-hint">Modelo + quantidade de unidades</span>
        </div>
        <div class="form-group full">
            <div style="background:var(--card2);border:1px solid var(--border);border-radius:10px;padding:16px">
                <label style="display:flex;align-items:center;gap:10px;cursor:pointer;user-select:none"><input type="checkbox" id="chk-cameras" name="possui_cameras" value="1" <?= $v['possui_cameras']?'checked':'' ?> onchange="document.getElementById('cameras-section').classList.toggle('show',this.checked)" style="width:18px;height:18px;accent-color:var(--cyan);cursor:pointer;flex-shrink:0"/><span style="font-size:14px;font-weight:700">📹 Possui câmeras de segurança</span></label>
                <div id="cameras-section" class="cameras-section <?= $v['possui_cameras']?'show':'' ?>">
                    <hr style="border-color:var(--border);margin:14px 0"/>
                    <div class="form-group" style="margin-bottom:14px"><label class="form-label">LOCAL DAS CÂMERAS</label><textarea class="form-textarea" name="camera_local" rows="2" placeholder="Ex: 2 câmeras na fachada frontal, 1 no quintal..."><?= e($v['camera_local']) ?></textarea></div>
                    <?php if ($fotosCamera): ?>
                    <div style="margin-bottom:14px"><div class="form-label" style="margin-bottom:8px">FOTOS REGISTRADAS</div><div class="fotos-grid"><?php foreach ($fotosCamera as $fc): ?><div class="foto-card"><img src="<?= e($fc['caminho_arquivo']) ?>" alt="Câmera"/><a href="ajax/deletar_foto.php?id=<?= $fc['id'] ?>&cliente_id=<?= $id ?>" class="foto-card-del" onclick="return confirm('Excluir esta foto?')">✕</a></div><?php endforeach; ?></div></div>
                    <?php endif; ?>
                    <div class="form-group"><label class="form-label">FOTOS DA INSTALAÇÃO DAS CÂMERAS</label><div class="upload-zone" id="zone-cameras" ondragover="this.classList.add('over');event.preventDefault()" ondragleave="this.classList.remove('over')" ondrop="dropFotos(event,'preview-cameras')"><input type="file" name="fotos_cameras[]" accept="image/*" multiple onchange="previewVarios(this,'preview-cameras')"/><div class="upload-zone-icon">📸</div><div class="upload-zone-label"><b>Clique ou arraste</b> as fotos da instalação</div><div class="upload-zone-hint">Múltiplas fotos · JPG · PNG · Máx. 8 MB cada</div></div><div id="preview-cameras" class="fotos-grid"></div></div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- ═══════ OBSERVAÇÕES ═══════ -->
<div class="form-card">
    <div class="form-section-title">✎ OBSERVAÇÕES INTERNAS</div>
    <div class="form-group"><textarea class="form-textarea" name="observacoes" rows="3" placeholder="Anotações internas, informações adicionais..."><?= e($v['observacoes']) ?></textarea></div>
</div>

<div style="display:flex;gap:12px;justify-content:flex-end;flex-wrap:wrap;padding-bottom:32px">
    <a href="<?= $id ? "cliente_detalhe.php?id=$id" : 'clientes.php' ?>" class="btn btn-ghost">Cancelar</a>
    <?php if (!$id): ?>
        <button type="button" onclick="submeterPara('os')" class="btn btn-ghost">💾 Salvar e Abrir OS</button>
        <button type="submit" class="btn btn-primary">✓ Cadastrar Cliente</button>
    <?php else: ?>
        <button type="submit" class="btn btn-primary">✓ Atualizar Cliente</button>
    <?php endif; ?>
</div>
</form>
</div>

<script>
let _map=null,_mCli=null,_routeLine=null;
let _kmlPoints=[],_kmlLines=[],_kmlLayers=[],_kmlLineLayers=[];
let _visibilidadeKML={cx:false,cto:false,poste:false,ceo:false,fo:false,torre:false,reserva:false,emenda:false,pop:false,ptp:false,cr:false,outro:false,feeder:false,ramal:false,drop:false,cabo:false,splitter:false,dio:false,nap:false,cep:false};
let _marcacaoSelecionada=null;

const KML_CORES={cx:'#00d4ff',cto:'#0ea5e9',poste:'#94a3b8',ceo:'#ec4899',fo:'#a855f7',torre:'#ef4444',reserva:'#fb923c',emenda:'#f59e0b',pop:'#eab308',ptp:'#22c55e',cr:'#8b5cf6',outro:'#94a3b8',feeder:'#ff4444',ramal:'#ffaa7f',drop:'#ff7700',cabo:'#ff2222',splitter:'#6366f1',dio:'#14b8a6',nap:'#f472b6',cep:'#84cc16'};
const KML_LABELS={cx:'Caixa (CX)',cto:'Caixa (CTO)',poste:'Poste',ceo:'Emenda Óptica (CEO)',fo:'Fibra Óptica',torre:'Torre',reserva:'Reserva Técnica',emenda:'Emenda/Fusão',pop:'POP / Nó',ptp:'PTP (Rádio)',cr:'CR',outro:'Outro',feeder:'Feeder',ramal:'Ramal',drop:'Drop',cabo:'Cabo FO',splitter:'Splitter',dio:'DIO',nap:'NAP',cep:'CEP/CEL'};

function haversineM(lat1,lng1,lat2,lng2){const R=6371000,d2r=Math.PI/180;const dLat=(lat2-lat1)*d2r,dLng=(lng2-lng1)*d2r;const a=Math.sin(dLat/2)**2+Math.cos(lat1*d2r)*Math.cos(lat2*d2r)*Math.sin(dLng/2)**2;return R*2*Math.atan2(Math.sqrt(a),Math.sqrt(1-a));}
function fmtDist(m){return m>=1000?(m/1000).toFixed(2)+' km':Math.round(m)+' m';}

// ═══════════════════ TELEFONES ADICIONAIS ═══════════════════
function adicionarTelefone(){
    const container=document.getElementById('telefones-container');
    const row=document.createElement('div');
    row.className='telefone-row';
    row.innerHTML=`
        <input class="form-input" type="text" name="telefones_extra[]" value="" placeholder="(17) 99999-9999" style="font-size:12px"/>
        <select class="form-select" name="telefones_tipo[]" style="font-size:11px;padding:5px 8px">
            <option value="Celular">Celular</option>
            <option value="WhatsApp">WhatsApp</option>
            <option value="Residencial">Residencial</option>
            <option value="Comercial">Comercial</option>
            <option value="Recado">Recado</option>
            <option value="Outro">Outro</option>
        </select>
        <button type="button" class="btn-rem-tel" onclick="removerTelefone(this)" title="Remover">✕</button>
    `;
    container.appendChild(row);
}

function removerTelefone(btn){
    const row=btn.closest('.telefone-row');
    if(row)row.remove();
}

// ═══════════════════ ATUALIZAR MAPA DINÂMICO ═══════════════════
function atualizarMapaDinamico(){
    const lat=parseFloat(document.getElementById('latitude').value);
    const lng=parseFloat(document.getElementById('longitude').value);
    if(!lat||!lng||!_map)return;
    
    // Atualiza posição do cliente no mapa
    const iconCasa=L.divIcon({className:'',html:`<div style="position:relative;width:28px;height:28px"><div style="position:absolute;inset:0;border-radius:50%;background:rgba(0,212,255,.25);animation:pulse-map 2s infinite"></div><div style="position:absolute;inset:4px;border-radius:50%;background:#00d4ff;border:2px solid #fff;box-shadow:0 0 10px #00d4ff;display:flex;align-items:center;justify-content:center;font-size:9px">🏠</div></div>`,iconSize:[28,28],iconAnchor:[14,14]});
    if(_mCli)_map.removeLayer(_mCli);
    _mCli=L.marker([lat,lng],{icon:iconCasa}).addTo(_map);
    _mCli.bindPopup(`<b>${document.getElementById('cliente-nome-exib')?.textContent||'Cliente'}</b>`);
    _map.setView([lat,lng],17);
    
    // Atualiza distâncias das marcações
    plotarMarcacoesKML();
}

async function geocodeReverso(lat,lng){try{const r=await fetch(`ajax/geocodificar.php?acao=reverse&lat=${lat}&lng=${lng}`);const d=await r.json();if(d.ok)return d;}catch(e){}return null;}

function classificarKML(nome){const n=nome.toUpperCase();
    if(/^CTO|_CTO|\bCTO\b/.test(n))return'cto';
    if(/^CX|^CXB|^C\d|^CP\d|^STR/.test(n))return'cx';
    if(/CEO/.test(n))return'ceo';
    if(/POSTE/.test(n))return'poste';
    if(/\bFEEDER\b/.test(n))return'feeder';
    if(/\bRAMAL\b|\bRAMA\b/.test(n))return'ramal';
    if(/\bDROP\b/.test(n))return'drop';
    if(/\bFO\b|FO[\s\-]?\d|FIBRA|ENTERRADO|AEREO/.test(n))return'fo';
    if(/^CB\b|^CABO\b/.test(n))return'cabo';
    if(/SPLITTER|SPLITER|DIVISOR/.test(n))return'splitter';
    if(/\bDIO\b/.test(n))return'dio';
    if(/\bNAP\b/.test(n))return'nap';
    if(/TORRE/.test(n))return'torre';
    if(/RESERVA|RESEVA|SOBRA/.test(n))return'reserva';
    if(/EMENDA|EMEDA|FUS[AÃ]O/.test(n))return'emenda';
    if(/\bPOP\b|DTC|OLT/.test(n))return'pop';
    if(/\bPTP\b/.test(n))return'ptp';
    if(/^CR[\s\-]?\d|\bCR\b/.test(n))return'cr';
    if(/^CEP|^CEL/.test(n))return'cep';
    return'outro';}

async function carregarKML(){if(_kmlPoints.length>0||_kmlLines.length>0)return;try{const r=await fetch('projeto_rede.kml?v='+Date.now());if(!r.ok)throw new Error('KML HTTP '+r.status);const txt=await r.text();if(!txt||txt.trim().startsWith('<!DOCTYPE')||txt.trim().startsWith('<html'))return;const xml=new DOMParser().parseFromString(txt,'text/xml');if(xml.querySelector('parsererror'))return;_kmlPoints=[];_kmlLines=[];xml.querySelectorAll('Placemark').forEach(p=>{const nomeEl=p.querySelector('name');const nome=nomeEl?nomeEl.textContent.trim():'';if(!nome)return;const kmlTipo=classificarKML(nome);const lineEl=p.querySelector('LineString');if(lineEl){const coordEl=lineEl.querySelector('coordinates');if(!coordEl)return;const latlngs=coordEl.textContent.trim().split(/\s+/).map(tok=>{const pts=tok.split(',');return[parseFloat(pts[1]),parseFloat(pts[0])];}).filter(ll=>!isNaN(ll[0])&&!isNaN(ll[1]));if(latlngs.length<2)return;_kmlLines.push({nome,kmlTipo,latlngs,cor:KML_CORES[kmlTipo]||KML_CORES.outro});return;}const ptEl=p.querySelector('Point');if(!ptEl)return;const coordEl=ptEl.querySelector('coordinates');if(!coordEl)return;const raw=coordEl.textContent.trim().split(',');if(raw.length<2)return;const lng=parseFloat(raw[0]),lat=parseFloat(raw[1]);if(isNaN(lat)||isNaN(lng))return;_kmlPoints.push({nome,lat,lng,kmlTipo});});console.log('✅ KML:',_kmlPoints.length,'pontos +',_kmlLines.length,'linhas');}catch(e){console.error('❌ Erro KML:',e.message);}}

function criarIconeKML(kmlTipo,selecionado=false){const cor=KML_CORES[kmlTipo]||KML_CORES.outro;const s=selecionado?14:8;const b=selecionado?2.5:1.5;const shadow=selecionado?'0 0 8px '+cor:'0 0 2px '+cor;let html='';switch(kmlTipo){case'cx':html=`<div style="width:${s}px;height:${s}px;border:${b}px solid ${cor};background:transparent;box-shadow:${shadow};display:flex;align-items:center;justify-content:center;font-size:4px;font-weight:900;color:${cor}">CX</div>`;break;case'cto':html=`<div style="width:${s}px;height:${s}px;border-radius:50%;border:${b}px solid ${cor};background:transparent;box-shadow:${shadow},inset 0 0 0 1.5px ${cor};display:flex;align-items:center;justify-content:center;font-size:3px;font-weight:900;color:${cor}">CTO</div>`;break;case'cr':html=`<div style="width:${s}px;height:${s}px;background:${cor};clip-path:polygon(50% 0%,100% 50%,50% 100%,0% 50%);box-shadow:${shadow}"></div>`;break;case'poste':html=`<div style="position:relative;width:${s}px;height:${s}px"><div style="position:absolute;left:50%;top:0;transform:translateX(-50%);width:1.5px;height:100%;background:${cor};box-shadow:${shadow}"></div><div style="position:absolute;top:1px;left:0;width:100%;height:1.5px;background:${cor}"></div></div>`;break;case'torre':html=`<div style="width:0;height:0;border-left:${s/2}px solid transparent;border-right:${s/2}px solid transparent;border-bottom:${s}px solid ${cor};filter:drop-shadow(0 0 2px ${cor})"></div>`;break;case'dio':case'nap':html=`<div style="width:${s}px;height:${s}px;border-radius:2px;background:${cor};box-shadow:${shadow};display:flex;align-items:center;justify-content:center;font-size:4px;font-weight:900;color:#000">${kmlTipo.toUpperCase()}</div>`;break;default:html=`<div style="width:${s}px;height:${s}px;border-radius:50%;background:${cor};box-shadow:${shadow}"></div>`;}return L.divIcon({className:'',html,iconSize:[s,s],iconAnchor:[s/2,s/2]});}

function plotarMarcacoesKML(){_kmlLayers.forEach(l=>{try{_map.removeLayer(l)}catch(e){}});_kmlLineLayers.forEach(l=>{try{_map.removeLayer(l)}catch(e){}});_kmlLayers=[];_kmlLineLayers=[];const lat=parseFloat(document.getElementById('latitude').value);const lng=parseFloat(document.getElementById('longitude').value);_kmlLines.forEach(line=>{if(!_visibilidadeKML[line.kmlTipo])return;const dashTypes=['fo','feeder','cabo','ramal','drop'];const poly=L.polyline(line.latlngs,{color:line.cor,weight:2,opacity:.7,dashArray:dashTypes.includes(line.kmlTipo)?'6,3':null});poly.bindPopup(`<b style="color:${line.cor};font-size:10px">📡 ${line.nome}</b><br><span style="font-size:9px;color:var(--muted)">${KML_LABELS[line.kmlTipo]||'Linha'}</span>`);poly.addTo(_map);poly.on('click',()=>{const mid=Math.floor(line.latlngs.length/2);selecionarMarcacaoKML(line.nome,line.kmlTipo,line.latlngs[mid][0],line.latlngs[mid][1],0);});_kmlLineLayers.push(poly);});_kmlPoints.forEach(mk=>{if(!_visibilidadeKML[mk.kmlTipo])return;const dist=lat&&lng?haversineM(lat,lng,mk.lat,mk.lng):Infinity;const icon=criarIconeKML(mk.kmlTipo,false);const marker=L.marker([mk.lat,mk.lng],{icon}).addTo(_map);const popupHtml=`<div style="min-width:110px;text-align:center"><b style="color:${KML_CORES[mk.kmlTipo]};font-size:10px">📍 ${mk.nome}</b><br><span style="font-size:8px;color:var(--muted)">${KML_LABELS[mk.kmlTipo]||'Ponto'}</span>${lat&&lng?`<br><span style="font-size:8px;color:var(--green);font-family:monospace;font-weight:700">📏 ${fmtDist(dist)}</span>`:''}</div>`;marker.bindPopup(popupHtml,{maxWidth:160});marker.on('click',()=>{selecionarMarcacaoKML(mk.nome,mk.kmlTipo,mk.lat,mk.lng,dist);setTimeout(()=>marker.openPopup(),100);});marker._kmlData=mk;_kmlLayers.push(marker);});if(_marcacaoSelecionada){_kmlLayers.forEach(m=>{const d=m._kmlData;if(d&&d.lat===_marcacaoSelecionada.lat&&d.lng===_marcacaoSelecionada.lng){m.setIcon(criarIconeKML(_marcacaoSelecionada.kmlTipo,true));}});}}

function toggleVisibilidadeKML(tipo,btn){_visibilidadeKML[tipo]=!_visibilidadeKML[tipo];if(_visibilidadeKML[tipo]){btn.classList.add('on');}else{btn.classList.remove('on');}plotarMarcacoesKML();}

function selecionarMarcacaoKML(nome,kmlTipo,lat,lng,dist){
    _marcacaoSelecionada={nome,kmlTipo,lat,lng,dist};
    const painel=document.getElementById('painel-marcacao');painel.style.display='block';
    document.getElementById('pm-nome').textContent=nome;
    document.getElementById('pm-nome').style.color=KML_CORES[kmlTipo]||KML_CORES.outro;
    document.getElementById('pm-dist').textContent=fmtDist(dist);
    document.getElementById('pm-info').innerHTML=`📍 ${KML_LABELS[kmlTipo]||'Ponto'} &nbsp;|&nbsp; 📐 ${lat.toFixed(5)}, ${lng.toFixed(5)}`;
    document.getElementById('pm-maps').href=`https://maps.google.com/?q=${lat},${lng}`;
    document.getElementById('pm-waze').href=`https://waze.com/ul?ll=${lat},${lng}&navigate=yes`;
    document.getElementById('pm-sv').href=`https://www.google.com/maps/@?api=1&map_action=pano&viewpoint=${lat},${lng}`;
    
    const cliLat=parseFloat(document.getElementById('latitude').value);
    const cliLng=parseFloat(document.getElementById('longitude').value);
    if(cliLat&&cliLng){_map.fitBounds([[cliLat,cliLng],[lat,lng]],{padding:[50,50]});}else{_map.setView([lat,lng],17);}
    
    _kmlLayers.forEach(m=>{const d=m._kmlData;if(d&&d.lat===lat&&d.lng===lng){m.setIcon(criarIconeKML(kmlTipo,true));}else{m.setIcon(criarIconeKML(m._kmlData.kmlTipo,false));}});
    if(cliLat&&cliLng)traçarRota(cliLat,cliLng,lat,lng);
    
    mostrarClienteAtualNaCaixa(nome);
}

function mostrarClienteAtualNaCaixa(nomeCaixa){
    const container=document.getElementById('cliente-atual-caixa');
    const card=document.getElementById('cliente-atual-card');
    const nomeSalvo=document.getElementById('h-kml-nome').value;
    const clienteNome=document.getElementById('nome')?.value||'Cliente';
    const clientePlano=document.querySelector('select[name="plano"]')?.value||'—';
    const clienteCidade=document.getElementById('endereco_cidade')?.value||'—';
    
    if(nomeSalvo===nomeCaixa){
        container.style.display='block';
        card.innerHTML=`
            <div style="flex:1">
                <div class="cliente-atual-nome">👤 ${clienteNome}</div>
                <div class="cliente-atual-info">📶 ${clientePlano} &nbsp;|&nbsp; 🏙 ${clienteCidade}</div>
                <div class="cliente-atual-info" style="color:var(--green);margin-top:2px">✓ Salvo nesta caixa</div>
            </div>
            <span style="font-size:9px;color:var(--green);font-weight:700">ATIVO</span>
        `;
    }else{
        container.style.display='none';
    }
}

function salvarMarcacaoNoCliente(){
    if(!_marcacaoSelecionada){mostrarToast('Selecione uma marcação primeiro.','warning');return;}
    const m=_marcacaoSelecionada;
    document.getElementById('h-cto-nome').value=m.nome;
    document.getElementById('h-olt-gps').value=m.lat+','+m.lng;
    document.getElementById('h-kml-nome').value=m.nome;
    document.getElementById('h-kml-tipo').value=m.kmlTipo;
    document.getElementById('h-kml-lat').value=m.lat;
    document.getElementById('h-kml-lng').value=m.lng;
    document.getElementById('h-kml-dist').value=m.dist;
    
    mostrarClienteAtualNaCaixa(m.nome);
    mostrarToast('✓ Marcação salva: '+m.nome,'success');
}

function initMapa(lat,lng){
    const el=document.getElementById('olt-mini-map');el.style.display='block';
    if(!_map){_map=L.map('olt-mini-map',{center:[lat,lng],zoom:17,zoomControl:false,attributionControl:false});L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png',{maxZoom:21}).addTo(_map);L.control.zoom({position:'bottomright'}).addTo(_map);}
    const iconCasa=L.divIcon({className:'',html:`<div style="position:relative;width:28px;height:28px"><div style="position:absolute;inset:0;border-radius:50%;background:rgba(0,212,255,.25);animation:pulse-map 2s infinite"></div><div style="position:absolute;inset:4px;border-radius:50%;background:#00d4ff;border:2px solid #fff;box-shadow:0 0 10px #00d4ff;display:flex;align-items:center;justify-content:center;font-size:9px">🏠</div></div>`,iconSize:[28,28],iconAnchor:[14,14]});
    if(_mCli)_map.removeLayer(_mCli);_mCli=L.marker([lat,lng],{icon:iconCasa}).addTo(_map);_mCli.bindPopup(`<b>${document.getElementById('cliente-nome-exib')?.textContent||'Cliente'}</b>`);_map.setView([lat,lng],17);setTimeout(()=>_map.invalidateSize(),200);
    const loading=document.getElementById('mapa-loading');if(loading)loading.style.display='none';
    carregarKML().then(()=>{plotarMarcacoesKML();const nomeSalvo=document.getElementById('h-kml-nome').value;if(nomeSalvo){const mk=_kmlPoints.find(m=>m.nome===nomeSalvo);if(mk){const d=haversineM(lat,lng,mk.lat,mk.lng);selecionarMarcacaoKML(mk.nome,mk.kmlTipo,mk.lat,mk.lng,d);}}});
}

async function traçarRota(latA,lngA,latB,lngB){if(_routeLine){_map.removeLayer(_routeLine);_routeLine=null;}try{const url=`https://router.project-osrm.org/route/v1/driving/${lngA},${latA};${lngB},${latB}?overview=full&geometries=geojson`;const r=await fetch(url,{signal:AbortSignal.timeout(8000)});if(!r.ok)throw new Error('OSRM error');const d=await r.json();if(!d.routes||!d.routes.length)throw new Error('Sem rota');_routeLine=L.polyline(d.routes[0].geometry.coordinates.map(([ln,lt])=>[lt,ln]),{color:'#10b981',weight:4,opacity:.85}).addTo(_map);}catch(e){_routeLine=L.polyline([[latA,lngA],[latB,lngB]],{color:'#10b981',weight:3,opacity:.5,dashArray:'6,3'}).addTo(_map);}}
function centralizarCliente(){const lat=parseFloat(document.getElementById('latitude').value);const lng=parseFloat(document.getElementById('longitude').value);if(!lat||!lng){return;}if(!_map)return;_map.setView([lat,lng],17);}

let _gpsObtendo=false;
function setGeoStatus(tipo,msg){const gs=document.getElementById('geo-status');gs.style.display='flex';gs.className='geo-status '+tipo;gs.textContent=msg;}
async function obterLocalizacaoGPS(){if(_gpsObtendo)return;if(!navigator.geolocation){setGeoStatus('err','⚠ GPS não disponível');return;}_gpsObtendo=true;const btn=document.getElementById('btn-gps');btn.disabled=true;btn.innerHTML='<span class="pulse"></span>⟳ Obtendo...';setGeoStatus('loading','⟳ Capturando GPS...');navigator.geolocation.getCurrentPosition(async(pos)=>{const lat=pos.coords.latitude,lng=pos.coords.longitude;document.getElementById('latitude').value=lat.toFixed(7);document.getElementById('longitude').value=lng.toFixed(7);setGeoStatus('ok',`✓ GPS: ${lat.toFixed(5)}, ${lng.toFixed(5)}`);const end=await geocodeReverso(lat,lng);if(end&&end.ok){if(end.logradouro)document.getElementById('endereco_logradouro').value=end.logradouro;if(end.numero)document.getElementById('endereco_numero').value=end.numero;if(end.bairro)document.getElementById('endereco_bairro').value=end.bairro;if(end.cep){const c=end.cep.replace(/\D/g,'');document.getElementById('endereco_cep').value=c.length===8?c.replace(/(\d{5})(\d{3})/,'$1-$2'):end.cep;}if(end.cidade){const sel=document.getElementById('endereco_cidade');for(let i=0;i<sel.options.length;i++){if(sel.options[i].value.toLowerCase()===end.cidade.toLowerCase()){sel.selectedIndex=i;onCidadeChange(sel);break;}}}document.getElementById('cliente-badge').style.display='flex';atualizarBadgeEndereco();}initMapa(lat,lng);document.getElementById('kml-filtros-bar').style.display='block';btn.innerHTML='<span class="pulse"></span>📍 Obter Localização Atual';btn.disabled=false;_gpsObtendo=false;},(err)=>{setGeoStatus('err','⚠ GPS falhou');btn.innerHTML='<span class="pulse"></span>📍 Obter Localização Atual';btn.disabled=false;_gpsObtendo=false;},{enableHighAccuracy:true,timeout:15000,maximumAge:0});}

function onCidadeChange(sel){const v={'Jales':'1001','Paranapuã':'1002','Mesópolis':'1004','Santa Albertina':'1005','Populina':'1003','Dirce Reis':'1001'};document.getElementById('vlan').value=v[sel.value]||'';}
let _cepBuscaTimeout;
function onEnderecoChange(){atualizarBadgeEndereco();clearTimeout(_cepBuscaTimeout);_cepBuscaTimeout=setTimeout(buscarCepPorEndereco,800);}
function buscarCepPorEndereco(){const rua=document.getElementById('endereco_logradouro').value.trim(),cidade=document.getElementById('endereco_cidade').value,cepInput=document.getElementById('endereco_cep');if(!rua||!cidade||cepInput.value.replace(/\D/g,'').length===8)return;const l=document.getElementById('cep-loader');if(l)l.style.display='block';fetch(`ajax/geocodificar.php?acao=cep_por_rua&cidade=${encodeURIComponent(cidade)}&rua=${encodeURIComponent(rua)}&uf=SP`).then(r=>r.json()).then(d=>{if(d.ok&&d.cep){document.getElementById('endereco_cep').value=d.cep;if(d.bairro&&!document.getElementById('endereco_bairro').value)document.getElementById('endereco_bairro').value=d.bairro;atualizarBadgeEndereco();}}).finally(()=>{if(l)l.style.display='none'});}
function atualizarBadgeEndereco(){const log=document.getElementById('endereco_logradouro').value.trim(),num=document.getElementById('endereco_numero').value.trim(),bai=document.getElementById('endereco_bairro').value.trim(),cid=document.getElementById('endereco_cidade').value;let end=log;if(num)end+=(end?', ':'')+num;if(bai)end+=(end?' - ':'')+bai;if(cid)end+=(end?', ':'')+cid;document.getElementById('cliente-endereco-exib').textContent=end||'Endereço não informado';document.getElementById('cliente-badge').style.display='flex';const lat=document.getElementById('latitude').value,lng=document.getElementById('longitude').value;if(lat&&lng){const m=document.getElementById('link-maps-cliente'),w=document.getElementById('link-waze-cliente'),s=document.getElementById('link-sv-cliente');if(m)m.href=`https://maps.google.com/?q=${lat},${lng}`;if(w)w.href=`https://waze.com/ul?ll=${lat},${lng}&navigate=yes`;if(s)s.href=`https://www.google.com/maps/@?api=1&map_action=pano&viewpoint=${lat},${lng}`;}}
function onCepInput(input){let v=input.value.replace(/\D/g,'').substring(0,8);if(v.length>5)v=v.substring(0,5)+'-'+v.substring(5);input.value=v;atualizarBadgeEndereco();if(v.replace(/\D/g,'').length===8){const l=document.getElementById('cep-loader');if(l)l.style.display='block';fetch(`ajax/geocodificar.php?acao=cep&cep=${v.replace(/\D/g,'')}`).then(r=>r.json()).then(d=>{if(d.ok){if(d.logradouro)document.getElementById('endereco_logradouro').value=d.logradouro;if(d.bairro)document.getElementById('endereco_bairro').value=d.bairro;if(d.cidade){const s=document.getElementById('endereco_cidade');for(let i=0;i<s.options.length;i++)if(s.options[i].value.toLowerCase()===d.cidade.toLowerCase()){s.selectedIndex=i;onCidadeChange(s);break;}}atualizarBadgeEndereco();}}).finally(()=>{if(l)l.style.display='none'});}}
function onRoteadorChange(sel){document.getElementById('password_equipamento').value=sel.value==='Zyxel'?'Mbc80480#':(sel.value?'mbc80480#':'');}
function onRepetidorChange(sel){const q=document.getElementById('qtd_repetidor_input'),h=document.getElementById('repetidor-hint');if(sel.value===''){q.style.display='none';q.value='0';h.textContent='Nenhum repetidor selecionado';}else{q.style.display='';if(q.value==='0')q.value='1';h.textContent='Modelo + quantidade de unidades';}}
function lerArquivos(files,cid){const c=document.getElementById(cid);Array.from(files).forEach(f=>{if(!f.type.startsWith('image/'))return;const r=new FileReader();r.onload=e=>{const d=document.createElement('div');d.className='foto-card';d.innerHTML=`<img src="${e.target.result}" alt="Preview"/>`;c.appendChild(d)};r.readAsDataURL(f);});}
function previewUm(i,cid){document.getElementById(cid).innerHTML='';if(i.files)lerArquivos(i.files,cid)}
function previewVarios(i,cid){if(i.files)lerArquivos(i.files,cid)}
function dropFoto(e,cid,zid){e.preventDefault();document.getElementById(zid).classList.remove('over');document.getElementById(cid).innerHTML='';if(e.dataTransfer.files)lerArquivos(e.dataTransfer.files,cid)}
function dropFotos(e,cid){e.preventDefault();document.getElementById('zone-cameras').classList.remove('over');if(e.dataTransfer.files)lerArquivos(e.dataTransfer.files,cid)}
function submeterPara(d){const f=document.getElementById('destino_pos_salvar');if(f)f.value=d;document.getElementById('form-cliente').submit();}

// Toast
function mostrarToast(mensagem,tipo='success'){const cores={success:'var(--green)',error:'var(--red)',info:'var(--cyan)',warning:'var(--amber, #f59e0b)'};const toast=document.createElement('div');toast.textContent=mensagem;toast.style.cssText=`position:fixed;bottom:24px;left:50%;transform:translateX(-50%);background:${cores[tipo]||cores.success};color:${tipo==='warning'?'#000':'#fff'};padding:10px 24px;border-radius:20px;font-size:13px;z-index:99999;font-weight:600;font-family:var(--ui),sans-serif;box-shadow:0 4px 20px rgba(0,0,0,.5);max-width:90vw;text-align:center;transition:opacity .3s`;document.body.appendChild(toast);setTimeout(()=>{toast.style.opacity='0'},2500);setTimeout(()=>toast.remove(),3000);}

(function(){const lat=document.getElementById('latitude').value,lng=document.getElementById('longitude').value;if(lat&&lng){const m=document.getElementById('link-maps-cliente'),w=document.getElementById('link-waze-cliente'),s=document.getElementById('link-sv-cliente');if(m)m.href=`https://maps.google.com/?q=${lat},${lng}`;if(w)w.href=`https://waze.com/ul?ll=${lat},${lng}&navigate=yes`;if(s)s.href=`https://www.google.com/maps/@?api=1&map_action=pano&viewpoint=${lat},${lng}`;}})();
document.addEventListener('DOMContentLoaded',()=>{const lat=parseFloat(document.getElementById('latitude').value),lng=parseFloat(document.getElementById('longitude').value);onRepetidorChange(document.getElementById('modelo_repetidor'));if(lat&&lng){initMapa(lat,lng);document.getElementById('cliente-badge').style.display='flex';document.getElementById('kml-filtros-bar').style.display='block';}});
</script>

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