<?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;
}

$logoUrl = 'https://ivr.wanyweb.com/assets/logo/wany21.png';
$heroImageUrl = 'https://ivr.wanyweb.com/assets/logo/ivrla.png';
$preloaderLogoUrl = 'https://ivr.wanyweb.com/admin/wanyer.png';

function safe_count(string $table): int {
  try {
    $pdo = db();
    $st = $pdo->query("SELECT COUNT(*) AS c FROM `{$table}`");
    return (int)($st ? $st->fetchColumn() : 0);
  } catch (Throwable $e) {
    return 0;
  }
}

function webhook_consent_stats(): array
{
  static $cache = null;
  if (is_array($cache)) return $cache;

  $stats = [
    'digits' => 0,
    'onayli' => 0,
    'onaysiz' => 0,
  ];

  try {
    $pdo = db();
    $st = $pdo->query("
      SELECT raw_body
      FROM webhook_logs
      WHERE raw_body IS NOT NULL
        AND raw_body <> ''
      ORDER BY id DESC
    ");
    $rows = $st ? ($st->fetchAll() ?: []) : [];

    $history = []; // [arayan_no => ['approved'=>bool, 'rejected'=>bool]]

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

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

      $arayan = payload_pick($payload, ['arayan_no', 'arayan', 'caller', 'from', 'msisdn']);
      $tus = payload_pick($payload, ['tus_bilgisi', 'digit']);

      if ($tus !== '') $stats['digits']++;
      if ($arayan === '' || $tus === '') continue;

      if (!isset($history[$arayan])) {
        $history[$arayan] = ['approved' => false, 'rejected' => false];
      }

      if (consent_is_approved_digit($tus)) {
        $history[$arayan]['approved'] = true;
      } elseif (consent_is_rejected_digit($tus)) {
        $history[$arayan]['rejected'] = true;
      }
    }

    foreach ($history as $h) {
      if (!empty($h['approved'])) {
        $stats['onayli']++;
      } elseif (!empty($h['rejected'])) {
        $stats['onaysiz']++;
      }
    }
  } catch (Throwable $e) {
    // no-op
  }

  $cache = $stats;
  return $cache;
}

function count_webhook_tuslamalar(): int
{
  $stats = webhook_consent_stats();
  return (int)($stats['digits'] ?? 0);
}

function count_latest_webhook_decision(string $wantTus): int
{
  $stats = webhook_consent_stats();
  if (consent_is_approved_digit($wantTus)) return (int)($stats['onayli'] ?? 0);
  if (consent_is_rejected_digit($wantTus)) return (int)($stats['onaysiz'] ?? 0);
  return 0;
}

$cntCalls    = safe_count('calls');
$cntDigitsTb = safe_count('ivr_digits');
$cntDigitsWh = count_webhook_tuslamalar();
$cntDigits   = max($cntDigitsTb, $cntDigitsWh);

$cntOnayli  = count_latest_webhook_decision(consent_digit_approved());
$cntOnaysiz = count_latest_webhook_decision(consent_digit_rejected());

$cntUsers    = safe_count('users');
$cntMailLogs = safe_count('consent_email_logs');

