<?php
declare(strict_types=1);

ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

require_once __DIR__ . '/../lib/db.php';
require_once __DIR__ . '/../lib/helpers.php';
require_once __DIR__ . '/../lib/consent.php';

start_app_session();

if (empty($_SESSION['user_id'])) {
  header('Location: login.php');
  exit;
}

$q = trim((string)($_GET['q'] ?? ''));

/**
 * ONAYSIZLAR SAYFASI (GÜNCEL KURAL)
 * webhook_logs tablosundan:
 * - arayan_no unique (1 kere)
 * - SADECE: hayatında 1 kere bile "1" basmamış olanlar
 * - VE: en az 1 kere "2" basmış olanlar
 * - Dropdown: sadece tus=2 event'leri göster
 * - İndir: popup -> alan seçimleri (Numara/Arama ID/Tarih/IP) + format (TXT/Excel)
 */

$sql = "SELECT id, arama_id, ip, token_ok, http_method, content_type, raw_body, created_at
        FROM webhook_logs
        WHERE 1=1";
$params = [];

if ($q !== '') {
  $sql .= " AND (
              arama_id LIKE ?
              OR ip LIKE ?
              OR raw_body LIKE ?
           )";
  $like = "%{$q}%";
  array_push($params, $like, $like, $like);
}

$sql .= " ORDER BY id DESC";
$st = db()->prepare($sql);
$st->execute($params);
$rows = $st->fetchAll() ?: [];

/** Group by arayan_no (unique) */
$groups = []; // [arayan_no => ['arayan_no'=>..., 'latest'=>..., 'events'=>[...]]]

foreach ($rows as $r) {
  $raw = (string)($r['raw_body'] ?? '');
  if ($raw === '') continue;

  $payload = parse_webhook_payload($raw);
  if (!is_array($payload)) continue;

  $arayan_no = payload_pick($payload, ['arayan_no', 'arayan', 'caller', 'from', 'msisdn']);
  if ($arayan_no === '') continue;

  $tus_bilgisi = payload_pick($payload, ['tus_bilgisi', 'digit']);
  $arama_id = payload_pick($payload, ['arama_id', 'call_id']);
  if ($arama_id === '') {
    $arama_id = (string)($r['arama_id'] ?? '');
  }

  $event = [
    'id' => (string)$r['id'],
    'arama_id' => $arama_id,
    'tus_bilgisi' => $tus_bilgisi,
    'created_at' => (string)$r['created_at'],
    'ip' => (string)($r['ip'] ?? ''),
  ];

  if (!isset($groups[$arayan_no])) {
    $groups[$arayan_no] = [
      'arayan_no' => $arayan_no,
      'events' => [],
    ];
  }

  $groups[$arayan_no]['events'][] = $event;
}

/** Sort events and set "latest" per arayan_no */
foreach ($groups as $k => $g) {
  usort($groups[$k]['events'], function ($a, $b) {
    $ta = strtotime((string)$a['created_at']) ?: 0;
    $tb = strtotime((string)$b['created_at']) ?: 0;
    if ($ta === $tb) return (int)$b['id'] <=> (int)$a['id'];
    return $tb <=> $ta;
  });

  $latestTus = '';
  foreach ($groups[$k]['events'] as $ev) {
    if ((string)$ev['tus_bilgisi'] !== '') {
      $latestTus = (string)$ev['tus_bilgisi'];
      break;
    }
  }

  $groups[$k]['latest'] = [
    'tus_bilgisi' => $latestTus,
    'created_at' => (string)($groups[$k]['events'][0]['created_at'] ?? ''),
  ];
}

/**
 * ✅ YENİ FİLTRE:
 * - Hayatında 1'e basmışsa: ASLA listelenmez
 * - En az 1 kez 2'ye basmışsa: listelenir
 * - Dropdown'da sadece 2 event'leri gösterilir
 */
$filtered = [];

