<?php
ini_set('display_errors', 1); error_reporting(E_ALL);
require_once __DIR__ . '/../header.php';
$pdo = App\Database::getConnection();

$filterModule = trim($_GET['module'] ?? '');
$filterEvent = trim($_GET['event'] ?? '');
$searchTerm = trim($_GET['q'] ?? '');
$limit = 250;

if (!function_exists('h')) {
  function h(?string $value): string {
    return htmlspecialchars($value ?? '', ENT_QUOTES, 'UTF-8');
  }
}

if (!function_exists('badgeColors')) {
    function badgeColors(string $event): array {
        $event = strtolower($event);
        if (strpos($event, 'fail') !== false || strpos($event, 'error') !== false) {
            return ['#fee2e2', '#b91c1c'];
        }
        if (strpos($event, 'block') !== false) {
            return ['#fef3c7', '#92400e'];
        }
        return ['#dcfce7', '#166534'];
    }
}

try {
    $sql = 'SELECT * FROM system_logs WHERE 1=1';
    $params = [];

    if ($filterModule !== '') {
        $sql .= ' AND module = :module';
        $params[':module'] = $filterModule;
    }
    if ($filterEvent !== '') {
        $sql .= ' AND event = :event';
        $params[':event'] = $filterEvent;
    }
    if ($searchTerm !== '') {
        $sql .= ' AND (event LIKE :q OR details LIKE :q OR user LIKE :q OR module LIKE :q)';
        $params[':q'] = '%' . $searchTerm . '%';
    }

    $sql .= ' ORDER BY created_at DESC LIMIT ' . $limit;
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $logs = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $moduleStmt = $pdo->query("SELECT DISTINCT module FROM system_logs WHERE module IS NOT NULL AND module <> '' ORDER BY module");
    $modules = $moduleStmt->fetchAll(PDO::FETCH_COLUMN) ?: [];
    $eventStmt = $pdo->query("SELECT DISTINCT event FROM system_logs ORDER BY event");
    $events = $eventStmt->fetchAll(PDO::FETCH_COLUMN) ?: [];
    $tableExists = true;
} catch (\PDOException $e) {
    $logs = [];
    $modules = [];
    $events = [];
    $tableExists = false;
    $tableError = 'Tablo bulunamadı: ' . $e->getMessage();
}
?>
<style>
  .log-page{max-width:1200px;width:100%;margin:0 auto;padding:32px 20px;}
  .log-hero{display:flex;flex-wrap:wrap;gap:12px;align-items:center;justify-content:space-between;margin-bottom:20px;}
  .log-hero h2{margin:0;font-family:'Segoe UI',sans-serif;font-size:30px;color:#0f172a;display:flex;align-items:center;gap:10px;}
  .log-count{background:#dbeafe;color:#1e3a8a;padding:6px 14px;border-radius:999px;font-weight:600;font-size:14px;}
  .log-filters{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:12px;background:#fff;border:1px solid #e2e8f0;border-radius:16px;padding:18px;margin-bottom:24px;box-shadow:0 10px 30px rgba(15,23,42,0.05);}
  .log-filters label{font-size:13px;font-weight:600;color:#475569;margin-bottom:4px;display:block;}
  .log-filters select,.log-filters input{width:100%;padding:10px 12px;border:1px solid #cbd5f5;border-radius:10px;font-size:14px;background:#f8fafc;font-family:'Segoe UI',sans-serif;}
  .log-filters select:focus,.log-filters input:focus{outline:none;border-color:#2563eb;box-shadow:0 0 0 3px rgba(37,99,235,0.15);}
  .filter-actions{display:flex;gap:8px;align-items:center;}
  .btn-primary{background:#2563eb;color:#fff;border:none;border-radius:10px;padding:10px 18px;font-weight:600;cursor:pointer;box-shadow:0 6px 16px rgba(37,99,235,0.25);}
  .btn-primary:hover{background:#1d4ed8;}
  .btn-link{color:#475569;text-decoration:none;font-weight:600;padding:10px 14px;border-radius:10px;background:#f1f5f9;display:inline-block;}
  .log-banner{padding:16px;border-radius:14px;margin-bottom:20px;display:flex;gap:10px;align-items:flex-start;}
  .log-banner--error{background:#fef2f2;border:1px solid #fecaca;color:#b91c1c;}
  .log-banner--empty{background:#f0fdf4;border:1px solid #bbf7d0;color:#166534;}
  .log-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:16px;}
  .log-card{background:#fff;border:1px solid #e5e7eb;border-radius:16px;padding:18px;box-shadow:0 12px 32px rgba(15,23,42,0.08);transition:.25s;} 
  .log-card:hover{transform:translateY(-4px);box-shadow:0 20px 40px rgba(15,23,42,0.15);} 
  .log-card__header{display:flex;justify-content:space-between;gap:12px;align-items:flex-start;margin-bottom:12px;} 
  .log-card__title{font-weight:600;color:#0f172a;font-size:16px;} 
  .badge{display:inline-flex;align-items:center;padding:4px 10px;border-radius:999px;font-size:12px;font-weight:600;} 
  .module-chip{background:#eef2ff;color:#4338ca;} 
  .log-card__meta{display:flex;flex-wrap:wrap;gap:10px;color:#475569;font-size:13px;margin-bottom:6px;} 
  .log-card__details{margin-top:12px;padding-top:12px;border-top:1px solid #e2e8f0;font-size:13px;color:#334155;white-space:pre-wrap;} 
  .log-card__footer{display:flex;flex-wrap:wrap;gap:10px;font-size:12px;color:#64748b;} 
  @media (max-width:600px){
    .log-filters{grid-template-columns:1fr;}
    .filter-actions{flex-direction:column;align-items:stretch;}
  }
</style>

<div class="log-page">
  <div class="log-hero">
    <h2><i class="bi bi-journal-text"></i> Sistem Logları</h2>
    <span class="log-count"><?= count($logs) ?> / <?= $limit ?> kayıt</span>
  </div>

  <?php if (!$tableExists): ?>
    <div class="log-banner log-banner--error">
      <i class="bi bi-exclamation-triangle" style="font-size:22px;"></i>
      <div>
        <strong>Tablo Bulunamadı</strong><br>
        Lütfen <code>php migrations/run_migrations.php</code> komutunu çalıştırın.<br>
        <small><?= h($tableError ?? '') ?></small>
      </div>
    </div>
  <?php else: ?>
    <form class="log-filters" method="get" action="/SistemModulu/loglar.php">
      <div>
        <label>Modül</label>
        <select name="module">
          <option value="">Tüm modüller</option>
          <?php foreach ($modules as $module): ?>
            <option value="<?= h($module) ?>" <?= $module === $filterModule ? 'selected' : '' ?>><?= h(strtoupper($module)) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div>
        <label>İşlem / Event</label>
        <select name="event">
          <option value="">Tüm olaylar</option>
          <?php foreach ($events as $event): ?>
            <option value="<?= h($event) ?>" <?= $event === $filterEvent ? 'selected' : '' ?>><?= h($event) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div>
        <label>Arama</label>
        <input type="search" name="q" value="<?= h($searchTerm) ?>" placeholder="kullanıcı, olay, detay">
      </div>
      <div class="filter-actions">
        <button type="submit" class="btn-primary"><i class="bi bi-funnel" style="margin-right:6px;"></i>Filtrele</button>
        <a href="/SistemModulu/loglar.php" class="btn-link">Temizle</a>
      </div>
    </form>
  <?php endif; ?>

  <?php if ($tableExists && empty($logs)): ?>
    <div class="log-banner log-banner--empty">
      <i class="bi bi-info-circle" style="font-size:22px;"></i>
      <div>
        <strong>Henüz log kaydı yok</strong><br>
        Bir işlem yaptıktan sonra kayıtları burada göreceksiniz.
      </div>
    </div>
  <?php elseif ($tableExists): ?>
    <div class="log-grid">
      <?php foreach ($logs as $log): ?>
        <?php [$badgeBg, $badgeColor] = badgeColors($log['event'] ?? ''); ?>
        <?php $moduleLabel = $log['module'] ?: 'GENEL'; ?>
        <article class="log-card">
          <div class="log-card__header">
            <div>
              <div class="log-card__title"><?= h($log['user'] ?? 'Sistem') ?></div>
              <div class="log-card__meta">
                <span class="badge" style="background:<?= $badgeBg ?>;color:<?= $badgeColor ?>;"><?= h($log['event']) ?></span>
                <span class="badge module-chip"><i class="bi bi-diagram-3" style="margin-right:4px;"></i><?= h($moduleLabel) ?></span>
              </div>
            </div>
            <div class="log-card__meta" style="justify-content:flex-end;">
              <span><i class="bi bi-clock" style="margin-right:4px;"></i><?= h(date('d.m.Y H:i', strtotime($log['created_at']))) ?></span>
            </div>
          </div>
          <div class="log-card__footer">
            <span><i class="bi bi-laptop" style="margin-right:4px;"></i><?= h($log['ip']) ?></span>
          </div>
          <?php if (!empty($log['details'])): ?>
            <div class="log-card__details">
              <strong>Detay:</strong><br><?= nl2br(h($log['details'])) ?>
            </div>
          <?php endif; ?>
        </article>
      <?php endforeach; ?>
    </div>
  <?php endif; ?>
</div>
<?php require_once __DIR__ . '/../footer.php'; ?>
