<?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/mail_settings.php';

start_app_session();

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

$pdo = db();
ensure_mail_settings_table($pdo);

$cfg = app_config();
$baseMail = mail_normalize_config(mail_settings_from_files($cfg));
$settingsRow = mail_fetch_settings_row($pdo);

if (!$settingsRow) {
  $seed = [
    'enabled' => $baseMail['enabled'] ? 1 : 0,
    'host' => $baseMail['host'],
    'port' => $baseMail['port'],
    'secure' => $baseMail['secure'],
    'username' => $baseMail['username'],
    'password' => $baseMail['password'],
    'from_email' => $baseMail['from_email'],
    'from_name' => $baseMail['from_name'],
    'to_emails' => implode(', ', $baseMail['to']),
    'subject_prefix' => $baseMail['subject_prefix'],
  ];
  mail_save_settings($pdo, $seed);
  $settingsRow = mail_fetch_settings_row($pdo);
}

$settingsMsg = '';
$settingsErr = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && (string)($_POST['action'] ?? '') === 'save_mail_settings') {
  csrf_verify();
  $existing = $settingsRow ?: mail_fetch_settings_row($pdo);

  $secure = strtolower(trim((string)($_POST['secure'] ?? 'ssl')));
  if (!in_array($secure, ['ssl','tls','none'], true)) {
    $secure = 'ssl';
  }

  $password = trim((string)($_POST['password'] ?? ''));
  if ($password === '' && $existing && (string)($existing['password'] ?? '') !== '') {
    $password = (string)$existing['password'];
  }

  $input = [
    'enabled' => !empty($_POST['enabled']) ? 1 : 0,
    'host' => trim((string)($_POST['host'] ?? '')),
    'port' => (int)($_POST['port'] ?? 0),
    'secure' => $secure,
    'username' => trim((string)($_POST['username'] ?? '')),
    'password' => $password,
    'from_email' => trim((string)($_POST['from_email'] ?? '')),
    'from_name' => trim((string)($_POST['from_name'] ?? '')),
    'to_emails' => trim((string)($_POST['to_emails'] ?? '')),
    'subject_prefix' => trim((string)($_POST['subject_prefix'] ?? '')),
  ];

  $missing = [];
  if ($input['enabled']) {
    if ($input['host'] === '') $missing[] = 'host';
    if ($input['port'] <= 0) $missing[] = 'port';
    if ($input['username'] === '') $missing[] = 'username';
    if ($input['password'] === '') $missing[] = 'password';
    if ($input['from_email'] === '') $missing[] = 'from_email';
    if ($input['to_emails'] === '') $missing[] = 'to_emails';
  }

  if ($missing) {
    $settingsErr = 'Zorunlu alanlar bos: ' . implode(', ', $missing);
  } else {
    mail_save_settings($pdo, $input);
    $settingsRow = mail_fetch_settings_row($pdo);
    $settingsMsg = 'Mail ayarlari guncellendi.';
  }
}

$settingsRow = $settingsRow ?: [];
$setEnabled = ((int)($settingsRow['enabled'] ?? ($baseMail['enabled'] ? 1 : 0)) === 1);
$setHost = (string)($settingsRow['host'] ?? $baseMail['host']);
$setPort = (int)($settingsRow['port'] ?? $baseMail['port']);
$setSecure = (string)($settingsRow['secure'] ?? $baseMail['secure']);
$setUsername = (string)($settingsRow['username'] ?? $baseMail['username']);
$setPassword = (string)($settingsRow['password'] ?? $baseMail['password']);
$setFromEmail = (string)($settingsRow['from_email'] ?? $baseMail['from_email']);
$setFromName = (string)($settingsRow['from_name'] ?? $baseMail['from_name']);
$setToEmails = (string)($settingsRow['to_emails'] ?? implode(', ', $baseMail['to']));
$setSubjectPrefix = (string)($settingsRow['subject_prefix'] ?? $baseMail['subject_prefix']);

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

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

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

$rows = [];
$total = 0;
$hasTable = table_exists('consent_email_logs');

