<?php
declare(strict_types=1);

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

/**
 * admin/calls.php
 * ✅ Onaylar.php / Onaysiz.php ile aynı sade tasarım (Nexa + kart UI)
 * ✅ Mobil uyumlu
 * ✅ Güvenli: calls tablosu yoksa da sayfa çalışır (0 gösterir)
 * ✅ Filtre: q, status, direction, from/to
 * ✅ Sayfalama
 * ✅ Detay: kart içinde dropdown
 */

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

start_app_session();

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

/** Kullanıcı e-postası */
$userEmail = '';
try {
  $st = db()->prepare("SELECT email FROM users WHERE id=? LIMIT 1");
  $st->execute([(int)$_SESSION['user_id']]);
  $userEmail = (string)($st->fetchColumn() ?: '');
} catch (Throwable $e) {}

/** Helpers: tablo var mı / kolonları al */
function table_exists(string $table): bool {
  try {
    $pdo = db();
    $dbName = (string)$pdo->query("SELECT DATABASE()")->fetchColumn();
    if ($dbName === '') return false;
    $st = $pdo->prepare("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=? AND table_name=? LIMIT 1");
    $st->execute([$dbName, $table]);
    return ((int)$st->fetchColumn() === 1);
  } catch (Throwable $e) {
    return false;
  }
}

function table_columns(string $table): array {
  try {
    $pdo = db();
    $cols = [];
    $st = $pdo->query("SHOW COLUMNS FROM `{$table}`");
    while ($r = $st->fetch()) {
      if (!empty($r['Field'])) $cols[] = (string)$r['Field'];
    }
    return $cols;
  } catch (Throwable $e) {
    return [];
  }
}

/** Filtreler */
$q         = trim((string)($_GET['q'] ?? ''));
$status    = trim((string)($_GET['status'] ?? ''));
$direction = trim((string)($_GET['direction'] ?? ''));
$from      = trim((string)($_GET['from'] ?? '')); // YYYY-MM-DD
$to        = trim((string)($_GET['to'] ?? ''));   // YYYY-MM-DD

$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 20;
$offset  = ($page - 1) * $perPage;

/** Data */
$rows = [];
$total = 0;
$hasTable = table_exists('calls');
$cols = $hasTable ? table_columns('calls') : [];
$colSet = array_flip($cols);

/** “muhtemel kolonlar” */
$colId        = isset($colSet['id']) ? 'id' : (isset($colSet['call_id']) ? 'call_id' : null);
$colCaller    = isset($colSet['caller']) ? 'caller' : (isset($colSet['from']) ? 'from' : (isset($colSet['src']) ? 'src' : null));
$colCallee    = isset($colSet['callee']) ? 'callee' : (isset($colSet['to']) ? 'to' : (isset($colSet['dst']) ? 'dst' : null));
$colStatus    = isset($colSet['status']) ? 'status' : (isset($colSet['call_status']) ? 'call_status' : null);
$colDirection = isset($colSet['direction']) ? 'direction' : (isset($colSet['dir']) ? 'dir' : null);
$colStarted   = isset($colSet['started_at']) ? 'started_at' : (isset($colSet['start_time']) ? 'start_time' : (isset($colSet['created_at']) ? 'created_at' : null));
$colEnded     = isset($colSet['ended_at']) ? 'ended_at' : (isset($colSet['end_time']) ? 'end_time' : null);
$colDuration  = isset($colSet['duration']) ? 'duration' : (isset($colSet['duration_sec']) ? 'duration_sec' : null);
$colRecUrl    = isset($colSet['record_url']) ? 'record_url' : (isset($colSet['recording_url']) ? 'recording_url' : null);
$colPayload   = isset($colSet['payload']) ? 'payload' : (isset($colSet['raw']) ? 'raw' : (isset($colSet['meta']) ? 'meta' : null));
$colCreated   = isset($colSet['created_at']) ? 'created_at' : null;

/** Where builder */
$where = [];
$params = [];

