<?php
header('Content-Type: text/html; charset=utf-8');
$ADMIN_PASS = "1234"; // troque
$dbPath = __DIR__ . "/storage/devices_db.json";

$pass = $_POST["pass"] ?? $_GET["pass"] ?? "";
if ($pass !== $ADMIN_PASS) {
  http_response_code(401);
  echo "401 - senha incorreta. Use ?pass=SUASENHA";
  exit;
}

if (!file_exists($dbPath)) {
  file_put_contents($dbPath, json_encode(new stdClass(), JSON_PRETTY_PRINT));
}

$db = json_decode(file_get_contents($dbPath), true);
if (!is_array($db)) $db = [];

$BASE = "https://updates.viso360.com.br/luiz";

function norm_mac($mac) {
  $mac = strtoupper(trim($mac));
  $mac = str_replace(["-", "."], ":", $mac);
  return $mac;
}

function save_db($path, $db) {
  file_put_contents($path, json_encode($db, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
}

function is_valid_ver($v) {
  if ($v === "") return true;
  return (bool)preg_match('/^\d+\.\d+\.\d+$/', $v);
}

$msg = "";
$action = $_POST["action"] ?? "";

/**
 * SAVE completo (cadastro/edição pelo topo)
 */
if ($action === "save") {
  $mac = norm_mac($_POST["mac"] ?? "");
  $active = ($_POST["active"] ?? "0") === "1";
  $note = trim($_POST["note"] ?? "");
  $digilink_ver = trim($_POST["digilink_ver"] ?? "");
  $cld24_ver = trim($_POST["cld24_ver"] ?? "");

  if ($mac === "") {
    $msg = "MAC invalido";
  } elseif (!is_valid_ver($digilink_ver) || !is_valid_ver($cld24_ver)) {
    $msg = "Versao invalida (use X.Y.Z ou vazio)";
  } else {
    if (!isset($db[$mac])) {
      $db[$mac] = [
        "active" => $active,
        "token" => "",
        "note" => $note,
        "digilink_ver" => $digilink_ver,
        "cld24_ver" => $cld24_ver,
        "updated_at" => gmdate("c")
      ];
    } else {
      $db[$mac]["active"] = $active;
      $db[$mac]["note"] = $note;
      $db[$mac]["digilink_ver"] = $digilink_ver;
      $db[$mac]["cld24_ver"] = $cld24_ver;
      $db[$mac]["updated_at"] = gmdate("c");
    }
    save_db($dbPath, $db);
    $msg = "Salvo: $mac";
  }
}

/**
 * Atualiza SOMENTE active
 */
if ($action === "set_active") {
  $mac = norm_mac($_POST["mac"] ?? "");
  $active = ($_POST["active"] ?? "0") === "1";

  if ($mac === "" || !isset($db[$mac])) {
    $msg = "MAC inexistente: $mac";
  } else {
    $db[$mac]["active"] = $active;
    $db[$mac]["updated_at"] = gmdate("c");
    save_db($dbPath, $db);
    $msg = "Status atualizado: $mac -> " . ($active ? "Active" : "Disabled");
  }
}

/**
 * Atualiza SOMENTE note (cliente)
 */
if ($action === "save_note") {
  $mac = norm_mac($_POST["mac"] ?? "");
  $note = trim($_POST["note"] ?? "");

  if ($mac === "" || !isset($db[$mac])) {
    $msg = "MAC inexistente: $mac";
  } else {
    $db[$mac]["note"] = $note;
    $db[$mac]["updated_at"] = gmdate("c");
    save_db($dbPath, $db);
    $msg = "Cliente atualizado: $mac";
  }
}

/**
 * Atualiza versões (somente se active)
 */
if ($action === "save_versions") {
  $mac = norm_mac($_POST["mac"] ?? "");
  $digilink_ver = trim($_POST["digilink_ver"] ?? "");
  $cld24_ver = trim($_POST["cld24_ver"] ?? "");

  if (!is_valid_ver($digilink_ver) || !is_valid_ver($cld24_ver)) {
    $msg = "Versao invalida (use X.Y.Z ou vazio)";
  } elseif (isset($db[$mac]) && !empty($db[$mac]["active"])) {
    $db[$mac]["digilink_ver"] = $digilink_ver;
    $db[$mac]["cld24_ver"] = $cld24_ver;
    $db[$mac]["updated_at"] = gmdate("c");
    save_db($dbPath, $db);
    $msg = "Versoes atualizadas: $mac";
  } else {
    $msg = "MAC nao ativo (ou inexistente): $mac";
  }
}

if ($action === "reset") {
  $mac = norm_mac($_POST["mac"] ?? "");
  if (isset($db[$mac])) {
    $db[$mac]["token"] = "";
    $db[$mac]["updated_at"] = gmdate("c");
    save_db($dbPath, $db);
    $msg = "Token resetado: $mac";
  }
}

if ($action === "reset_clear_versions") {
  $mac = norm_mac($_POST["mac"] ?? "");
  if (isset($db[$mac])) {
    $db[$mac]["token"] = "";
    $db[$mac]["digilink_ver"] = "";
    $db[$mac]["cld24_ver"] = "";
    $db[$mac]["updated_at"] = gmdate("c");
    save_db($dbPath, $db);
    $msg = "Token e versoes limpos: $mac";
  }
}

if ($action === "delete") {
  $mac = norm_mac($_POST["mac"] ?? "");
  unset($db[$mac]);
  save_db($dbPath, $db);
  $msg = "Removido: $mac";
}
?>
<!doctype html>
<html lang="pt-BR">
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

<title>viso360 - MAC admin</title>

<style>
:root{
  --bg:#0b1220;
  --card:rgba(255,255,255,0.06);
  --line:rgba(255,255,255,0.12);
  --text:rgba(255,255,255,0.92);
  --muted:rgba(255,255,255,0.7);
  --shadow:0 18px 40px rgba(0,0,0,0.35);
  --ok:#2bd576;
  --bad:#ff5c7a;
  --btn:rgba(255,255,255,0.10);
  --btnh:rgba(255,255,255,0.16);
  --in:rgba(255,255,255,0.10);
  --inh:rgba(255,255,255,0.16);
  --r:16px;
}

*{box-sizing:border-box}
body{
  margin:0;
  font-family: system-ui, -apple-system, Segoe UI, Roboto, Arial, sans-serif;
  background:
    radial-gradient(1200px 600px at 10% -10%, rgba(56,189,248,0.25), transparent 55%),
    radial-gradient(900px 500px at 90% 0%, rgba(168,85,247,0.22), transparent 50%),
    radial-gradient(900px 600px at 50% 120%, rgba(34,197,94,0.15), transparent 55%),
    var(--bg);
  color:var(--text);
}

.container{max-width:1320px;margin:26px auto;padding:0 16px;}
.card{
  border:1px solid var(--line);
  border-radius:var(--r);
  background:linear-gradient(180deg,var(--card),rgba(255,255,255,0.03));
  box-shadow:var(--shadow);
  overflow:hidden;
}
.header{
  padding:18px 20px;
  border-bottom:1px solid var(--line);
  display:flex;justify-content:space-between;gap:12px;align-items:flex-start;
}
h2{margin:0;font-size:18px}
.sub{margin-top:6px;font-size:12px;color:var(--muted)}
.badge{
  padding:8px 10px;border:1px solid var(--line);border-radius:999px;
  background:rgba(255,255,255,0.06);font-size:12px;color:var(--muted);white-space:nowrap;
}
.content{padding:20px}

.msg{
  padding:10px 12px;border-radius:14px;margin-bottom:16px;
  border:1px solid rgba(43,213,118,0.35);
  background:rgba(43,213,118,0.10);
  font-size:13px;
}

.section{
  border:1px solid var(--line);
  background:rgba(255,255,255,0.04);
  border-radius:16px;
  padding:16px;
  margin-bottom:18px;
}
.section-title{
  font-size:12px;color:var(--muted);text-transform:uppercase;letter-spacing:.3px;
  margin:0 0 12px 2px;
}

label{display:block;font-size:12px;color:var(--muted);margin:0 0 6px 2px}
input,select{
  width:100%;
  padding:10px;
  border-radius:12px;
  border:1px solid var(--line);
  background:var(--in);
  color:var(--text);
  outline:none;
}
input:focus,select:focus{background:var(--inh);border-color:rgba(255,255,255,0.22)}
input:disabled,select:disabled{opacity:.55;cursor:not-allowed}

.btn{
  padding:10px 12px;border-radius:12px;border:1px solid var(--line);
  background:var(--btn);color:var(--text);cursor:pointer;font-weight:600;
  text-decoration:none; display:inline-block;
}
.btn:hover{background:var(--btnh)}
.btn.primary{border-color:rgba(56,189,248,0.35);background:rgba(56,189,248,0.18)}
.btn.primary:hover{background:rgba(56,189,248,0.24)}
.btn.danger{border-color:rgba(255,92,122,0.35);background:rgba(255,92,122,0.16)}
.btn.danger:hover{background:rgba(255,92,122,0.22)}

.grid{
  display:grid;
  grid-template-columns: 1.2fr 0.7fr 0.9fr 0.9fr 2.6fr auto;
  gap:14px;
  align-items:end;
}
@media (max-width: 980px){
  .grid{grid-template-columns:1fr 1fr}
  .span-2{grid-column:1/-1}
}

.table-wrap{
  border:1px solid var(--line);
  border-radius:16px;
  background:rgba(255,255,255,0.03);
  overflow:auto;
}
table{border-collapse:collapse;width:100%;min-width:1320px}
th,td{padding:12px 10px;border-bottom:1px solid rgba(255,255,255,0.08);vertical-align:top;font-size:13px}
th{
  position:sticky;top:0;
  background:rgba(10,16,28,0.92);
  backdrop-filter: blur(10px);
  font-size:12px;color:rgba(255,255,255,0.78);
  text-transform:uppercase;letter-spacing:.3px;
}
tr:hover td{background:rgba(255,255,255,0.04)}

.pill{
  display:inline-flex;align-items:center;gap:8px;
  padding:6px 10px;border-radius:999px;border:1px solid var(--line);
  background:rgba(255,255,255,0.06);font-size:12px;color:var(--muted);
}
.dot{width:8px;height:8px;border-radius:999px;background:rgba(255,255,255,0.45)}
.pill.ok{border-color:rgba(43,213,118,0.35)} .pill.ok .dot{background:var(--ok)}
.pill.bad{border-color:rgba(255,92,122,0.35)} .pill.bad .dot{background:var(--bad)}

.row-flex{display:flex;gap:10px;align-items:center;flex-wrap:wrap}
.url{font-size:12px;color:rgba(255,255,255,0.75);word-break:break-all;line-height:1.35}
.small{margin-top:14px;font-size:12px;color:var(--muted)}

.note-input{min-width:340px}
.ver-input{min-width:150px}
.status-select{min-width:150px}
</style>
</head>
<meta charset="utf-8">
<body>
<div class="container">
  <div class="card">
    <div class="header">
      <div>
        <h2>MAC management</h2>
        <div class="sub">Status auto-save, versões com botão, cliente inline.</div>
      </div>
      <div class="badge">/luiz/admin.php?pass=YOURPASS</div>
    </div>

    <div class="content">
      <?php if ($msg) echo "<div class='msg'>".htmlspecialchars($msg)."</div>"; ?>

      <div class="section">
        <div class="section-title">Cadastrar / editar registro</div>

        <form method="post">
          <input type="hidden" name="pass" value="<?php echo htmlspecialchars($pass); ?>">
          <input type="hidden" name="action" value="save">

          <div class="grid">
            <div class="span-2">
              <label>MAC</label>
              <input name="mac" id="mac_input" placeholder="AA:BB:CC:DD:EE:FF" maxlength="17" required>
            </div>

            <div>
              <label>Status</label>
              <select name="active">
                <option value="1">Active</option>
                <option value="0">Disabled</option>
              </select>
            </div>

            <div>
              <label>DIGILINK ver</label>
              <input name="digilink_ver" placeholder="1.0.3">
            </div>

            <div>
              <label>CLD24 ver</label>
              <input name="cld24_ver" placeholder="3.1.2">
            </div>

            <div class="span-2">
              <label>Cliente</label>
              <input name="note" placeholder="Nome do cliente / observação">
            </div>

            <div>
              <button class="btn primary" type="submit">Save</button>
            </div>
          </div>
        </form>
      </div>

      <div class="table-wrap">
        <table>
          <tr>
            <th>MAC</th>
            <th>Status</th>
            <th>Token</th>
            <th>DIGILINK</th>
            <th>CLD24</th>
            <th>URLs</th>
            <th>Cliente</th>
            <th>Updated</th>
            <th>Ações</th>
          </tr>

          <?php foreach ($db as $mac => $rec): ?>
          <?php
            $is_active = !empty($rec["active"]);
            $dv = trim($rec["digilink_ver"] ?? "");
            $cv = trim($rec["cld24_ver"] ?? "");
            $durl = $dv ? ($BASE . "/releases/DIGILINK/" . $dv . "/app.bin") : "";
            $curl = $cv ? ($BASE . "/releases/CLD24/" . $cv . "/app.hex") : "";
            $note_val = (string)($rec["note"] ?? "");
          ?>
          <tr>
            <td><strong><?php echo htmlspecialchars($mac); ?></strong></td>

            <td>
              <div class="row-flex">
                <?php if ($is_active): ?>
                  <span class="pill ok"><span class="dot"></span>Active</span>
                <?php else: ?>
                  <span class="pill bad"><span class="dot"></span>Disabled</span>
                <?php endif; ?>

                <!-- STATUS (auto-save) -->
                <form method="post" class="js-status-form">
                  <input type="hidden" name="pass" value="<?php echo htmlspecialchars($pass); ?>">
                  <input type="hidden" name="action" value="set_active">
                  <input type="hidden" name="mac" value="<?php echo htmlspecialchars($mac); ?>">
                  <select name="active" class="status-select js-status-select">
                    <option value="1" <?php echo $is_active ? "selected" : ""; ?>>Active</option>
                    <option value="0" <?php echo !$is_active ? "selected" : ""; ?>>Disabled</option>
                  </select>
                </form>
              </div>
            </td>

            <td><?php echo !empty($rec["token"]) ? "<span class='pill ok'><span class='dot'></span>Yes</span>" : "<span class='pill'><span class='dot'></span>No</span>"; ?></td>

            <!-- VERSÕES (um form próprio) -->
            <td colspan="2">
              <form method="post" class="row-flex">
                <input type="hidden" name="pass" value="<?php echo htmlspecialchars($pass); ?>">
                <input type="hidden" name="action" value="save_versions">
                <input type="hidden" name="mac" value="<?php echo htmlspecialchars($mac); ?>">

                <input class="ver-input"
                       name="digilink_ver"
                       value="<?php echo htmlspecialchars($dv); ?>"
                       placeholder="DIGILINK 1.0.3"
                       <?php echo $is_active ? "" : "disabled"; ?>>

                <input class="ver-input"
                       name="cld24_ver"
                       value="<?php echo htmlspecialchars($cv); ?>"
                       placeholder="CLD24 3.1.2"
                       <?php echo $is_active ? "" : "disabled"; ?>>

                <button class="btn" type="submit" <?php echo $is_active ? "" : "disabled"; ?>>Salvar versões</button>
              </form>
            </td>

            <td class="url">
              <?php if ($durl) echo htmlspecialchars($durl) . "<br>"; ?>
              <?php if ($curl) echo htmlspecialchars($curl); ?>
            </td>

            <!-- NOTE inline (um form próprio) -->
            <td>
              <form method="post" class="row-flex js-note-form">
                <input type="hidden" name="pass" value="<?php echo htmlspecialchars($pass); ?>">
                <input type="hidden" name="action" value="save_note">
                <input type="hidden" name="mac" value="<?php echo htmlspecialchars($mac); ?>">

                <input class="note-input js-note-input"
                       name="note"
                       value="<?php echo htmlspecialchars($note_val); ?>"
                       placeholder="Nome do cliente">
                <button class="btn" type="submit">Salvar</button>
              </form>
            </td>

            <td><?php echo htmlspecialchars($rec["updated_at"] ?? ""); ?></td>

            <td>
              <div class="row-flex">

                <!-- BOTÃO DASHBOARD -->
                <a class="btn"
                   href="device.php?pass=<?php echo urlencode($pass); ?>&mac=<?php echo urlencode($mac); ?>">Dashboard</a>

                <form method="post">
                  <input type="hidden" name="pass" value="<?php echo htmlspecialchars($pass); ?>">
                  <input type="hidden" name="action" value="reset">
                  <input type="hidden" name="mac" value="<?php echo htmlspecialchars($mac); ?>">
                  <button class="btn" type="submit">Reset token</button>
                </form>

                <form method="post">
                  <input type="hidden" name="pass" value="<?php echo htmlspecialchars($pass); ?>">
                  <input type="hidden" name="action" value="reset_clear_versions">
                  <input type="hidden" name="mac" value="<?php echo htmlspecialchars($mac); ?>">
                  <button class="btn" type="submit">Reset + limpar</button>
                </form>

                <form method="post" onsubmit="return confirm('Deletar este MAC?');">
                  <input type="hidden" name="pass" value="<?php echo htmlspecialchars($pass); ?>">
                  <input type="hidden" name="action" value="delete">
                  <input type="hidden" name="mac" value="<?php echo htmlspecialchars($mac); ?>">
                  <button class="btn danger" type="submit">Delete</button>
                </form>
              </div>
            </td>
          </tr>
          <?php endforeach; ?>

        </table>
      </div>

      <p class="small">Access via: /luiz/admin.php?pass=YOURPASS</p>
    </div>
  </div>
</div>

<script>
// Máscara MAC AA:BB:CC:DD:EE:FF (no form do topo)
(function(){
  const input = document.getElementById('mac_input');
  if (!input) return;

  input.addEventListener('input', function() {
    let v = input.value.toUpperCase().replace(/[^0-9A-F]/g, '').substring(0, 12);
    let out = '';
    for (let i = 0; i < v.length; i++) {
      if (i > 0 && i % 2 === 0) out += ':';
      out += v[i];
    }
    input.value = out;
  });

  input.addEventListener('paste', function(e){
    e.preventDefault();
    let text = (e.clipboardData || window.clipboardData).getData('text');
    input.value = text;
    input.dispatchEvent(new Event('input'));
  });
})();

// Auto-save do Status (muda e já envia)
(function(){
  document.querySelectorAll('.js-status-select').forEach(sel => {
    sel.addEventListener('change', () => {
      const form = sel.closest('form');
      if (form) form.submit();
    });
  });
})();

// Auto-save do Cliente ao sair do campo (blur) se mudou
(function(){
  document.querySelectorAll('.js-note-form').forEach(form => {
    const input = form.querySelector('.js-note-input');
    if (!input) return;

    let last = input.value;

    input.addEventListener('keydown', (e) => {
      if (e.key === 'Enter') {
        e.preventDefault();
        form.submit();
      }
    });

    input.addEventListener('blur', () => {
      if (input.value !== last) form.submit();
    });

    form.addEventListener('submit', () => {
      last = input.value;
    });
  });
})();
</script>

</body>
</html>