foreach ($groups as $arayanNo => $g) {
  $hasApproved = false;
  $hasRejected = false;

  foreach ($g['events'] as $ev) {
    $t = (string)($ev['tus_bilgisi'] ?? '');
    if (consent_is_approved_digit($t)) { $hasApproved = true; break; }
    if (consent_is_rejected_digit($t)) { $hasRejected = true; }
  }

  if ($hasApproved) continue;
  if (!$hasRejected) continue;

  $onlyRejected = array_values(array_filter($g['events'], function ($ev) {
    return consent_is_rejected_digit((string)($ev['tus_bilgisi'] ?? ''));
  }));

  if (!$onlyRejected) continue;

  $g['events'] = $onlyRejected;

  // Listede sıralama: en güncel 2 kaydına göre (desc)
  $g['sort_ts'] = strtotime((string)($g['events'][0]['created_at'] ?? '')) ?: 0;

  $filtered[] = $g;
}

usort($filtered, function ($a, $b) {
  $ta = (int)($a['sort_ts'] ?? 0);
  $tb = (int)($b['sort_ts'] ?? 0);
  return $tb <=> $ta;
});

$unique_rows = array_values($filtered);
$total_rows = count($unique_rows);

/** ---------------- EXPORT ---------------- */
function normalize_fields(string $fieldsParam): array {
  $allowed = ['numara', 'arama_id', 'tarih', 'ip'];
  $parts = array_filter(array_map('trim', explode(',', $fieldsParam)));
  $parts = array_values(array_unique($parts));
  $parts = array_values(array_intersect($parts, $allowed));
  return $parts;
}

function field_label(string $f): string {
  if ($f === 'numara') return 'Numara';
  if ($f === 'arama_id') return 'Arama ID';
  if ($f === 'tarih') return 'Tarih';
  if ($f === 'ip') return 'IP';
  return $f;
}

function build_row(array $ev, string $arayanNo, array $fields): array {
  $row = [];
  foreach ($fields as $f) {
    if ($f === 'numara')   $row[] = $arayanNo;
    if ($f === 'arama_id') $row[] = (string)($ev['arama_id'] ?? '');
    if ($f === 'tarih')    $row[] = (string)($ev['created_at'] ?? '');
    if ($f === 'ip')       $row[] = (string)($ev['ip'] ?? '');
  }
  return $row;
}

