<?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'] ?? ''));

/**
 * webhook_logs tablosundan çek:
 * - arayan_no sadece 1 kere görünsün (unique)
 * - üstte SADECE "Onaylı / Onaysız" yazsın (tus rakamı yazmasın)
 *   * 1 => Onaylı (yeşil)
 *   * 2 => Onaysız (kırmızı)
 * - dropdown içinde aynı arayan_no'ya ait arama_id'ler listelensin
 */

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

  // latest tus_bilgisi: en güncel event'te doluysa o, değilse ilk dolu olan
  $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'] ?? ''),
  ];
}

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

function tus_label(string $tus): array {
  // 1 => Onaylı (yeşil), 2 => Onaysız (kırmızı)
  if (consent_is_approved_digit($tus)) return ['class' => 'onay', 'text' => 'Onaylı'];
  if (consent_is_rejected_digit($tus)) return ['class' => 'onaysiz', 'text' => 'Onaysız'];
  return ['class' => 'neutral', 'text' => 'Bilinmiyor'];
}
?>
<!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>Tuşlamalar</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;
    }
    .header-title{ font-size:18px; font-weight:700; }

    .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:600;
    }

    .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:600; 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:600; 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:700; 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:800;
    }
    .status-pill.onay{ background:#e8f5e9; color:#2e7d32; }
    .status-pill.onaysiz{ background:#ffebee; color:#c62828; }
    .status-pill.neutral{ background:#eeeeee; color:#444; }

    .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:600;
    }
    .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:600; min-width:90px; }
    .info-value{ font-weight:700; 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:800; font-size:13px; word-break:break-all; }
    .event-badge{
      display:inline-flex; align-items:center;
      font-size:12px; font-weight:800; padding:3px 10px; border-radius:999px; white-space:nowrap;
    }
    .event-badge.onay{ background:#e8f5e9; color:#2e7d32; }
    .event-badge.onaysiz{ background:#ffebee; color:#c62828; }
    .event-badge.neutral{ background:#eeeeee; color:#444; }

    .event-meta{
      display:flex; justify-content:space-between; gap:10px; font-size:12px; color:#666; font-weight:700;
    }

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

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

    @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; }
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="header">
      <div class="header-title">Tuşlamalar</div>
      <a href="dashboard.php" class="back-btn">← Panel</a>
    </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ı arayan</div>
    <?php endif; ?>

    <?php if (!$unique_rows): ?>
      <div class="empty-state">
        <h3>Henüz tuşlama yok</h3>
        <p>Webhook loglarına kayıt geldikçe burada listelenecek.</p>
      </div>
    <?php else: ?>
      <?php foreach ($unique_rows as $g):
        $arayanNo = (string)$g['arayan_no'];
        $latestTus = (string)($g['latest']['tus_bilgisi'] ?? '');
        $latest = tus_label($latestTus);
      ?>
        <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 <?= htmlspecialchars($latest['class'], ENT_QUOTES, 'UTF-8') ?>">
                <?= htmlspecialchars($latest['text'], ENT_QUOTES, 'UTF-8') ?>
              </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">arayan_no</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):
                $lab = tus_label((string)$ev['tus_bilgisi']);
                $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 <?= htmlspecialchars($lab['class'], ENT_QUOTES, 'UTF-8') ?>">
                      <?= htmlspecialchars($lab['text'], ENT_QUOTES, 'UTF-8') ?>
                    </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>

  <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'));
    });
  </script>
</body>
</html>
