<?php
// cliente_form.php — Cadastrar / Editar cliente (LAYOUT REFORMULADO 2026)
$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;
}

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,
        'cto_nome'             => trim($_POST['cto_nome'] ?? '') ?: null,
        'olt_gps'              => trim($_POST['olt_gps']  ?? '') ?: null,
        'qtd_repetidor'        => max(0,(int)($_POST['qtd_repetidor'] ?? 0)),
        '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'] ?? ''),
        'modelo_repetidor'     => trim($_POST['modelo_repetidor'] ?? '') ?: null,
        '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'] ?? ''),
    ];
    $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'] ?? ''); }
    if (!isset($colsExistentes['cto_nome']))     unset($data['cto_nome']);
    if (!isset($colsExistentes['olt_gps']))      unset($data['olt_gps']);
    if (!isset($colsExistentes['qtd_repetidor'])) unset($data['qtd_repetidor']);
    if (!$data['nome']) $erros[] = 'Nome é obrigatório.';
    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);
                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();
                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(); }
    }
}

$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');

$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',
    'modelo_repetidor','qtd_repetidor','possui_cameras','camera_local',
    'ativo','bloqueado','observacoes'], '');
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>
<script src="assets/rota.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css"/>

<style>
.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}
.caixa-link-maps{background:#4285F4;color:#fff;width:24px;height:24px;border-radius:5px;display:flex;align-items:center;justify-content:center;text-decoration:none;font-size:11px}
.caixa-link-waze{background:#33ccff;color:#000;width:24px;height:24px;border-radius:5px;display:flex;align-items:center;justify-content:center;text-decoration:none;font-size:11px}

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

/* Barra de rolagem FULL WIDTH */
.marcacoes-full{width:100%;margin:6px 0;display:none}
.marcacoes-full-inner{background:var(--card);border:1px solid var(--border);border-radius:10px;padding:6px 10px}
.marcacoes-full-label{font-size:10px;color:var(--muted);font-family:var(--mono);letter-spacing:1px;margin-bottom:8px;display:flex;align-items:center;justify-content:space-between}
.marcacoes-full-busca{position:relative;margin-bottom:8px}
.marcacoes-full-busca input{width:100%;padding:6px 10px 6px 30px;background:var(--card2);border:1px solid var(--border);border-radius:6px;font-size:11px;color:var(--text);outline:none}
.marcacoes-full-busca input:focus{border-color:var(--cyan)}
.marcacoes-full-busca span{position:absolute;left:10px;top:50%;transform:translateY(-50%);font-size:12px;color:var(--muted)}
.marcacoes-scroll{display:flex;gap:8px;overflow-x:auto;overflow-y:hidden;scroll-behavior:smooth;-webkit-overflow-scrolling:touch;padding-bottom:6px}
.marcacoes-scroll::-webkit-scrollbar{height:5px}
.marcacoes-scroll::-webkit-scrollbar-track{background:var(--card2);border-radius:3px}
.marcacoes-scroll::-webkit-scrollbar-thumb{background:var(--border2);border-radius:3px}
.marcacao-card{flex:0 0 auto;min-width:100px;max-width:140px;background:var(--card2);border:1px solid var(--border);border-radius:8px;padding:6px 8px;cursor:pointer;transition:all .15s;text-align:center;position:relative}
.marcacao-card:hover{border-color:var(--cyan)}
.marcacao-card.selecionada{border-color:var(--green);background:rgba(16,185,129,.08)}
.marcacao-card-icone{display:flex;align-items:center;justify-content:center;width:22px;height:22px;border-radius:50%;background:var(--card);border:2px solid var(--cyan);margin:0 auto 4px auto;font-size:9px;color:var(--cyan);font-weight:900;font-family:monospace;line-height:1}
.marcacao-card.selecionada .marcacao-card-icone{border-color:var(--green);color:var(--green);background:rgba(16,185,129,.15);box-shadow:0 0 10px rgba(16,185,129,.4)}
.marcacao-card-nome{font-size:9px;font-weight:700;color:var(--text);margin-bottom:1px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.marcacao-card-dist{font-size:10px;color:var(--green);font-family:var(--mono);font-weight:800}
.marcacao-card-btn{display:block;margin-top:6px;padding:3px 8px;background:rgba(16,185,129,.15);color:var(--green);border:1px solid rgba(16,185,129,.3);border-radius:4px;font-size:9px;font-weight:700;cursor:pointer;text-align:center;transition:all .15s}
.marcacao-card-btn:hover{background:rgba(16,185,129,.25)}

/* Mapa FULL WIDTH */
#olt-mini-map{width:100%;height:280px;border-radius:12px;border:1px solid var(--border);margin:0 0 14px 0;overflow:hidden;display:none}
@media(min-width:768px){#olt-mini-map{height:320px}}
@media(min-width:1200px){#olt-mini-map{height:350px}}
.leaflet-container{background:#0a1220!important}

.leaflet-popup-content-wrapper{background:var(--card)!important;border:1px solid var(--border)!important;border-radius:10px!important;box-shadow:0 8px 24px rgba(0,0,0,.5)!important}
.leaflet-popup-content{font-family:var(--ui)!important;color:var(--text)!important;margin:8px 10px!important;font-size:11px!important;line-height:1.5!important}
.leaflet-popup-tip{background:var(--card)!important}
.leaflet-popup-close-button{color:var(--muted)!important;font-size:16px!important;top:4px!important;right:6px!important}
.leaflet-popup-close-button:hover{color:var(--text)!important}

.icone-cx-padrao{display:flex;align-items:center;justify-content:center;width:12px;height:12px;border-radius:50%;border:2px solid #00d4ff;box-shadow:0 0 6px rgba(0,212,255,0.4)}
.icone-cx-selecionada{display:flex;align-items:center;justify-content:center;width:18px;height:18px;border-radius:50%;border:3px solid #10b981;box-shadow:0 0 12px rgba(16,185,129,0.6)}

@keyframes spin{to{transform:translateY(-50%) rotate(360deg)}}
#cep-loader{animation:spin .8s linear infinite}

#painel-caixa{transition:all .3s ease}
#det-body{transition:all .3s ease}
#btn-toggle-det{transition:all .2s ease}
#btn-toggle-det:hover{background:rgba(255,255,255,.15)}
</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"/>
<input type="hidden" name="olt_gps" id="h-olt-gps"/>

<!-- 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" value="<?= e($v['telefone']) ?>" placeholder="(17) 99999-9999"/></div>
        <div class="form-group full"><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 (RUA / AVENIDA)</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();"><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 <span style="font-size:9px;color:var(--cyan)">(AUTO)</span></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>

    <!-- Badge do cliente -->
    <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 ?>" id="link-maps-cliente" target="_blank" class="caixa-link-maps" title="Google Maps" style="font-size:12px;font-weight:800">M</a>
            <a href="<?= $wazeHref ?>" id="link-waze-cliente" target="_blank" class="caixa-link-waze" title="Waze" style="font-size:10px;font-weight:800">W</a>
            <a href="<?= $svHref ?>" id="link-sv-cliente" target="_blank" title="Street View" style="background:#F4B400;color:#000;width:24px;height:24px;border-radius:5px;display:flex;align-items:center;justify-content:center;text-decoration:none;font-size:10px;font-weight:800">SV</a>
        </div>
    </div>
</div>

<!-- PAINEL DA CAIXA SELECIONADA -->
<div id="painel-caixa" style="display:none;margin-top:8px">
  <div style="background:rgba(0,212,255,.06);border:1px solid rgba(0,212,255,.25);border-radius:10px;padding:10px 14px">
    <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:4px">
      <div>
        <div style="font-size:9px;color:var(--muted);font-family:var(--mono);letter-spacing:1px">📦 CAIXA SELECIONADA</div>
        <div id="pc-nome" style="font-size:14px;font-weight:800;color:var(--cyan);line-height:1.2">—</div>
      </div>
      <div style="text-align:right">
        <div id="pc-dist" style="font-size:20px;font-weight:800;color:var(--green);font-family:var(--mono);line-height:1">—</div>
        <div style="font-size:9px;color:var(--muted);font-family:var(--mono)">distância</div>
      </div>
    </div>
    <div id="pc-end" style="font-size:11px;color:var(--muted);font-family:var(--mono);margin-bottom:8px;line-height:1.4">—</div>
    <div style="display:flex;gap:6px;flex-wrap:wrap">
      <a id="pc-maps" href="#" target="_blank" style="flex:1;min-width:64px;display:flex;align-items:center;justify-content:center;gap:5px;padding:6px 8px;background:#4285F4;color:#fff;border-radius:7px;text-decoration:none;font-size:11px;font-weight:700"><span style="font-size:13px">◉</span> Maps</a>
      <a id="pc-waze" href="#" target="_blank" style="flex:1;min-width:64px;display:flex;align-items:center;justify-content:center;gap:5px;padding:6px 8px;background:#33ccff;color:#000;border-radius:7px;text-decoration:none;font-size:11px;font-weight:700"><span style="font-size:13px">🔵</span> Waze</a>
      <a id="pc-sv" href="#" target="_blank" style="flex:1;min-width:64px;display:flex;align-items:center;justify-content:center;gap:5px;padding:6px 8px;background:#F4B400;color:#000;border-radius:7px;text-decoration:none;font-size:11px;font-weight:700"><span style="font-size:13px">📷</span> Street</a>
      <button type="button" id="btn-toggle-det" onclick="handleToggleDetalhes()" style="flex:1;min-width:64px;display:flex;align-items:center;justify-content:center;gap:5px;padding:6px 8px;background:rgba(255,255,255,.08);color:var(--text);border:1px solid var(--border);border-radius:7px;cursor:pointer;font-size:11px;font-weight:700"><span style="font-size:13px">📋</span> <span id="btn-toggle-det-lbl">Detalhes</span></button>
      <button type="button" onclick="salvarCaixaSelecionada()" style="flex:1;min-width:80px;display:flex;align-items:center;justify-content:center;gap:4px;padding:6px 8px;background:rgba(16,185,129,.15);color:var(--green);border:1px solid rgba(16,185,129,.35);border-radius:7px;cursor:pointer;font-size:11px;font-weight:700"><span style="font-size:13px">💾</span> Salvar</button>
    </div>
    <div id="det-body" style="display:none;margin-top:10px;padding-top:10px;border-top:1px solid rgba(0,212,255,.18)">
      <div style="text-align:center;padding:16px;color:var(--muted);font-size:12px">Carregando...</div>
    </div>
  </div>
</div>

<!-- BARRA DE ROLAGEM FULL WIDTH -->
<div class="marcacoes-full" id="marcacoes-full">
    <div class="marcacoes-full-inner">
        <div class="marcacoes-full-label">
            <span>📦 CAIXAS PRÓXIMAS (até 2 km)</span>
            <div style="display:flex;gap:6px">
              <button type="button" class="btn btn-ghost btn-sm" onclick="centralizarCliente()" style="font-size:10px;padding:4px 8px;" title="Centralizar mapa no cliente">🎯 Centralizar</button>
            </div>
        </div>
        <div class="marcacoes-full-busca">
            <span>⌕</span>
            <input type="text" id="busca-caixas" placeholder="Buscar caixa por nome..." oninput="filtrarMarcacoesScroll()"/>
        </div>
        <div class="marcacoes-scroll" id="marcacoes-scroll"></div>
    </div>
</div>

<!-- MAPA FULL WIDTH -->
<div id="olt-mini-map"></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 <span style="font-size:9px;color:var(--cyan)">(AUTO)</span></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" style="flex:1">
              <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" value="<?= (int)($v['qtd_repetidor'] ?? 1) ?>" min="0" max="10" title="Quantidade de repetidores" style="width:60px;text-align:center;font-family:var(--mono);font-weight:700;flex-shrink:0" id="qtd_repetidor_input"/>
          </div>
          <span class="form-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="button" onclick="submeterPara('editar')" 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>
// ═══════════════════ VARIÁVEIS GLOBAIS ═══════════════════
let _map = null, _mCli = null, _routeLine = null, _rotaToken = 0;
let _mCaixas = [];
let _caixas = [], _caixaAtual = null;
let _detAberto = false;
let _caixaDetAtual = null;

// ═══════════════════ UTILITÁRIOS ═══════════════════
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'; }
function normStr(s){return (s||'').toLowerCase().replace(/[^a-z0-9]/g,'')}

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

async function loadCaixas() {
    if (_caixas.length > 0) return _caixas;
    try {
        const resp = await fetch('ajax/ctos.php');
        const data = await resp.json();
        if (data.ok && data.ctos) { _caixas = data.ctos; return _caixas; }
    } catch(e) {}
    return [];
}

// ═══════════════════ ÍCONES ═══════════════════
function criarIconeCaixa(selecionada = false) {
    if (selecionada) {
        return L.divIcon({
            className: '',
            html: `<div class="icone-cx-selecionada"></div>`,
            iconSize: [18, 18],
            iconAnchor: [9, 9]
        });
    }
    return L.divIcon({
        className: '',
        html: `<div class="icone-cx-padrao"></div>`,
        iconSize: [12, 12],
        iconAnchor: [6, 6]
    });
}

// ═══════════════════ INICIALIZAR MAPA ═══════════════════
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: 15, zoomControl: false, attributionControl: false });
        const darkLayer = L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png');
        const satelliteLayer = L.tileLayer('https://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}');
        darkLayer.addTo(_map);
        L.control.layers({'🌑 Dark': darkLayer, '🛰 Satélite': satelliteLayer}, {}, {position: 'topright'}).addTo(_map);
        L.control.zoom({position: 'bottomright'}).addTo(_map);
    }
    const iconCasa = L.divIcon({className:'',html:`
      <div style="position:relative;width:44px;height:44px">
        <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:6px;border-radius:50%;background:#00d4ff;border:3px solid #fff;box-shadow:0 0 20px #00d4ff,0 0 6px #000;display:flex;align-items:center;justify-content:center;font-size:14px">🏠</div>
      </div>
    `,iconSize:[44,44],iconAnchor:[22,22]});
    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], 15);
    setTimeout(() => _map.invalidateSize(), 200);
}

// ═══════════════════ ENDEREÇO DA CAIXA ═══════════════════
async function obterEnderecoCaixa(c) {
    if (c.endereco) return c.endereco;
    if (c._endLoading) return c._endLoading;
    c._endLoading = (async () => {
        try {
            const r = await fetch(`ajax/geocodificar.php?acao=reverse&lat=${c.lat}&lng=${c.lng}`);
            const d = await r.json();
            if (d.ok) {
                const partes = [d.logradouro, d.numero, d.bairro, d.cidade].filter(Boolean);
                c.endereco = partes.join(', ') || 'Endereço não encontrado';
            } else {
                c.endereco = 'Endereço não encontrado';
            }
        } catch (e) {
            c.endereco = 'Endereço não encontrado';
        }
        return c.endereco;
    })();
    return c._endLoading;
}

// ═══════════════════ ATUALIZAR MARCADORES NO MAPA ═══════════════════
function atualizarMarcadoresMapa(idxSelecionado = null) {
    _mCaixas.forEach(m => _map.removeLayer(m));
    _mCaixas = [];

    const temSelecao = idxSelecionado !== null;

    _caixas.forEach((c, idx) => {
        const prox  = c.dist <= 2000;
        const ehSel = temSelecao && idx === idxSelecionado;

        if (temSelecao && !ehSel) return;
        if (!temSelecao && !prox) return;

        const icon = criarIconeCaixa(ehSel);
        const marker = L.marker([c.lat, c.lng], {icon}).addTo(_map);

        const popupContent = `
            <div style="min-width:130px;text-align:center">
                <b style="color:var(--cyan);font-size:12px;display:block;margin-bottom:3px">${c.name}</b>
                <span style="font-size:11px;color:var(--green);font-family:monospace;font-weight:700">${fmtDist(c.dist)}</span>
            </div>`;
        marker.bindPopup(popupContent, {maxWidth:220, closeButton:true});

        marker.on('popupopen', () => {
            if (!c.endereco) {
                obterEnderecoCaixa(c).then(end => {
                    atualizarCardEndereco(idx, end);
                });
            }
        });
        marker.on('click', () => selecionarMarcacao(idx, true));

        if (ehSel) setTimeout(() => marker.openPopup(), 200);
        _mCaixas.push(marker);
    });
}

// ═══════════════════ BARRA DE ROLAGEM ═══════════════════
function filtrarMarcacoesScroll() {
    const busca = document.getElementById('busca-caixas').value.toLowerCase();
    renderMarcacoesScroll(busca);
}

function renderMarcacoesScroll(filtro = '') {
    const container = document.getElementById('marcacoes-full');
    const scroll = document.getElementById('marcacoes-scroll');
    const buscaAtual = (filtro || document.getElementById('busca-caixas')?.value || '').toLowerCase();

    // Todas as caixas até 2km (sem filtro CX)
    let proximas = _caixas.filter(c => c.dist <= 2000);
    
    // Aplica busca por nome se houver texto
    if (buscaAtual) {
        proximas = proximas.filter(c => c.name.toLowerCase().includes(buscaAtual));
    }
    
    if (proximas.length === 0) {
        container.style.display = 'block';
        scroll.innerHTML = '<div style="padding:12px;text-align:center;color:var(--muted);font-size:11px;white-space:nowrap">Nenhuma caixa encontrada</div>';
        return;
    }
    container.style.display = 'block';

    scroll.innerHTML = proximas.map((c, i) => {
        const globalIdx = _caixas.indexOf(c);
        const sel = _caixaAtual && _caixaAtual.name === c.name && _caixaAtual.lat === c.lat;
        return `<div class="marcacao-card${sel ? ' selecionada' : ''}" id="marcacao-${globalIdx}">
            <div class="marcacao-card-icone">📍</div>
            <div class="marcacao-card-nome">${c.name}</div>
            <div class="marcacao-card-dist">${fmtDist(c.dist)}</div>
            <button class="marcacao-card-btn" onclick="event.stopPropagation();selecionarMarcacao(${globalIdx});salvarCaixaSelecionada()">✓ Vincular</button>
        </div>`;
    }).join('');
    
    // Seleciona automaticamente a primeira se não houver seleção
    if (!_caixaAtual && proximas.length > 0) {
        const primeiroGlobal = _caixas.indexOf(proximas[0]);
        selecionarMarcacao(primeiroGlobal);
    }
}

// ═══════════════════ ROTEAMENTO ═══════════════════
async function calcularERenderRota(map, latA, lngA, latB, lngB, lr, opts = {}) {
    const cor = opts.cor || '#10b981';
    const weight = opts.weight || 4;

    if (lr.layers && lr.layers.length) {
        lr.layers.forEach(l => { try { map.removeLayer(l); } catch(e){} });
        lr.layers = [];
    }

    try {
        const url = `https://router.project-osrm.org/route/v1/driving/${lngA},${latA};${lngB},${latB}?overview=full&geometries=geojson`;
        const resp = await fetch(url, { signal: AbortSignal.timeout(8000) });
        if (!resp.ok) throw new Error('OSRM error');
        const data = await resp.json();
        if (!data.routes || !data.routes.length) throw new Error('Sem rota');

        const coords = data.routes[0].geometry.coordinates.map(([ln, lt]) => [lt, ln]);
        const dist = data.routes[0].distance;
        const linha = L.polyline(coords, { color: cor, weight: weight, opacity: 0.85, lineJoin: 'round', lineCap: 'round' }).addTo(map);

        if (coords.length > 2) {
            const setaIco = L.divIcon({ className: '', html: `<div style="color:${cor};font-size:16px;text-shadow:0 0 4px #000">➤</div>`, iconSize: [18,18], iconAnchor: [9,9] });
            const seta = L.marker(coords[Math.floor(coords.length / 2)], {icon: setaIco, interactive: false}).addTo(map);
            lr.layers = [linha, seta];
        } else {
            lr.layers = [linha];
        }

        const distLabel = dist < 1000 ? `${Math.round(dist)} m` : `${(dist/1000).toFixed(2)} km`;
        const labelIco = L.divIcon({ className: '', html: `<div style="background:rgba(0,0,0,.72);color:#fff;font-size:9px;font-family:monospace;padding:2px 6px;border-radius:8px;white-space:nowrap;box-shadow:0 1px 4px rgba(0,0,0,.5)">${distLabel}</div>`, iconSize: [60,20], iconAnchor: [30,10] });
        const pontoMeio = coords[Math.floor(coords.length * 0.4)];
        const labelMark = L.marker(pontoMeio, {icon: labelIco, interactive: false}).addTo(map);
        lr.layers.push(labelMark);
    } catch(e) {
        console.warn('OSRM falhou, usando linha reta:', e.message);
        const linha = L.polyline([[latA,lngA],[latB,lngB]], { color: cor, weight: weight, opacity: 0.6, dashArray: '8 6' }).addTo(map);
        lr.layers = [linha];
    }
}

function atualizarCardEndereco(idx, end) {
    const el = document.getElementById(`marcacao-end-${idx}`);
    if (el) el.textContent = end;
}

// ═══════════════════ PAINEL DA CAIXA ═══════════════════
function atualizarPainelCaixa(c, end) {
    const p = document.getElementById('painel-caixa');
    if (!p) return;
    _caixaDetAtual = c;
    document.getElementById('pc-nome').textContent = c.name;
    document.getElementById('pc-end').textContent  = end || '…';
    document.getElementById('pc-dist').textContent = fmtDist(c.dist);
    document.getElementById('pc-maps').href = `https://maps.google.com/?q=${c.lat},${c.lng}`;
    document.getElementById('pc-waze').href = `https://waze.com/ul?ll=${c.lat},${c.lng}&navigate=yes`;
    document.getElementById('pc-sv').href   = `https://www.google.com/maps/@?api=1&map_action=pano&viewpoint=${c.lat},${c.lng}`;
    p.style.display = 'block';

    if (_detAberto) {
        carregarDetalhesCaixa();
    }
}

function handleToggleDetalhes() {
    const body = document.getElementById('det-body');
    const lbl  = document.getElementById('btn-toggle-det-lbl');
    if (!body || !lbl) return;
    _detAberto = !_detAberto;
    if (_detAberto) {
        body.style.display = 'block';
        lbl.textContent = 'Ocultar';
        carregarDetalhesCaixa();
    } else {
        body.style.display = 'none';
        lbl.textContent = 'Detalhes';
    }
}

async function carregarDetalhesCaixa() {
    if (!_caixaDetAtual) return;
    const c = _caixaDetAtual;
    const body = document.getElementById('det-body');
    body.innerHTML = '<div style="text-align:center;padding:14px;color:var(--muted);font-size:12px">⟳ Carregando...</div>';
    const nomeClienteAtual = document.getElementById('nome')?.value?.trim() || 'este cliente';

    try {
        const resp = await fetch(`ajax/caixa_detalhes.php?nome=${encodeURIComponent(c.name)}&lat=${c.lat}&lng=${c.lng}`);
        if (!resp.ok) throw new Error('Endpoint indisponível');
        const d = await resp.json();

        let html = '';
        if (d.clientes && d.clientes.length) {
            html += `<div style="margin-bottom:10px"><div style="font-size:10px;color:var(--muted);font-family:var(--mono);letter-spacing:1px;margin-bottom:6px">👥 CLIENTES NESTA CAIXA (${d.clientes.length})</div>`;
            d.clientes.forEach(cl => {
                html += `<div style="display:flex;align-items:center;justify-content:space-between;padding:6px 10px;background:var(--card);border:1px solid var(--border);border-radius:7px;margin-bottom:4px">
                    <div><div style="font-size:12px;font-weight:600">${cl.nome}</div><div style="font-size:10px;color:var(--muted);font-family:var(--mono)">${cl.plano||'—'} · ${cl.status||'ativo'}</div></div>
                    <a href="cliente_detalhe.php?id=${cl.id}" style="font-size:10px;color:var(--cyan);text-decoration:none;font-weight:700">Ver ›</a>
                </div>`;
            });
            html += `</div>`;
        } else {
            html += `<div style="font-size:11px;color:var(--muted);margin-bottom:10px">Nenhum cliente cadastrado nesta caixa ainda.</div>`;
        }

        if (d.fotos && d.fotos.length) {
            html += `<div style="font-size:10px;color:var(--muted);font-family:var(--mono);letter-spacing:1px;margin-bottom:6px">📸 FOTOS (${d.fotos.length})</div><div style="display:flex;flex-wrap:wrap;gap:6px">`;
            d.fotos.forEach(f => { html += `<a href="${f.url}" target="_blank"><img src="${f.url}" style="width:64px;height:64px;object-fit:cover;border-radius:6px;border:1px solid var(--border)"/></a>`; });
            html += `</div>`;
        }
        body.innerHTML = html;
    } catch(e) {
        body.innerHTML = `<div style="font-size:10px;color:var(--muted);text-align:center">Lista de clientes/fotos indisponível.</div>`;
    }
}

// ═══════════════════ SALVAR CAIXA SELECIONADA ═══════════════════
function salvarCaixaSelecionada() {
    if (!_caixaDetAtual && !_caixaAtual) {
        alert('Selecione uma caixa primeiro.');
        return;
    }
    const c = _caixaDetAtual || _caixaAtual;
    document.getElementById('h-cto-nome').value = c.name;
    document.getElementById('h-olt-gps').value  = c.lat + ',' + c.lng;

    const toast = document.createElement('div');
    toast.textContent = '✓ Caixa vinculada: ' + c.name + ' (salve o formulário para confirmar)';
    toast.style.cssText = 'position:fixed;bottom:24px;left:50%;transform:translateX(-50%);background:var(--green);color:#fff;padding:10px 20px;border-radius:20px;font-size:12px;z-index:9999;font-weight:600;box-shadow:0 4px 16px rgba(0,0,0,.4);max-width:90vw;text-align:center';
    document.body.appendChild(toast);
    setTimeout(() => { toast.style.opacity='0'; toast.style.transition='opacity .3s'; }, 2200);
    setTimeout(() => toast.remove(), 2600);
}

function centralizarCliente() {
    const lat = parseFloat(document.getElementById('latitude').value);
    const lng = parseFloat(document.getElementById('longitude').value);
    if (!lat || !lng) { alert('Localização do cliente não definida.'); return; }
    if (!_map) return;
    _map.setView([lat, lng], 16);
}

// ═══════════════════ SELEÇÃO DE MARCAÇÃO ═══════════════════
function selecionarMarcacao(idx, fromMap = false) {
    const c = _caixas[idx];
    if (!c) return;
    _caixaAtual = c;
    
    document.getElementById('h-cto-nome').value = c.name;
    document.getElementById('h-olt-gps').value = c.lat + ',' + c.lng;
    
    // Destaca na barra
    document.querySelectorAll('.marcacao-card').forEach(el => el.classList.remove('selecionada'));
    const card = document.getElementById(`marcacao-${idx}`);
    if (card) {
        card.classList.add('selecionada');
        card.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' });
    }
    
    atualizarMarcadoresMapa(idx);
    
    const lat = parseFloat(document.getElementById('latitude').value);
    const lng = parseFloat(document.getElementById('longitude').value);
    
    if (lat && lng) {
        _map.fitBounds([[lat, lng], [c.lat, c.lng]], {padding: [40, 40]});
    } else {
        _map.setView([c.lat, c.lng], 15);
    }
    
    const marcador = _mCaixas.find(m => { const ll = m.getLatLng(); return ll.lat === c.lat && ll.lng === c.lng; });
    if (marcador) marcador.openPopup();
    
    obterEnderecoCaixa(c).then(end => {
        atualizarCardEndereco(idx, end);
        atualizarPainelCaixa(c, end);
    });
    
    // Rota
    const meuToken = ++_rotaToken;
    if (_routeLine) {
        (Array.isArray(_routeLine) ? _routeLine : [_routeLine]).forEach(l => { try { if (_map.hasLayer(l)) _map.removeLayer(l); } catch(e){} });
        _routeLine = null;
    }
    if (!lat || !lng) return;
    const lr = { layers: [] };
    calcularERenderRota(_map, lat, lng, c.lat, c.lng, lr, { cor: '#10b981', weight: 5 })
        .then(() => { if (_rotaToken !== meuToken) { (lr.layers || []).forEach(l => { try { _map.removeLayer(l); } catch(e){} }); } else { _routeLine = lr.layers; } })
        .catch(() => {});
}

// ═══════════════════ GPS ═══════════════════
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)} (±${Math.round(pos.coords.accuracy)}m)`);
        
        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);
        await loadCaixas();
        _caixas.forEach(c => { c.dist = haversineM(lat, lng, c.lat, c.lng); });
        _caixas.sort((a,b) => a.dist - b.dist);
        atualizarMarcadoresMapa();
        renderMarcacoesScroll();
        
        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 });
}

// ═══════════════════ DEMAIS FUNÇÕES ═══════════════════
function onCidadeChange(sel) {
    const vlans = {'Jales':'1001','Paranapuã':'1002','Mesópolis':'1004','Santa Albertina':'1005','Populina':'1003','Dirce Reis':'1001'};
    document.getElementById('vlan').value = vlans[sel.value] || '';
}

let _cepBuscaTimeout;
function onEnderecoChange() { atualizarBadgeEndereco(); clearTimeout(_cepBuscaTimeout); _cepBuscaTimeout = setTimeout(buscarCepPorEndereco, 800); }

function buscarCepPorEndereco() {
    const rua = document.getElementById('endereco_logradouro').value.trim();
    const cidade = document.getElementById('endereco_cidade').value;
    const cepInput = document.getElementById('endereco_cep');
    if (!rua || !cidade) return;
    if (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();
    const num = document.getElementById('endereco_numero').value.trim();
    const bai = document.getElementById('endereco_bairro').value.trim();
    const cidSel = document.getElementById('endereco_cidade');
    const cid = cidSel.value;
    let parte1 = log; if (num) parte1 += (parte1 ? ', ' : '') + num;
    let end = parte1; 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 mapsEl = document.getElementById('link-maps-cliente'), wazeEl = document.getElementById('link-waze-cliente'), svEl = document.getElementById('link-sv-cliente');
        if (mapsEl) mapsEl.href = `https://maps.google.com/?q=${lat},${lng}`;
        if (wazeEl) wazeEl.href = `https://waze.com/ul?ll=${lat},${lng}&navigate=yes`;
        if (svEl) svEl.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 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();}