if ($hasTable) {
  // q search
  if ($q !== '') {
    $ors = [];
    if ($colCaller) { $ors[] = "`{$colCaller}` LIKE ?"; $params[] = "%{$q}%"; }
    if ($colCallee) { $ors[] = "`{$colCallee}` LIKE ?"; $params[] = "%{$q}%"; }
    if (isset($colSet['call_id'])) { $ors[] = "`call_id` LIKE ?"; $params[] = "%{$q}%"; }
    if (isset($colSet['netgsm_call_id'])) { $ors[] = "`netgsm_call_id` LIKE ?"; $params[] = "%{$q}%"; }
    if (!empty($ors)) $where[] = '(' . implode(' OR ', $ors) . ')';
  }

  // status
  if ($status !== '' && $colStatus) {
    $where[] = "`{$colStatus}` = ?";
    $params[] = $status;
  }

  // direction
  if ($direction !== '' && $colDirection) {
    $where[] = "`{$colDirection}` = ?";
    $params[] = $direction;
  }

  // date range
  $dateCol = $colStarted ?: $colCreated;
  if ($dateCol) {
    if ($from !== '' && preg_match('/^\d{4}-\d{2}-\d{2}$/', $from)) {
      $where[] = "`{$dateCol}` >= ?";
      $params[] = $from . " 00:00:00";
    }
    if ($to !== '' && preg_match('/^\d{4}-\d{2}-\d{2}$/', $to)) {
      $where[] = "`{$dateCol}` <= ?";
      $params[] = $to . " 23:59:59";
    }
  }

  $whereSql = $where ? ("WHERE " . implode(" AND ", $where)) : "";

  // total
  try {
    $st = db()->prepare("SELECT COUNT(*) FROM `calls` {$whereSql}");
    $st->execute($params);
    $total = (int)$st->fetchColumn();
  } catch (Throwable $e) {
    $total = 0;
  }

  // rows
  try {
    $orderCol = $colStarted ?: $colCreated ?: ($colId ?: 'id');
    $sql = "SELECT * FROM `calls` {$whereSql} ORDER BY `{$orderCol}` DESC LIMIT {$perPage} OFFSET {$offset}";
    $st = db()->prepare($sql);
    $st->execute($params);
    $rows = $st->fetchAll() ?: [];
  } catch (Throwable $e) {
    $rows = [];
  }
}

$totalPages = max(1, (int)ceil(max(0, $total) / $perPage));

/** UI helpers */
function fmt_dt(?string $dt): string {
  if (!$dt) return '';
  $ts = strtotime($dt);
  if ($ts === false) return (string)$dt;
  return date('d.m.Y H:i', $ts);
}
function fmt_dur($dur): string {
  if ($dur === null || $dur === '') return '';
  $n = (int)$dur;
  if ($n <= 0) return '0 sn';
  $m = intdiv($n, 60);
  $s = $n % 60;
  if ($m <= 0) return $s . ' sn';
  return $m . ' dk ' . str_pad((string)$s, 2, '0', STR_PAD_LEFT) . ' sn';
}
function status_pill(string $s): array {
  $k = mb_strtolower(trim($s));
  if ($k === '') return ['class' => 'neutral', 'text' => 'Bilinmiyor'];
  if (str_contains($k, 'ok') || str_contains($k, 'success') || str_contains($k, 'answered') || str_contains($k, 'complete')) {
    return ['class' => 'green', 'text' => $s];
  }
  if (str_contains($k, 'miss') || str_contains($k, 'noanswer') || str_contains($k, 'failed') || str_contains($k, 'busy') || str_contains($k, 'reject')) {
    return ['class' => 'neutral', 'text' => $s];
  }
  if (str_contains($k, 'ring') || str_contains($k, 'inprogress') || str_contains($k, 'progress')) {
    return ['class' => 'neutral', 'text' => $s];
  }
  return ['class' => 'neutral', 'text' => $s];
}

function build_url(array $override = []): string {
  $q = $_GET;
  foreach ($override as $k => $v) {
    if ($v === null || $v === '') unset($q[$k]);
    else $q[$k] = $v;
  }
  $qs = http_build_query($q);
  return basename($_SERVER['PHP_SELF']) . ($qs ? ("?" . $qs) : "");
}