$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) {}
?>
<!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>NETGSM Santral • Dashboard</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: #ffffff;
      color: #000;
      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);
    }

    .preloader{
      position: fixed;
      inset: 0;
      background: #fff;
      display:flex;
      align-items:center;
      justify-content:center;
      z-index: 99999;
      transition: opacity .22s ease, visibility .22s ease;
    }
    .preloader.hide{
      opacity:0;
      visibility:hidden;
      pointer-events:none;
    }
    .preloader-inner{
      display:flex;
      flex-direction:column;
      align-items:center;
      justify-content:center;
      gap: 14px;
      padding: 16px;
      text-align:center;
    }

    .preloader-logo{
      width: 330px;
      max-width: 78vw;
      height:auto;
      object-fit: contain;
      border-radius: 18px;
    }
    .preloader-ph{
      width: 330px;
      height: 330px;
      max-width: 78vw;
      max-height: 78vw;
      border-radius: 18px;
      background:#f3f3f3;
    }

    .loading-line{
      display:inline-flex;
      align-items:flex-end;
      justify-content:center;
      gap: 10px;
      font-weight: 900;
      font-size: 14px;
      color: #111;
      letter-spacing: -0.1px;
    }
    .dots{
      display:inline-flex;
      align-items:flex-end;
      gap: 6px;
      transform: translateY(-1px);
    }
    .dot{
      width: 7px;
      height: 7px;
      border-radius: 999px;
      background: #111;
      opacity: .25;
      animation: dotPulse 1s ease-in-out infinite;
    }
    .dot:nth-child(2){ animation-delay: .16s; }
    .dot:nth-child(3){ animation-delay: .32s; }

    @keyframes dotPulse{
      0%, 100% { transform: translateY(0); opacity: .25; }
      50% { transform: translateY(-6px); opacity: .9; }
    }

    .page{ opacity:0; }
    .page.ready{ opacity:1; transition: opacity .18s ease; }

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

    .header{
      display:flex;
      align-items:flex-start;
      justify-content:space-between;
      gap:10px;
      padding:10px 0 8px 0;
      margin-bottom:12px;
      flex-wrap:wrap;
    }
    .left-head{
      display:flex;
      align-items:center;
      gap:10px;
      min-width:0;
      flex: 1 1 260px;
    }
    .logo{
      height:34px;
      width:auto;
      object-fit:contain;
      border-radius:10px;
      flex-shrink:0;
    }
    .header-title{
      display:flex;
      flex-direction:column;
      gap:2px;
      min-width:0;
    }
    .header-title .t1{ font-size:18px; font-weight:800; letter-spacing:-0.2px; }
    .header-title .t2{
      font-size:12px;
      color:#666;
      font-weight:700;
      white-space:nowrap;
      overflow:hidden;
      text-overflow:ellipsis;
      max-width: 62vw;
    }

    .right-head{
      display:flex;
      align-items:center;
      gap:8px;
      flex-wrap:wrap;
      justify-content:flex-end;
      flex: 0 1 auto;
    }
    @media (max-width:520px){
      .right-head{ width:100%; justify-content:flex-start; }
      .header-title .t2{ max-width:85vw; }
    }

    .pill{
      background:#f0f0f0;
      border:none;
      padding:8px 12px;
      border-radius:999px;
      font-size:13px;
      font-family:'Nexa', sans-serif;
      cursor:pointer;
      text-decoration:none;
      color:#000;
      font-weight:800;
      display:inline-flex;
      align-items:center;
      gap:6px;
      white-space:nowrap;
    }
    .pill.online{ background:#e8f5e9; color:#2e7d32; }
    .dot-green{ width:9px; height:9px; border-radius:999px; background:#2e7d32; display:inline-block; }

    .hero-wrap{
      margin: 0 0 12px 0;
      border-radius: 16px;
      overflow: hidden;
      background:#f8f8f8;
    }
    .hero-img{
      display:block;
      width:100%;
      height:auto;
      max-height: 260px;
      object-fit: cover;
    }
    .hero-placeholder{
      width:100%;
      height: 160px;
      display:flex;
      align-items:center;
      justify-content:center;
      gap:8px;
      color:#666;
      font-weight:800;
      font-size:13px;
      background: repeating-linear-gradient(
        45deg,
        #f7f7f7,
        #f7f7f7 10px,
        #f1f1f1 10px,
        #f1f1f1 20px
      );
    }
    @media (min-width:900px){
      .hero-img{ max-height: 320px; }
      .hero-placeholder{ height: 200px; }
    }

    .grid{
      display:grid;
      grid-template-columns: repeat(2, minmax(0, 1fr));
      gap:10px;
    }
    @media (max-width:380px){
      .grid{ grid-template-columns: 1fr; }
    }
    @media (min-width:900px){
      .grid{ grid-template-columns: repeat(3, minmax(0, 1fr)); gap:12px; }
    }

    .card{
      background:#f8f8f8;
      border-radius:14px;
      padding:12px;
      text-decoration:none;
      color:inherit;
      display:block;
      transition: transform .12s ease, background .12s ease;
    }
    .card:hover{ background:#f3f3f3; }
    .card:active{ transform: scale(.99); }

    .card.green { background:#e8f5e9; }
    .card.green:hover { background:#dff1e2; }

    .card.red { background:#ffebee; }
    .card.red:hover { background:#ffe2e6; }

    .card-top{
      display:flex;
      align-items:flex-start;
      justify-content:space-between;
      gap:12px;
      margin-bottom:10px;
    }
    .card-title{ font-size:14px; font-weight:800; color:#111; }
    .card-sub{
      font-size:12px;
      font-weight:700;
      color:#666;
      margin-top:3px;
      line-height:1.25;
    }
    .card.green .card-sub{ color:#2e7d32; }
    .card.red .card-sub{ color:#c62828; }

    .card-num{
      font-size:28px;
      font-weight:800;
      letter-spacing:-0.5px;
      color:#000;
      line-height:1;
      text-align:right;
      min-width:56px;
      flex-shrink:0;
    }

    .card-go{
      width:100%;
      padding:10px;
      background:#e8e8e8;
      border-radius:10px;
      font-size:13px;
      color:#444;
      display:flex;
      align-items:center;
      justify-content:center;
      gap:6px;
      font-weight:800;
    }
    .card.green .card-go{ background:#d4edd9; color:#2e7d32; }
    .card.red .card-go{ background:#ffd6dd; color:#c62828; }

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

    @media (prefers-reduced-motion: reduce){
      .dot{ animation: none !important; }
      .preloader, .page{ transition: none !important; }
    }
  </style>
</head>
<body>
  <div class="preloader" id="preloader" aria-live="polite" aria-busy="true">
    <div class="preloader-inner">
      <?php if (!empty($preloaderLogoUrl)): ?>
        <img class="preloader-logo" src="<?= e($preloaderLogoUrl) ?>" alt="Yükleniyor">
      <?php else: ?>
        <div class="preloader-ph"></div>
      <?php endif; ?>

      <div class="loading-line">
        <span>Yükleniyor</span>
        <span class="dots" aria-hidden="true">
          <span class="dot"></span>
          <span class="dot"></span>
          <span class="dot"></span>
        </span>
      </div>
    </div>
  </div>

  <div class="page" id="pageRoot">
    <div class="container">
      <div class="header">
        <div class="left-head">
          <?php if ($logoUrl): ?>
            <img src="<?= e($logoUrl) ?>" alt="Logo" class="logo">
          <?php endif; ?>
          <div class="header-title">
            <div class="t1">Dashboard</div>
            <div class="t2"><?= $userEmail ? e($userEmail) : 'admin' ?></div>
          </div>
        </div>

        <div class="right-head">
          <span class="pill online"><span class="dot-green"></span> API Online</span>
          <a class="pill" href="settings.php">Ayarlar</a>
          <a class="pill" href="logout.php">Çıkış</a>
        </div>
      </div>

      <div class="hero-wrap">
        <?php if (!empty($heroImageUrl)): ?>
          <img src="<?= e($heroImageUrl) ?>" alt="Banner" class="hero-img">
        <?php else: ?>
          <div class="hero-placeholder">Görsel URL giriniz (heroImageUrl)</div>
        <?php endif; ?>
      </div>

      <div class="grid">
        <a href="calls.php" class="card">
          <div class="card-top">
            <div>
              <div class="card-title">Aramalar</div>
              <div class="card-sub">Toplam arama kaydı</div>
            </div>
            <div class="card-num"><?= (int)$cntCalls ?></div>
          </div>
          <div class="card-go">Detaya Git →</div>
        </a>

        <a href="ivr-digits.php" class="card">
          <div class="card-top">
            <div>
              <div class="card-title">Tuşlamalar</div>
              <div class="card-sub">IVR / Webhook tuş kayıtları</div>
            </div>
            <div class="card-num"><?= (int)$cntDigits ?></div>
          </div>
          <div class="card-go">IVR Tuşlamalari -></div>
        </a>

        <a href="onaylar.php" class="card green">
          <div class="card-top">
            <div>
              <div class="card-title">Onaylı</div>
              <div class="card-sub">Onay veren aramalar</div>
            </div>
            <div class="card-num"><?= (int)$cntOnayli ?></div>
          </div>
          <div class="card-go">Onaylılari Ac -></div>
        </a>

        <a href="onaysiz.php" class="card red">
          <div class="card-top">
            <div>
              <div class="card-title">Onaysız</div>
              <div class="card-sub">Onay vermeyen aramalar</div>
            </div>
            <div class="card-num"><?= (int)$cntOnaysiz ?></div>
          </div>
          <div class="card-go">Onaysızlari Ac -></div>
        </a>

        <a href="users.php" class="card">
          <div class="card-top">
            <div>
              <div class="card-title">Kullanıcılar</div>
              <div class="card-sub">Panel kullanıcıları</div>
            </div>
            <div class="card-num"><?= (int)$cntUsers ?></div>
          </div>
          <div class="card-go">Detaya Git →</div>
        </a>

        <a href="email-logs.php" class="card">
          <div class="card-top">
            <div>
              <div class="card-title">Mail Logları</div>
              <div class="card-sub">Gönderilen raporlar</div>
            </div>
            <div class="card-num"><?= (int)$cntMailLogs ?></div>
          </div>
          <div class="card-go">Detaya Git →</div>
        </a>

        <a href="sms-send.php" class="card green">
          <div class="card-top">
            <div>
              <div class="card-title">SMS Gönder</div>
              <div class="card-sub">Onaylılara SMS gonder</div>
            </div>
            <div class="card-num"><?= (int)$cntOnayli ?></div>
          </div>
          <div class="card-go">Onaylılara SMS Gönder -></div>
        </a>

        <a href="consent-csv.php" class="card">
          <div class="card-top">
            <div>
              <div class="card-title">CSV Log</div>
              <div class="card-sub">Tarih araligi ile CSV indir / mail</div>
            </div>
            <div class="card-num"><?= (int)$cntDigits ?></div>
          </div>
          <div class="card-go">CSV Raporu -></div>
        </a>

        <a href="dashboard.php" class="card">
          <div class="card-top">
            <div>
              <div class="card-title">Sistem</div>
              <div class="card-sub">CSRF • Session • Log</div>
            </div>
            <div class="card-num">OK</div>
          </div>
          <div class="card-go">Yenile ↻</div>
        </a>
      </div>

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

  <script>
    (function () {
      const pre = document.getElementById('preloader');
      const page = document.getElementById('pageRoot');

      function hide() {
        if (!pre) return;
        pre.classList.add('hide');
        if (page) page.classList.add('ready');
        setTimeout(() => { try { pre.remove(); } catch(e) {} }, 260);
      }

      const showForMs = 3000;
      const safetyMax = 9000;
      const t0 = Date.now();
      let loaded = false;

      function tryHide() {
        const elapsed = Date.now() - t0;
        const left = Math.max(0, showForMs - elapsed);
        setTimeout(hide, left);
      }

      window.addEventListener('load', () => {
        loaded = true;
        tryHide();
      });

      setTimeout(() => {
        if (!loaded) hide();
      }, showForMs);

      setTimeout(hide, safetyMax);
    })();
  </script>
</body>
</html>
