<?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'] ?? ''));
if ($q !== '') {
    $q = function_exists('mb_substr') ? mb_substr($q, 0, 120, 'UTF-8') : substr($q, 0, 120);
}
$message = trim((string)($_GET['message'] ?? ''));
$status = trim((string)($_GET['status'] ?? 'success'));
$page = max(1, (int)($_GET['page'] ?? 1));
$allowedLimits = [25, 50, 100];
$limit = (int)($_GET['page_size'] ?? 50);
if (!in_array($limit, $allowedLimits, true)) $limit = 50;
$offset = ($page - 1) * $limit;

$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 . '%';
}
$countSql = 'SELECT COUNT(*) FROM app_logs';
if ($where) $countSql .= ' WHERE ' . implode(' AND ', $where);
$countStmt = $pdo->prepare($countSql);
$countStmt->execute($params);
$totalLogs = (int)$countStmt->fetchColumn();
$pages = max(1, (int)ceil($totalLogs / $limit));
$page = min($page, $pages);
$offset = ($page - 1) * $limit;

$sql = 'SELECT id, log_level, log_type, message, file_path, created_at FROM app_logs';
if ($where) $sql .= ' WHERE ' . implode(' AND ', $where);
$sql .= ' ORDER BY id DESC LIMIT ' . (int)$limit . ' OFFSET ' . (int)$offset;
$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();

function logsUrlWith($changes = []) {
    $params = $_GET;
    foreach ($changes as $key => $value) {
        if ($value === null || $value === '') unset($params[$key]);
        else $params[$key] = $value;
    }
    return 'logs.php?' . http_build_query($params);
}

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"><label>표시 수<select name="page_size"><?php foreach ($allowedLimits as $size): ?><option value="<?php echo $size; ?>" <?php echo $limit === $size ? 'selected' : ''; ?>><?php echo $size; ?>건</option><?php endforeach; ?></select></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(maskInternalPathText($log['message'] ?? '')); ?></td>
                            <td class="log-file-cell"><?php echo h(maskInternalPathText($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>
    <?php if ($pages > 1): ?>
        <nav class="search-pagination" aria-label="로그 페이지">
            <?php if ($page > 1): ?><a class="btn btn-secondary btn-sm" href="<?php echo h(logsUrlWith(['page' => $page - 1])); ?>">이전</a><?php endif; ?>
            <span class="settings-muted"><?php echo number_format($page); ?> / <?php echo number_format($pages); ?> 페이지 · <?php echo number_format($totalLogs); ?>건</span>
            <?php if ($page < $pages): ?><a class="btn btn-secondary btn-sm" href="<?php echo h(logsUrlWith(['page' => $page + 1])); ?>">다음</a><?php endif; ?>
        </nav>
    <?php endif; ?>

    <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(maskInternalPathText($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(); ?>
