<?php
require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/includes/db.php';
require_once dirname(__DIR__) . '/includes/functions.php';
require_once dirname(__DIR__) . '/includes/auth.php';
require_once dirname(__DIR__) . '/includes/layout.php';
requirePermission('log_view');

$pdo = getDBConnection();
$level = trim((string)($_GET['level'] ?? ''));
$type = trim((string)($_GET['type'] ?? ''));
$q = trim((string)($_GET['q'] ?? ''));
$message = trim((string)($_GET['message'] ?? ''));
$status = trim((string)($_GET['status'] ?? 'success'));

$where = [];
$params = [];
if ($level !== '') {
    $where[] = 'log_level = :level';
    $params[':level'] = $level;
}
if ($type !== '') {
    $where[] = 'log_type = :type';
    $params[':type'] = $type;
}
if ($q !== '') {
    $where[] = '(message LIKE :q OR context LIKE :q OR file_path LIKE :q)';
    $params[':q'] = '%' . $q . '%';
}
$sql = 'SELECT * FROM app_logs';
if ($where) $sql .= ' WHERE ' . implode(' AND ', $where);
$sql .= ' ORDER BY id DESC LIMIT 300';
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$logs = $stmt->fetchAll();
$types = $pdo->query("SELECT DISTINCT log_type FROM app_logs ORDER BY log_type ASC LIMIT 200")->fetchAll();

renderHeader('오류 로그', 'logs');
?>
<div class="admin-dashboard logs-page">
    <div class="page-title-section">
        <h1 class="page-main-title">오류 로그</h1>
        <p class="page-subtitle">PHP, 스캔, 스트리밍, 백업/복원 등 운영 중 발생한 로그를 확인합니다.</p>
    </div>
    <?php if ($message !== ''): ?>
        <div class="alert-box <?php echo $status === 'error' ? 'alert-danger' : 'alert-info'; ?>"><div class="alert-content"><p><?php echo h($message); ?></p></div></div>
    <?php endif; ?>

    <section class="settings-card">
        <form method="GET" class="settings-form compact-filter-form">
            <div class="form-row">
                <div class="form-group"><label>레벨<select name="level"><option value="">전체</option><?php foreach (['info','warning','error','critical'] as $lv): ?><option value="<?php echo h($lv); ?>" <?php echo $level === $lv ? 'selected' : ''; ?>><?php echo h($lv); ?></option><?php endforeach; ?></select></label></div>
                <div class="form-group"><label>타입<select name="type"><option value="">전체</option><?php foreach ($types as $row): ?><option value="<?php echo h($row['log_type']); ?>" <?php echo $type === $row['log_type'] ? 'selected' : ''; ?>><?php echo h($row['log_type']); ?></option><?php endforeach; ?></select></label></div>
                <div class="form-group"><label>검색<input type="search" name="q" value="<?php echo h($q); ?>" placeholder="메시지, context, 파일"></label></div>
                <div class="form-group form-group-actions"><button class="btn btn-secondary" type="submit">필터</button></div>
            </div>
        </form>
        <?php if (hasPermission('log_delete')): ?>
        <form action="log_clear.php" method="POST" class="inline-action-form" onsubmit="return confirm('90일보다 오래된 앱 로그를 정리할까요?');">
            <?php echo csrfInput(); ?>
            <input type="text" name="confirm_phrase" class="form-control danger-confirm-input" placeholder="삭제합니다" required>
            <button class="btn btn-danger" name="action" value="cleanup_old">오래된 로그 정리</button>
        </form>
        <?php endif; ?>
    </section>

    <div class="table-container log-table-container">
        <table class="data-table log-table">
            <thead><tr><th>시간</th><th>레벨</th><th>타입</th><th>메시지</th><th>파일</th><th>상세</th></tr></thead>
            <tbody>
                <?php if (empty($logs)): ?>
                    <tr><td colspan="6" class="text-center">표시할 로그가 없습니다.</td></tr>
                <?php else: ?>
                    <?php foreach ($logs as $log): ?>
                        <tr>
                            <td><?php echo h($log['created_at']); ?></td>
                            <td><span class="log-level level-<?php echo h($log['log_level']); ?>"><?php echo h($log['log_level']); ?></span></td>
                            <td><?php echo h($log['log_type']); ?></td>
                            <td class="log-message-cell"><?php echo h($log['message']); ?></td>
                            <td class="log-file-cell"><?php echo h($log['file_path'] ?: '-'); ?></td>
                            <td><a class="btn btn-secondary btn-sm" href="log_view.php?id=<?php echo h($log['id']); ?>">보기</a></td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <div class="log-card-list">
        <?php foreach ($logs as $log): ?>
            <article class="log-card">
                <span class="log-level level-<?php echo h($log['log_level']); ?>"><?php echo h($log['log_level']); ?></span>
                <strong><?php echo h($log['log_type']); ?></strong>
                <p><?php echo h($log['message']); ?></p>
                <small><?php echo h($log['created_at']); ?></small>
                <a class="btn btn-secondary btn-sm" href="log_view.php?id=<?php echo h($log['id']); ?>">상세 보기</a>
            </article>
        <?php endforeach; ?>
    </div>
</div>
<?php renderFooter(); ?>