?>
<!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>Aramalar</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);
    }
    /* iOS input zoom engeli */
    input, select, button { font-size:16px; }

    .container { max-width:100%; padding:8px; }
    @media (min-width: 900px){
      .container{ max-width:980px; margin:0 auto; padding:16px; }
    }

    .header{
      display:flex; align-items:center; justify-content:space-between;
      padding:12px 0 8px 0; margin-bottom:12px; gap: 10px; flex-wrap:wrap;
    }
    .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-sub{ font-size:12px; font-weight:800; color:#666; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; max-width: 78vw; }
    .header-actions{ display:flex; align-items:center; gap:6px; flex-wrap:wrap; justify-content:flex-end; }

    .pillbtn{
      background:#f0f0f0; 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; color:black; font-weight:800;
      white-space: nowrap;
    }

    .filters{
      background:#f8f8f8;
      border-radius:14px;
      padding:12px;
      margin-bottom:10px;
    }
    .filters-grid{
      display:grid;
      grid-template-columns: 1fr;
      gap:8px;
    }
    @media (min-width: 900px){
      .filters-grid{
        grid-template-columns: 2fr 1fr 1fr 1fr 1fr;
        align-items:end;
      }
    }

    .field-label{
      font-size:12px;
      color:#666;
      font-weight:800;
      padding:0 2px 6px 2px;
    }
    .in{
      width:100%;
      padding:10px 14px;
      border:1px solid #e0e0e0;
      border-radius:20px;
      font-size:15px;
      background:#fff;
      font-family:'Nexa', sans-serif;
      outline:none;
    }
    .in:focus{ border-color:#d0d0d0; }
    .btn{
      padding:10px 14px; background:#f0f0f0; border:none; border-radius:20px;
      font-weight:900; cursor:pointer; font-family:'Nexa', sans-serif;
      font-size:14px; white-space:nowrap;
    }
    .btn.primary{ background:#111; color:#fff; }
    .btnrow{
      display:flex; gap:8px; justify-content:space-between; margin-top:10px; flex-wrap:wrap;
    }
    .link-reset{
      color:#666; font-weight:900; text-decoration:none; font-size:13px;
      display:inline-flex; align-items:center; gap:6px;
      padding:10px 12px; border-radius:20px; background:#f0f0f0;
    }

    .total-count{ font-size:12px; color:#666; margin-bottom:8px; font-weight:800; 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:flex-start; margin-bottom:8px; gap:10px;
    }
    .call-main{ min-width:0; }
    .call-title{ font-size:16px; font-weight:800; word-break:break-all; }
    .call-sub{
      margin-top:4px;
      font-size:12px; color:#666; font-weight:800;
      display:flex; flex-wrap:wrap; gap:10px;
    }
    .sub-pill{ display:inline-flex; gap:6px; align-items:center; }
    .dot{ width:6px; height:6px; border-radius:999px; background:#bbb; display:inline-block; }

    .status-pill{
      display:inline-block; padding:6px 12px; border-radius:999px;
      font-size:12px; font-weight:900; white-space:nowrap;
      background:#eeeeee; color:#444;
    }
    .status-pill.green{ background:#e8f5e9; color:#2e7d32; }
    .status-pill.neutral{ background:#eeeeee; color:#444; }

    .actions{
      display:flex; gap:6px; justify-content:flex-end; flex-wrap:wrap;
    }
    .mini{
      background:#e8e8e8; border:none; border-radius:12px;
      padding:8px 10px;
      font-size:12px;
      font-weight:900;
      font-family:'Nexa', sans-serif;
      cursor:pointer;
      text-decoration:none;
      color:#111;
      white-space:nowrap;
      display:inline-flex; align-items:center; gap:6px;
    }

    .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:8px;
      font-family:'Nexa', sans-serif; font-weight:900;
    }
    .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:800; min-width:110px; }
    .info-value{ font-weight:800; text-align:right; max-width:70%; word-break:break-all; }

    .payload{
      margin-top:10px;
      background:#fff;
      border:1px solid #e6e6e6;
      border-radius:10px;
      padding:10px;
      font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
      font-size:12px;
      line-height:1.45;
      white-space:pre-wrap;
      word-break:break-word;
      color:#222;
      max-height:240px;
      overflow:auto;
    }

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

    .pager{
      display:flex; justify-content:space-between; align-items:center;
      gap:10px; margin-top:10px; flex-wrap:wrap;
      padding: 8px 2px;
    }
    .pager .pinfo{ font-size:12px; color:#666; font-weight:900; }
    .pager a{
      background:#f0f0f0; border-radius:16px; padding:8px 12px;
      text-decoration:none; color:#111; font-weight:900; font-size:13px;
    }
    .pager a.disabled{ opacity:.45; pointer-events:none; }

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

    @media (max-width:480px){
      .container{ padding:6px; }
      .call-item{ padding:10px; margin-bottom:6px; }
      .call-title{ font-size:15px; }
      .in{ padding:9px 12px; font-size:14px; }
      .btn{ padding:9px 14px; font-size:13px; }
    }
  </style>
</head>
<body>
  <div class="container">

    <div class="header">
      <div class="header-left">
        <div class="header-title">Aramalar</div>
        <div class="header-sub">
          <?= $userEmail ? e($userEmail) : 'admin' ?>
          <?php if (!$hasTable): ?> • calls tablosu yok (0 gösteriliyor)<?php endif; ?>
        </div>
      </div>

      <div class="header-actions">
        <a href="dashboard.php" class="pillbtn">← Panel</a>
        <a href="logout.php" class="pillbtn">Çıkış</a>
      </div>
    </div>

    <div class="filters">
      <form method="get">
        <div class="filters-grid">
          <div>
            <div class="field-label">Ara</div>
            <input class="in" type="text" name="q" value="<?= e($q) ?>" placeholder="Numara / Call ID ..." />
          </div>

          <div>
            <div class="field-label">Durum</div>
            <select class="in" name="status">
              <option value="">Tümü</option>
              <option value="answered" <?= $status==='answered'?'selected':''; ?>>answered</option>
              <option value="missed"   <?= $status==='missed'?'selected':''; ?>>missed</option>
              <option value="failed"   <?= $status==='failed'?'selected':''; ?>>failed</option>
              <option value="busy"     <?= $status==='busy'?'selected':''; ?>>busy</option>
            </select>
          </div>

          <div>
            <div class="field-label">Yön</div>
            <select class="in" name="direction">
              <option value="">Tümü</option>
              <option value="inbound"  <?= $direction==='inbound'?'selected':''; ?>>inbound</option>
              <option value="outbound" <?= $direction==='outbound'?'selected':''; ?>>outbound</option>
            </select>
          </div>

          <div>
            <div class="field-label">Başlangıç</div>
            <input class="in" type="date" name="from" value="<?= e($from) ?>" />
          </div>

          <div>
            <div class="field-label">Bitiş</div>
            <input class="in" type="date" name="to" value="<?= e($to) ?>" />
          </div>
        </div>

        <div class="btnrow">
          <a class="link-reset" href="calls.php">Sıfırla</a>
          <button class="btn primary" type="submit">Filtrele</button>
        </div>
      </form>
    </div>

    <div class="total-count">
      Toplam <?= (int)$total ?> kayıt • Sayfa <?= (int)$page ?>/<?= (int)$totalPages ?>
    </div>

    <?php if (!$rows): ?>
      <div class="empty-state">
        <h3>Kayıt bulunamadı</h3>
        <p>Filtreleri değiştirerek tekrar deneyin.</p>
      </div>
    <?php else: ?>
      <?php foreach ($rows as $r): ?>
        <?php
          $caller = $colCaller ? (string)($r[$colCaller] ?? '') : '';
          $callee = $colCallee ? (string)($r[$colCallee] ?? '') : '';
          $stt    = $colStatus ? (string)($r[$colStatus] ?? '') : '';
          $dir    = $colDirection ? (string)($r[$colDirection] ?? '') : '';
          $dt0    = $colStarted ? (string)($r[$colStarted] ?? '') : ($colCreated ? (string)($r[$colCreated] ?? '') : '');
          $dt1    = $colEnded ? (string)($r[$colEnded] ?? '') : '';
          $dur    = $colDuration ? (string)($r[$colDuration] ?? '') : '';
          $rec    = $colRecUrl ? (string)($r[$colRecUrl] ?? '') : '';
          $payload= $colPayload ? (string)($r[$colPayload] ?? '') : '';

          $idForUi = '';
          if ($colId) $idForUi = (string)($r[$colId] ?? '');
          else $idForUi = (string)($r['id'] ?? '');

          $pill = status_pill($stt);
        ?>

        <div class="call-item">
          <div class="call-header">
            <div class="call-main">
              <div class="call-title">
                <?= e($caller ?: '—') ?> <span style="color:#bbb; font-weight:900;">→</span> <?= e($callee ?: '—') ?>
              </div>

              <div class="call-sub">
                <?php if ($idForUi !== ''): ?>
                  <span class="sub-pill"><span class="dot"></span>ID: <?= e($idForUi) ?></span>
                <?php endif; ?>
                <?php if ($dir !== ''): ?>
                  <span class="sub-pill"><span class="dot"></span>Yön: <?= e($dir) ?></span>
                <?php endif; ?>
                <?php if ($dt0 !== ''): ?>
                  <span class="sub-pill"><span class="dot"></span><?= e(fmt_dt($dt0)) ?></span>
                <?php endif; ?>
                <?php if ($dur !== ''): ?>
                  <span class="sub-pill"><span class="dot"></span><?= e(fmt_dur($dur)) ?></span>
                <?php endif; ?>
              </div>
            </div>

            <div class="actions">
              <span class="status-pill <?= e($pill['class']) ?>"><?= e($pill['text']) ?></span>
              <?php if ($rec !== ''): ?>
                <a class="mini" href="<?= e($rec) ?>" target="_blank" rel="noopener">Dinle</a>
              <?php endif; ?>
            </div>
          </div>

          <button class="dropdown-btn" type="button" onclick="toggleDropdown(this)">
            <span class="btn-text">Detayları Göster</span>
            <span class="arrow">▼</span>
          </button>

          <div class="dropdown-content">
            <div class="info-row">
              <span class="info-label">Arayan</span>
              <span class="info-value"><?= e($caller ?: '-') ?></span>
            </div>
            <div class="info-row">
              <span class="info-label">Aranan</span>
              <span class="info-value"><?= e($callee ?: '-') ?></span>
            </div>
            <?php if ($dir !== ''): ?>
              <div class="info-row">
                <span class="info-label">Yön</span>
                <span class="info-value"><?= e($dir) ?></span>
              </div>
            <?php endif; ?>
            <?php if ($stt !== ''): ?>
              <div class="info-row">
                <span class="info-label">Durum</span>
                <span class="info-value"><?= e($stt) ?></span>
              </div>
            <?php endif; ?>
            <?php if ($dt0 !== ''): ?>
              <div class="info-row">
                <span class="info-label">Başlangıç</span>
                <span class="info-value"><?= e(fmt_dt($dt0)) ?></span>
              </div>
            <?php endif; ?>
            <?php if ($dt1 !== ''): ?>
              <div class="info-row">
                <span class="info-label">Bitiş</span>
                <span class="info-value"><?= e(fmt_dt($dt1)) ?></span>
              </div>
            <?php endif; ?>
            <?php if ($dur !== ''): ?>
              <div class="info-row">
                <span class="info-label">Süre</span>
                <span class="info-value"><?= e(fmt_dur($dur)) ?></span>
              </div>
            <?php endif; ?>
            <?php if ($rec !== ''): ?>
              <div class="info-row">
                <span class="info-label">Kayıt</span>
                <span class="info-value"><a href="<?= e($rec) ?>" target="_blank" rel="noopener">Aç</a></span>
              </div>
            <?php endif; ?>

            <?php if ($payload !== ''): ?>
              <div style="height:10px"></div>
              <div class="info-row" style="border-bottom:none; padding-bottom:0;">
                <span class="info-label">Payload</span>
                <span class="info-value">
                  <button class="mini" type="button" onclick="copyPayload(this)">Kopyala</button>
                </span>
              </div>
              <pre class="payload" data-payload="1"><?=
                // JSON ise prettify dene
                (function(string $raw): string {
                  $t = trim($raw);
                  if (($t !== '') && (($t[0] === '{' && substr($t, -1) === '}') || ($t[0] === '[' && substr($t, -1) === ']'))) {
                    $j = json_decode($t, true);
                    if (json_last_error() === JSON_ERROR_NONE) {
                      return json_encode($j, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
                    }
                  }
                  return $raw;
                })($payload)
              ?></pre>
            <?php endif; ?>
          </div>
        </div>
      <?php endforeach; ?>

      <div class="pager">
        <div class="pinfo">Sayfa <?= (int)$page ?> / <?= (int)$totalPages ?></div>
        <div style="display:flex; gap:8px; flex-wrap:wrap;">
          <a class="<?= $page<=1 ? 'disabled' : '' ?>" href="<?= e(build_url(['page' => max(1, $page-1)])) ?>">← Önceki</a>
          <a class="<?= $page>=$totalPages ? 'disabled' : '' ?>" href="<?= e(build_url(['page' => min($totalPages, $page+1)])) ?>">Sonraki →</a>
        </div>
      </div>
    <?php endif; ?>

    <div class="footer">
      © <?= date('Y') ?> • NETGSM Santral MVP
    </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 = "Detayları 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 = "Detayları Göster";
          }
        });

        dropdown.classList.add('show');
        arrow.textContent = '▲';
        txt.textContent = "Detayları Gizle";
      }
    }

    document.addEventListener('DOMContentLoaded', function() {
      document.querySelectorAll('.dropdown-content').forEach(item => item.classList.remove('show'));
    });

    function copyPayload(btn){
      const box = btn.closest('.dropdown-content');
      if (!box) return;
      const pre = box.querySelector('pre[data-payload="1"]');
      if (!pre) return;

      const txt = pre.innerText || '';
      navigator.clipboard.writeText(txt).then(() => {
        const old = btn.textContent;
        btn.textContent = 'Kopyalandı';
        setTimeout(() => btn.textContent = old, 900);
      }).catch(() => {
        alert('Kopyalama başarısız.');
      });
    }
  </script>
</body>
</html>