$export = (string)($_GET['export'] ?? '');
if ($export === 'txt' || $export === 'csv') {
  $fields = normalize_fields((string)($_GET['fields'] ?? ''));

  // hiçbir şey seçilmezse default hepsi
  if (!$fields) {
    $fields = ['numara', 'arama_id', 'tarih', 'ip'];
  }

  $stamp = date('Ymd_His');

  // Sadece numara seçiliyse unique numara listesi indir
  $onlyNumara = (count($fields) === 1 && $fields[0] === 'numara');

  if ($export === 'txt') {
    header('Content-Type: text/plain; charset=UTF-8');
    header('Content-Disposition: attachment; filename="onaysizlar_' . $stamp . '.txt"');

    if ($onlyNumara) {
      foreach ($unique_rows as $g) {
        echo (string)$g['arayan_no'] . "\n";
      }
      exit;
    }

    $sep = " | ";
    echo implode($sep, array_map('field_label', $fields)) . "\n";
    echo str_repeat('-', 48) . "\n";

    foreach ($unique_rows as $g) {
      $arayanNo = (string)$g['arayan_no'];
      foreach ($g['events'] as $ev) {
        $row = build_row($ev, $arayanNo, $fields);
        $row = array_map(function ($v) {
          $v = (string)$v;
          return $v === '' ? '-' : $v;
        }, $row);
        echo implode($sep, $row) . "\n";
      }
    }
    exit;
  }

  header('Content-Type: text/csv; charset=UTF-8');
  header('Content-Disposition: attachment; filename="onaysizlar_' . $stamp . '.csv"');
  echo "\xEF\xBB\xBF";

  $out = fopen('php://output', 'w');
  fputcsv($out, array_map('field_label', $fields), ';');

  if ($onlyNumara) {
    foreach ($unique_rows as $g) {
      fputcsv($out, [(string)$g['arayan_no']], ';');
    }
    fclose($out);
    exit;
  }

  foreach ($unique_rows as $g) {
    $arayanNo = (string)$g['arayan_no'];
    foreach ($g['events'] as $ev) {
      $row = build_row($ev, $arayanNo, $fields);
      $row = array_map(function ($v) {
        $v = (string)$v;
        return $v === '' ? '-' : $v;
      }, $row);
      fputcsv($out, $row, ';');
    }
  }

  fclose($out);
  exit;
}
?>
<!doctype html>
<html lang="tr">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <title>Onaysızlar</title>
  <style>
    @font-face {
      font-family: 'Nexa';
      src: url('/assets/fonts/NexaRegular.woff2') format('woff2'),
           url('/assets/fonts/NexaRegular.woff') format('woff');
      font-weight: 400;
      font-style: normal;
      font-display: swap;
    }
    @font-face {
      font-family: 'Nexa';
      src: url('/assets/fonts/Nexa Bold.woff2') format('woff2'),
           url('/assets/fonts/Nexa Bold.woff') format('woff');
      font-weight: 700;
      font-style: normal;
      font-display: swap;
    }
    @font-face {
      font-family: 'Nexa';
      src: url('/assets/fonts/Nexa-Heavy.woff2') format('woff2'),
           url('/assets/fonts/Nexa-Heavy.woff') format('woff');
      font-weight: 800;
      font-style: normal;
      font-display: swap;
    }

    * { margin:0; padding:0; box-sizing:border-box; -webkit-tap-highlight-color:transparent; }

    body{
      font-family:'Nexa', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
      background:white; color:black; line-height:1.3; min-height:100vh;
      padding: env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left);
    }

    .container { max-width:100%; padding:8px; }

    .header{
      display:flex; align-items:center; justify-content:space-between;
      padding:12px 0 8px 0; margin-bottom:12px; gap: 10px;
    }
    .header-left{
      display:flex; flex-direction:column; gap: 4px; min-width: 0;
    }
    .header-title{ font-size:18px; font-weight:800; letter-spacing:-0.2px; }

    .header-actions{
      display:flex; align-items:center; gap:6px; flex-wrap:wrap; justify-content:flex-end;
    }

    .back-btn{
      background:#f0f0f0; border:none; padding:6px 12px; border-radius:16px;
      font-size:13px; font-family:'Nexa', sans-serif;
      display:flex; align-items:center; gap:3px;
      cursor:pointer; text-decoration:none; color:black; font-weight:700;
      white-space: nowrap;
    }

    .dl-btn{
      background:#ffebee;
      color:#c62828;
      border:none;
      padding:6px 12px;
      border-radius:16px;
      font-size:13px;
      font-family:'Nexa', sans-serif;
      display:inline-flex;
      align-items:center;
      gap:6px;
      cursor:pointer;
      text-decoration:none;
      font-weight:900;
      white-space: nowrap;
    }

    .search-form{ margin-bottom:12px; display:flex; gap:6px; }
    .search-input{
      flex:1; padding:10px 14px; border:1px solid #e0e0e0; border-radius:20px;
      font-size:15px; background:#f8f8f8; font-family:'Nexa', sans-serif;
    }
    .search-btn{
      padding:10px 18px; background:#f0f0f0; border:none; border-radius:20px;
      font-weight:700; cursor:pointer; font-family:'Nexa', sans-serif;
      font-size:14px; white-space:nowrap;
    }

    .total-count{ font-size:12px; color:#666; margin-bottom:8px; font-weight:700; padding-left:2px; }

    .call-item{
      background:#f8f8f8; border-radius:14px; padding:12px; margin-bottom:8px; position:relative;
    }
    .call-header{
      display:flex; justify-content:space-between; align-items:center; margin-bottom:8px; gap:10px;
    }
    .call-number{ font-size:16px; font-weight:800; word-break:break-all; }

    .call-status{
      display:flex; align-items:center; gap:8px; white-space:nowrap;
    }
    .status-pill{
      display:inline-block; padding:6px 12px; border-radius:999px;
      font-size:13px; font-weight:900;
      background:#ffebee; color:#c62828;
    }

    .dropdown-btn{
      width:100%; padding:10px; background:#e8e8e8; border:none; border-radius:10px;
      font-size:13px; color:#666; cursor:pointer;
      display:flex; align-items:center; justify-content:center; gap:6px; margin-top:6px;
      font-family:'Nexa', sans-serif; font-weight:700;
    }
    .dropdown-btn .btn-text, .dropdown-btn .arrow{ pointer-events:none; }

    .dropdown-content{
      display:none; background:#f0f0f0; border-radius:10px; padding:12px; margin-top:6px;
    }
    .dropdown-content.show{ display:block; }

    .info-row{
      display:flex; justify-content:space-between; padding:6px 0; border-bottom:1px solid #e0e0e0;
      font-size:13px; gap:10px;
    }
    .info-row:last-child{ border-bottom:none; }
    .info-label{ color:#666; font-weight:700; min-width:90px; }
    .info-value{ font-weight:800; text-align:right; max-width:75%; word-break:break-all; }

    .event-list{ display:flex; flex-direction:column; gap:8px; }
    .event-item{
      background:#fff; border-radius:10px; padding:10px; border:1px solid #e6e6e6;
    }
    .event-top{
      display:flex; align-items:center; justify-content:space-between; gap:10px; margin-bottom:6px;
    }
    .event-aramaid{ font-weight:900; font-size:13px; word-break:break-all; }
    .event-badge{
      display:inline-flex; align-items:center;
      font-size:12px; font-weight:900; padding:3px 10px; border-radius:999px; white-space:nowrap;
      background:#ffebee; color:#c62828;
    }
    .event-meta{
      display:flex; justify-content:space-between; gap:10px; font-size:12px; color:#666; font-weight:800;
    }

    .empty-state{ text-align:center; padding:30px 16px; color:#666; }
    .empty-state h3{ font-size:16px; margin-bottom:6px; font-weight:800; }
    .empty-state p{ font-size:14px; line-height:1.4; font-weight:700; }

    .footer{ text-align:center; padding:16px 0; color:#999; font-size:12px; margin-top:16px; font-weight:700; }

    @media (max-width:480px){
      .container{ padding:6px; }
      .call-item{ padding:10px; margin-bottom:6px; }
      .call-number{ font-size:15px; }
      .search-input{ padding:9px 12px; font-size:14px; }
      .search-btn{ padding:9px 14px; font-size:13px; }
    }

    @media (max-width:350px){
      .call-header{ flex-direction:column; align-items:flex-start; gap:6px; }
      .header-actions{ justify-content:flex-start; }
    }

    /* ---------- Modal ---------- */
    .modal-backdrop{
      position:fixed; inset:0;
      background: rgba(0,0,0,.45);
      display:none;
      align-items:flex-end;
      justify-content:center;
      padding: 14px;
      z-index: 9999;
    }
    .modal-backdrop.show{ display:flex; }

    .modal{
      width:100%;
      max-width: 520px;
      background:#fff;
      border-radius: 16px;
      padding: 12px;
    }
    .modal-head{
      display:flex; align-items:center; justify-content:space-between; gap:10px;
      padding: 6px 6px 10px 6px;
    }
    .modal-title{
      font-weight:900;
      font-size:16px;
      letter-spacing:-0.2px;
    }
    .modal-close{
      border:none;
      background:#f0f0f0;
      border-radius: 12px;
      padding: 8px 10px;
      cursor:pointer;
      font-family:'Nexa', sans-serif;
      font-weight:900;
      font-size: 13px;
    }
    .modal-body{
      background:#f8f8f8;
      border-radius: 14px;
      padding: 12px;
    }

    .seg{
      display:flex;
      gap: 8px;
      margin-bottom: 10px;
    }
    .seg label{
      flex:1;
      display:flex;
      align-items:center;
      justify-content:center;
      gap: 8px;
      padding: 10px;
      border-radius: 12px;
      background:#fff;
      border: 1px solid #e6e6e6;
      cursor:pointer;
      font-weight:900;
      font-size: 13px;
      user-select:none;
    }
    .seg input{ display:none; }
    .seg input:checked + span{
      color:#c62828;
    }
    .seg label.active{
      border-color:#ffd6dd;
      background:#ffebee;
    }

    .checkgrid{
      display:grid;
      grid-template-columns: repeat(2, minmax(0, 1fr));
      gap: 10px;
      margin-top: 10px;
    }
    @media (max-width:360px){
      .checkgrid{ grid-template-columns: 1fr; }
    }
    .chk{
      display:flex;
      align-items:center;
      gap: 10px;
      background:#fff;
      border: 1px solid #e6e6e6;
      border-radius: 12px;
      padding: 10px;
      cursor:pointer;
      user-select:none;
    }
    .chk input{
      width: 18px;
      height: 18px;
    }
    .chk .t{
      font-weight:900;
      font-size: 13px;
    }
    .modal-actions{
      display:flex;
      gap: 8px;
      margin-top: 12px;
    }
    .btn2{
      flex:1;
      border:none;
      border-radius: 12px;
      padding: 12px;
      font-family:'Nexa', sans-serif;
      font-weight: 900;
      cursor:pointer;
      font-size: 14px;
    }
    .btn2.primary{
      background:#ffebee;
      color:#c62828;
    }
    .btn2.ghost{
      background:#e8e8e8;
      color:#444;
    }
    .hint{
      margin-top: 10px;
      font-size: 12px;
      color:#666;
      font-weight:800;
      line-height: 1.35;
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="header">
      <div class="header-left">
        <div class="header-title">Onaysızlar</div>
      </div>

      <div class="header-actions">
        <button class="dl-btn" type="button" onclick="openExportModal()">İndir</button>
        <a href="dashboard.php" class="back-btn">← Panel</a>
      </div>
    </div>

    <form class="search-form" method="get">
      <input
        type="text"
        name="q"
        value="<?= htmlspecialchars($q, ENT_QUOTES, 'UTF-8') ?>"
        placeholder="Ara (arama_id / ip / raw_body)..."
        class="search-input"
      >
      <button type="submit" class="search-btn">Ara</button>
    </form>

    <?php if ($total_rows > 0): ?>
      <div class="total-count">Toplam <?= $total_rows ?> farklı onaysız arayan</div>
    <?php endif; ?>

    <?php if (!$unique_rows): ?>
      <div class="empty-state">
        <h3>Onaysız kayıt yok</h3>
        <p>Webhook loglarına onaysız kayıt geldikçe burada listelenecek.</p>
      </div>
    <?php else: ?>
      <?php foreach ($unique_rows as $g):
        $arayanNo = (string)$g['arayan_no'];
      ?>
        <div class="call-item">
          <div class="call-header">
            <div class="call-number"><?= htmlspecialchars($arayanNo, ENT_QUOTES, 'UTF-8') ?></div>
            <div class="call-status">
              <span class="status-pill">Onaysız</span>
            </div>
          </div>

          <button class="dropdown-btn" type="button" onclick="toggleDropdown(this)">
            <span class="btn-text">Arama ID'leri Göster</span>
            <span class="arrow">▼</span>
          </button>

          <div class="dropdown-content">
            <div class="info-row">
              <span class="info-label">Numara</span>
              <span class="info-value"><?= htmlspecialchars($arayanNo, ENT_QUOTES, 'UTF-8') ?></span>
            </div>

            <div style="height:10px"></div>

            <div class="event-list">
              <?php foreach ($g['events'] as $ev):
                $aramaId = (string)($ev['arama_id'] ?? '');
              ?>
                <div class="event-item">
                  <div class="event-top">
                    <div class="event-aramaid"><?= htmlspecialchars($aramaId !== '' ? $aramaId : '-', ENT_QUOTES, 'UTF-8') ?></div>
                    <div class="event-badge">Onaysız</div>
                  </div>
                  <div class="event-meta">
                    <div><?= htmlspecialchars((string)$ev['created_at'], ENT_QUOTES, 'UTF-8') ?></div>
                    <div><?= htmlspecialchars((string)$ev['ip'], ENT_QUOTES, 'UTF-8') ?></div>
                  </div>
                </div>
              <?php endforeach; ?>
            </div>

          </div>
        </div>
      <?php endforeach; ?>
    <?php endif; ?>

    <div class="footer">
      © <?= date('Y') ?> • NETGSM Santral MVP
    </div>
  </div>

  <!-- EXPORT MODAL -->
  <div class="modal-backdrop" id="exportBackdrop" onclick="backdropClose(event)">
    <div class="modal" role="dialog" aria-modal="true" aria-labelledby="exportTitle">
      <div class="modal-head">
        <div class="modal-title" id="exportTitle">İndirme Seçenekleri</div>
        <button class="modal-close" type="button" onclick="closeExportModal()">Kapat</button>
      </div>

      <div class="modal-body">
        <div class="seg" id="formatSeg">
          <label id="lblCsv">
            <input type="radio" name="fmt" value="csv" checked>
            <span>Excel (CSV)</span>
          </label>
          <label id="lblTxt">
            <input type="radio" name="fmt" value="txt">
            <span>TXT</span>
          </label>
        </div>

        <div class="checkgrid">
          <label class="chk">
            <input type="checkbox" id="f_numara" checked>
            <span class="t">Numara</span>
          </label>
          <label class="chk">
            <input type="checkbox" id="f_arama_id" checked>
            <span class="t">Arama ID</span>
          </label>
          <label class="chk">
            <input type="checkbox" id="f_tarih" checked>
            <span class="t">Tarih</span>
          </label>
          <label class="chk">
            <input type="checkbox" id="f_ip" checked>
            <span class="t">IP</span>
          </label>
        </div>

        <div class="hint">
          Seçtiğiniz alanlar indirilecek dosyaya eklenecek. Sadece “Numara” seçerseniz, numaralar tek satır halinde (unique) iner.
        </div>

        <div class="modal-actions">
          <button class="btn2 ghost" type="button" onclick="selectAllFields(true)">Hepsini Seç</button>
          <button class="btn2 primary" type="button" onclick="doExport()">İndir</button>
        </div>
      </div>
    </div>
  </div>

  <script>
    function toggleDropdown(button) {
      const dropdown = button.nextElementSibling;
      const txt = button.querySelector('.btn-text');
      const arrow = button.querySelector('.arrow');

      if (dropdown.classList.contains('show')) {
        dropdown.classList.remove('show');
        arrow.textContent = '▼';
        txt.textContent = "Arama ID'leri Göster";
      } else {
        document.querySelectorAll('.dropdown-content.show').forEach(item => {
          item.classList.remove('show');
          const btn = item.previousElementSibling;
          if (btn) {
            const t = btn.querySelector('.btn-text');
            const a = btn.querySelector('.arrow');
            if (a) a.textContent = '▼';
            if (t) t.textContent = "Arama ID'leri Göster";
          }
        });

        dropdown.classList.add('show');
        arrow.textContent = '▲';
        txt.textContent = "Arama ID'leri Gizle";
      }
    }

    document.addEventListener('DOMContentLoaded', function() {
      document.querySelectorAll('.dropdown-content').forEach(item => item.classList.remove('show'));
      syncFormatUI();
      document.querySelectorAll('input[name="fmt"]').forEach(r => r.addEventListener('change', syncFormatUI));
    });

    function openExportModal(){
      document.getElementById('exportBackdrop').classList.add('show');
      document.body.style.overflow = 'hidden';
    }
    function closeExportModal(){
      document.getElementById('exportBackdrop').classList.remove('show');
      document.body.style.overflow = '';
    }
    function backdropClose(e){
      if (e.target && e.target.id === 'exportBackdrop') closeExportModal();
    }

    function selectAllFields(on){
      document.getElementById('f_numara').checked = on;
      document.getElementById('f_arama_id').checked = on;
      document.getElementById('f_tarih').checked = on;
      document.getElementById('f_ip').checked = on;
    }

    function syncFormatUI(){
      const fmt = document.querySelector('input[name="fmt"]:checked')?.value || 'csv';
      const lblCsv = document.getElementById('lblCsv');
      const lblTxt = document.getElementById('lblTxt');
      if (fmt === 'csv') {
        lblCsv.classList.add('active');
        lblTxt.classList.remove('active');
      } else {
        lblTxt.classList.add('active');
        lblCsv.classList.remove('active');
      }
    }

    function doExport(){
      const fmt = document.querySelector('input[name="fmt"]:checked')?.value || 'csv';

      const fields = [];
      if (document.getElementById('f_numara').checked) fields.push('numara');
      if (document.getElementById('f_arama_id').checked) fields.push('arama_id');
      if (document.getElementById('f_tarih').checked) fields.push('tarih');
      if (document.getElementById('f_ip').checked) fields.push('ip');

      const params = new URLSearchParams(window.location.search);
      params.set('export', fmt);
      if (fields.length > 0) params.set('fields', fields.join(','));
      else params.delete('fields');

      window.location.href = window.location.pathname + '?' + params.toString();
      closeExportModal();
    }
  </script>
</body>
</html>