// Inicializa links
(function() {
    const lat = document.getElementById('latitude').value, lng = document.getElementById('longitude').value;
    if (lat && lng) {
        const mapsEl = document.getElementById('link-maps-cliente'), wazeEl = document.getElementById('link-waze-cliente'), svEl = document.getElementById('link-sv-cliente');
        if (mapsEl) mapsEl.href = `https://maps.google.com/?q=${lat},${lng}`;
        if (wazeEl) wazeEl.href = `https://waze.com/ul?ll=${lat},${lng}&navigate=yes`;
        if (svEl) svEl.href = `https://www.google.com/maps/@?api=1&map_action=pano&viewpoint=${lat},${lng}`;
    }
})();

// ═══════════════════ INICIALIZAÇÃO ═══════════════════
document.addEventListener('DOMContentLoaded', () => {
    const lat = parseFloat(document.getElementById('latitude').value);
    const lng = parseFloat(document.getElementById('longitude').value);
    if (lat && lng) {
        initMapa(lat, lng);
        document.getElementById('cliente-badge').style.display = 'flex';
        loadCaixas().then(() => {
            _caixas.forEach(c => { c.dist = haversineM(lat, lng, c.lat, c.lng); });
            _caixas.sort((a,b) => a.dist - b.dist);
            atualizarMarcadoresMapa();
            renderMarcacoesScroll();
        });
    }
    
    const repetidorSelect = document.querySelector('select[name="modelo_repetidor"]');
    const qtdInput = document.getElementById('qtd_repetidor_input');
    if (repetidorSelect && qtdInput) {
        const toggleQtd = () => { if (repetidorSelect.value === '') { qtdInput.style.display = 'none'; qtdInput.value = '0'; } else { qtdInput.style.display = ''; if (qtdInput.value === '0') qtdInput.value = '1'; } };
        repetidorSelect.addEventListener('change', toggleQtd);
        toggleQtd();
    }
});
</script>

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