if ($hasTable) {
  $where = [];
  $params = [];

  if ($q !== '') {
    $where[] = '(subject LIKE ? OR from_email LIKE ? OR to_emails LIKE ?)';
    $like = "%{$q}%";
    array_push($params, $like, $like, $like);
  }
  if ($status !== '') {
    $where[] = 'status = ?';
    $params[] = $status;
  }
  if ($from !== '' && preg_match('/^\d{4}-\d{2}-\d{2}$/', $from)) {
    $where[] = 'sent_at >= ?';
    $params[] = $from . ' 00:00:00';
  }
  if ($to !== '' && preg_match('/^\d{4}-\d{2}-\d{2}$/', $to)) {
    $where[] = 'sent_at <= ?';
    $params[] = $to . ' 23:59:59';
  }

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

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

  try {
    $sql = "SELECT * FROM consent_email_logs {$whereSql} ORDER BY sent_at DESC, id 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));

function status_badge(string $s): array {
  $k = strtolower(trim($s));
  if ($k === 'sent') return ['class' => 'green', 'text' => 'Gonderildi'];
  if ($k === 'failed') return ['class' => 'red', 'text' => 'Hata'];
  if ($k === 'skipped') return ['class' => 'neutral', 'text' => 'Atlandi'];
  return ['class' => 'neutral', 'text' => ($s !== '' ? $s : 'Bilinmiyor')];
}

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) : "");
}

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 parse_json_list(?string $json): array {
  if (!$json) return [];
  $j = json_decode($json, true);
  if (is_array($j)) return $j;
  return [];
}
?>
<!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>Mail Loglari</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; }
    @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-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;
    }

    .settings-card{
      background:#f8f8f8;
      border-radius:14px;
      padding:12px;
      margin-bottom:10px;
    }
    .settings-title{ font-size:15px; font-weight:900; margin-bottom:8px; }
    .settings-grid{ display:grid; grid-template-columns:1fr; gap:8px; }
    .field{ display:flex; flex-direction:column; gap:6px; }
    .notice{ padding:8px 10px; border-radius:10px; font-size:12px; font-weight:900; margin-bottom:8px; }
    .notice.ok{ background:#e8f5e9; color:#2e7d32; }
    .notice.err{ background:#ffebee; color:#c62828; }

    .chk{ width:auto; height:18px; }
    @media (min-width: 900px){
      .settings-grid{ grid-template-columns: 1fr 1fr; }
      .settings-grid .full{ grid-column: 1 / -1; }
    }

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

    .log-item{ background:#f8f8f8; border-radius:14px; padding:12px; margin-bottom:8px; }
    .log-header{ display:flex; justify-content:space-between; align-items:flex-start; margin-bottom:8px; gap:10px; }
    .log-title{ font-size:15px; font-weight:800; word-break:break-word; }
    .log-sub{ font-size:12px; color:#666; font-weight:800; margin-top:4px; }

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

    .meta{ display:flex; flex-wrap:wrap; gap:10px; font-size:12px; font-weight:800; color:#666; }

    .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-word; }

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

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

    .footer{ text-align:center; padding:16px 0; color:#999; font-size:12px; margin-top:16px; font-weight:800; }
  </style>
</head>
<body>
  <div class="container">
    <div class="header">
      <div class="header-left">
        <div class="header-title">Mail Loglari</div>
        <?php if (!$hasTable): ?>
          <div class="log-sub">consent_email_logs tablosu yok</div>
        <?php endif; ?>
      </div>
      <div class="header-actions">
        <a href="dashboard.php" class="pillbtn">← Panel</a>
        <a href="logout.php" class="pillbtn">Cikis</a>
      </div>
    </div>

    <div class="settings-card">
      <div class="settings-title">Mail Ayarlari</div>
      <?php if ($settingsMsg !== ''): ?>
        <div class="notice ok"><?= e($settingsMsg) ?></div>
      <?php endif; ?>
      <?php if ($settingsErr !== ''): ?>
        <div class="notice err"><?= e($settingsErr) ?></div>
      <?php endif; ?>
      <form method="post">
        <input type="hidden" name="action" value="save_mail_settings" />
        <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>" />
        <div class="settings-grid">
          <label class="field">
            <span class="field-label">Aktif</span>
            <input class="chk" type="checkbox" name="enabled" value="1" <?= $setEnabled ? 'checked' : '' ?> />
          </label>
          <label class="field">
            <span class="field-label">SMTP Host</span>
            <input class="in" type="text" name="host" value="<?= e($setHost) ?>" />
          </label>
          <label class="field">
            <span class="field-label">SMTP Port</span>
            <input class="in" type="number" name="port" value="<?= (int)$setPort ?>" />
          </label>
          <label class="field">
            <span class="field-label">Guvenlik</span>
            <select class="in" name="secure">
              <option value="ssl" <?= $setSecure==='ssl'?'selected':''; ?>>ssl</option>
              <option value="tls" <?= $setSecure==='tls'?'selected':''; ?>>tls</option>
              <option value="none" <?= $setSecure==='none'?'selected':''; ?>>none</option>
            </select>
          </label>
          <label class="field">
            <span class="field-label">SMTP Kullanici</span>
            <input class="in" type="text" name="username" value="<?= e($setUsername) ?>" />
          </label>
          <label class="field">
            <span class="field-label">SMTP Sifre</span>
            <input class="in" type="password" name="password" value="<?= e($setPassword) ?>" />
          </label>
          <label class="field">
            <span class="field-label">Gonderen Email</span>
            <input class="in" type="email" name="from_email" value="<?= e($setFromEmail) ?>" />
          </label>
          <label class="field">
            <span class="field-label">Gonderen Ismi</span>
            <input class="in" type="text" name="from_name" value="<?= e($setFromName) ?>" />
          </label>
          <label class="field full">
            <span class="field-label">Alicilar (virgul veya yeni satir)</span>
            <textarea class="in" name="to_emails" rows="2"><?= e($setToEmails) ?></textarea>
          </label>
          <label class="field full">
            <span class="field-label">Konu On Eki</span>
            <input class="in" type="text" name="subject_prefix" value="<?= e($setSubjectPrefix) ?>" />
          </label>
        </div>
        <div class="btnrow">
          <button class="btn primary" type="submit">Kaydet</button>
        </div>
      </form>
    </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="Konu / Gonderen / Alici..." />
          </div>
          <div>
            <div class="field-label">Durum</div>
            <select class="in" name="status">
              <option value="">Tumu</option>
              <option value="sent" <?= $status==='sent'?'selected':''; ?>>sent</option>
              <option value="failed" <?= $status==='failed'?'selected':''; ?>>failed</option>
              <option value="skipped" <?= $status==='skipped'?'selected':''; ?>>skipped</option>
            </select>
          </div>
          <div>
            <div class="field-label">Baslangic</div>
            <input class="in" type="date" name="from" value="<?= e($from) ?>" />
          </div>
          <div>
            <div class="field-label">Bitis</div>
            <input class="in" type="date" name="to" value="<?= e($to) ?>" />
          </div>
        </div>
        <div class="btnrow">
          <a class="link-reset" href="email-logs.php">Sifirla</a>
          <button class="btn primary" type="submit">Filtrele</button>
        </div>
      </form>
    </div>

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

    <?php if (!$rows): ?>
      <div class="empty-state">
        <h3>Kayit bulunamadi</h3>
        <p>Filtreleri degistirerek tekrar deneyin.</p>
      </div>
    <?php else: ?>
      <?php foreach ($rows as $r): ?>
        <?php
          $badge = status_badge((string)($r['status'] ?? ''));
          $toList = parse_json_list((string)($r['to_emails'] ?? ''));
          $toText = $toList ? implode(', ', $toList) : (string)($r['to_emails'] ?? '');
          $attList = parse_json_list((string)($r['attachments'] ?? ''));
          $attText = $attList ? implode(', ', $attList) : (string)($r['attachments'] ?? '');
        ?>
        <div class="log-item">
          <div class="log-header">
            <div>
              <div class="log-title"><?= e((string)($r['subject'] ?? '')) ?></div>
              <div class="log-sub"><?= e(fmt_dt((string)($r['sent_at'] ?? ''))) ?></div>
              <div class="meta">
                <span>Onayli: <?= (int)($r['onayli_count'] ?? 0) ?></span>
                <span>Onaysiz: <?= (int)($r['onaysiz_count'] ?? 0) ?></span>
                <span>Toplam: <?= (int)($r['total_numbers'] ?? 0) ?></span>
              </div>
            </div>
            <div class="status-pill <?= e($badge['class']) ?>"><?= e($badge['text']) ?></div>
          </div>

          <button class="dropdown-btn" type="button" onclick="toggleDropdown(this)">
            <span class="btn-text">Detaylari Goster</span>
            <span class="arrow">▼</span>
          </button>

          <div class="dropdown-content">
            <div class="info-row">
              <span class="info-label">Gonderen</span>
              <span class="info-value"><?= e((string)($r['from_email'] ?? '')) ?></span>
            </div>
            <div class="info-row">
              <span class="info-label">Alici(lar)</span>
              <span class="info-value"><?= e($toText) ?></span>
            </div>
            <div class="info-row">
              <span class="info-label">Ekler</span>
              <span class="info-value"><?= e($attText ?: '-') ?></span>
            </div>
            <?php if (!empty($r['error'])): ?>
              <div class="info-row">
                <span class="info-label">Hata</span>
                <span class="info-value"><?= e((string)$r['error']) ?></span>
              </div>
            <?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)])) ?>">← Onceki</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 = 'Detaylari Goster';
      } 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 = 'Detaylari Goster';
          }
        });

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

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