<?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('audit_view');

$pdo = getDBConnection();
$source = in_array(($_GET['source'] ?? 'admin'), ['admin', 'app'], true) ? $_GET['source'] : 'admin';
$action = trim((string)($_GET['action'] ?? ''));
$adminId = max(0, (int)($_GET['admin_id'] ?? 0));
$q = trim((string)($_GET['q'] ?? ''));
if ($q !== '') {
    $q = function_exists('mb_substr') ? mb_substr($q, 0, 120, 'UTF-8') : substr($q, 0, 120);
}
$from = trim((string)($_GET['from'] ?? ''));
$to = trim((string)($_GET['to'] ?? ''));
$page = max(1, (int)($_GET['page'] ?? 1));
$limit = 50;
$offset = ($page - 1) * $limit;
$where = [];
$params = [];

if ($source === 'admin') {
    if ($action !== '') {
        $where[] = 'l.action_type = :action';
        $params[':action'] = $action;
    }
    if ($adminId > 0) {
        $where[] = 'l.admin_user_id = :admin_id';
        $params[':admin_id'] = $adminId;
    }
    if ($q !== '') {
        $where[] = '(l.message LIKE :q_msg OR u.username LIKE :q_user OR u.display_name LIKE :q_display)';
        $params[':q_msg'] = '%' . $q . '%';
        $params[':q_user'] = '%' . $q . '%';
        $params[':q_display'] = '%' . $q . '%';
    }
    if ($from !== '') {
        $where[] = 'l.created_at >= :from_date';
        $params[':from_date'] = $from . ' 00:00:00';
    }
    if ($to !== '') {
        $where[] = 'l.created_at <= :to_date';
        $params[':to_date'] = $to . ' 23:59:59';
    }
    $whereSql = $where ? 'WHERE ' . implode(' AND ', $where) : '';
    $countStmt = $pdo->prepare("SELECT COUNT(*) FROM admin_logs l LEFT JOIN admin_users u ON u.id = l.admin_user_id $whereSql");
    $countStmt->execute($params);
    $total = (int)$countStmt->fetchColumn();
    $stmt = $pdo->prepare("
        SELECT l.*, u.username, u.display_name, 'admin' AS source_name
        FROM admin_logs l
        LEFT JOIN admin_users u ON u.id = l.admin_user_id
        $whereSql
        ORDER BY l.id DESC
        LIMIT $limit OFFSET $offset
    ");
    $stmt->execute($params);
    $logs = $stmt->fetchAll();
} else {
    if ($action !== '') {
        $where[] = '(log_type = :action OR message LIKE :action_like OR context LIKE :action_context)';
        $params[':action'] = $action;
        $params[':action_like'] = '%' . $action . '%';
        $params[':action_context'] = '%' . $action . '%';
    }
    if ($adminId > 0) {
        $where[] = 'user_id = :admin_id';
        $params[':admin_id'] = $adminId;
    }
    if ($q !== '') {
        $where[] = '(message LIKE :q_msg OR context LIKE :q_context)';
        $params[':q_msg'] = '%' . $q . '%';
        $params[':q_context'] = '%' . $q . '%';
    }
    if ($from !== '') {
        $where[] = 'created_at >= :from_date';
        $params[':from_date'] = $from . ' 00:00:00';
    }
    if ($to !== '') {
        $where[] = 'created_at <= :to_date';
        $params[':to_date'] = $to . ' 23:59:59';
    }
    $where[] = "log_type IN ('audit','login_error','backup','restore','import','export','maintenance')";
    $whereSql = 'WHERE ' . implode(' AND ', $where);
    $countStmt = $pdo->prepare("SELECT COUNT(*) FROM app_logs $whereSql");
    $countStmt->execute($params);
    $total = (int)$countStmt->fetchColumn();
    $stmt = $pdo->prepare("
        SELECT id, user_id AS admin_user_id, log_type AS action_type, message, ip_address, user_agent, created_at, log_level, context, 'app' AS source_name
        FROM app_logs
        $whereSql
        ORDER BY id DESC
        LIMIT $limit OFFSET $offset
    ");
    $stmt->execute($params);
    $logs = $stmt->fetchAll();
}

$admins = $pdo->query("SELECT id, username, display_name, role FROM admin_users ORDER BY username ASC")->fetchAll();
$actions = $source === 'admin'
    ? $pdo->query("SELECT DISTINCT action_type FROM admin_logs ORDER BY action_type ASC LIMIT 200")->fetchAll()
    : $pdo->query("SELECT DISTINCT log_type AS action_type FROM app_logs WHERE log_type IN ('audit','login_error','backup','restore','import','export','maintenance') ORDER BY log_type ASC")->fetchAll();
$pages = max(1, (int)ceil($total / $limit));

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

renderHeader('감사 로그', 'audit_logs');
?>
<div class="admin-dashboard logs-page audit-logs-page">
    <div class="page-title-section">
        <h1 class="page-main-title">감사 로그</h1>
        <p class="page-subtitle">관리자 로그인, 권한 부족, 백업, 복원, 가져오기, 로그 정리 같은 보안 이벤트를 확인합니다.</p>
    </div>

    <section class="settings-card">
        <form method="GET" class="settings-form compact-filter-form">
            <div class="form-row">
                <div class="form-group"><label>소스<select name="source"><option value="admin" <?php echo $source === 'admin' ? 'selected' : ''; ?>>관리자 작업</option><option value="app" <?php echo $source === 'app' ? 'selected' : ''; ?>>앱 감사 이벤트</option></select></label></div>
                <div class="form-group"><label>관리자<select name="admin_id"><option value="">전체</option><?php foreach ($admins as $admin): ?><option value="<?php echo h($admin['id']); ?>" <?php echo $adminId === (int)$admin['id'] ? 'selected' : ''; ?>><?php echo h($admin['display_name'] ?: $admin['username']); ?> (<?php echo h(adminRoleLabels()[$admin['role']] ?? $admin['role']); ?>)</option><?php endforeach; ?></select></label></div>
                <div class="form-group"><label>작업<select name="action"><option value="">전체</option><?php foreach ($actions as $row): ?><option value="<?php echo h($row['action_type']); ?>" <?php echo $action === $row['action_type'] ? 'selected' : ''; ?>><?php echo h($row['action_type']); ?></option><?php endforeach; ?></select></label></div>
                <div class="form-group"><label>시작일<input type="date" name="from" value="<?php echo h($from); ?>"></label></div>
                <div class="form-group"><label>종료일<input type="date" name="to" value="<?php echo h($to); ?>"></label></div>
                <div class="form-group"><label>검색<input type="search" name="q" value="<?php echo h($q); ?>" maxlength="100"></label></div>
                <div class="form-group form-group-actions"><button class="btn btn-secondary" type="submit">필터</button></div>
            </div>
        </form>
    </section>

    <div class="section-heading-row">
        <h2 class="section-title">총 <?php echo number_format($total); ?>건</h2>
        <span class="settings-muted"><?php echo number_format($page); ?> / <?php echo number_format($pages); ?> 페이지</span>
    </div>

    <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>IP</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><?php echo h($log['source_name']); ?></td>
                            <td><?php echo h(($log['display_name'] ?? '') ?: ($log['username'] ?? ('#' . ($log['admin_user_id'] ?? '-')))); ?></td>
                            <td><?php echo h($log['action_type']); ?></td>
                            <td class="log-message-cell"><?php echo h(maskSensitiveLogMessage($log['message'] ?? '')); ?></td>
                            <td><?php echo h($log['ip_address'] ?: '-'); ?></td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <div class="log-card-list">
        <?php foreach ($logs as $log): ?>
            <article class="log-card">
                <strong><?php echo h($log['action_type']); ?></strong>
                <p><?php echo h(maskSensitiveLogMessage($log['message'] ?? '')); ?></p>
                <small><?php echo h($log['created_at']); ?> · <?php echo h($log['ip_address'] ?: '-'); ?></small>
            </article>
        <?php endforeach; ?>
    </div>

    <?php if ($pages > 1): ?>
        <nav class="search-pagination">
            <?php if ($page > 1): ?><a class="btn btn-secondary btn-sm" href="<?php echo h(auditQueryUrl(['page' => $page - 1])); ?>">이전</a><?php endif; ?>
            <?php if ($page < $pages): ?><a class="btn btn-secondary btn-sm" href="<?php echo h(auditQueryUrl(['page' => $page + 1])); ?>">다음</a><?php endif; ?>
        </nav>
    <?php endif; ?>
</div>
<?php renderFooter(); ?>
