<?php
// pages/admin_audit.php — 로그 추적 (시스템관리자 전용)
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/auth.php';
requireLogin();
require_once __DIR__ . '/../includes/header.php';
$db = (new Database())->getConnection();

$filterPeriod = $_GET['period'] ?? '';
$filterYear = $_GET['year'] ?? date('Y');
$filterMonth = $_GET['month'] ?? '';
$filterWeek = $_GET['week'] ?? '';
$filterDate = $_GET['date'] ?? '';

$countSql = "SELECT COUNT(*) FROM audit_log WHERE 1=1";
$sql = "SELECT al.*, ua.login_id, s.name AS changed_by_name
FROM audit_log al LEFT JOIN user_account ua ON al.changed_by = ua.user_id LEFT JOIN staff s ON ua.staff_id = s.staff_id WHERE 1=1";
$params = []; $countParams = [];
$periodCond = "";

if ($filterPeriod === 'year') { $periodCond = " AND YEAR(al.created_at) = ?"; $params[] = $filterYear; $countParams[] = $filterYear; }
elseif ($filterPeriod === 'month' && $filterMonth) { $periodCond = " AND DATE_FORMAT(al.created_at,'%Y-%m') = ?"; $params[] = $filterMonth; $countParams[] = $filterMonth; }
elseif ($filterPeriod === 'week') {
    $ws = $filterWeek ? date('Y-m-d', strtotime($filterWeek)) : date('Y-m-d', strtotime('monday this week'));
    $we = date('Y-m-d', strtotime($ws . ' +6 days'));
    $periodCond = " AND DATE(al.created_at) BETWEEN ? AND ?"; $params[] = $ws; $params[] = $we; $countParams[] = $ws; $countParams[] = $we;
}
elseif ($filterPeriod === 'day' && $filterDate) { $periodCond = " AND DATE(al.created_at) = ?"; $params[] = $filterDate; $countParams[] = $filterDate; }

$sql .= str_replace('al.created_at','al.created_at',$periodCond);
$countSql .= str_replace('al.','', $periodCond);
$sql .= " ORDER BY al.created_at DESC";

// 총 건수
$cntStmt = $db->prepare($countSql); $cntStmt->execute($countParams);
$totalCnt = (int)$cntStmt->fetchColumn();

// 페이지네이션
$perPage = 20; $page = max(1,(int)($_GET['page']??1));
$totalPages = max(1, ceil($totalCnt / $perPage));
$offset = ($page - 1) * $perPage;
$sql .= " LIMIT $perPage OFFSET $offset";
$stmt = $db->prepare($sql); $stmt->execute($params); $logs = $stmt->fetchAll();

// 카테고리 매핑 (table_name + action → 한글 카테고리)
function getCategory($table, $action) {
    $map = [
        'LOGIN' => '로그인', 'LOGOUT' => '로그아웃', 'REGISTER' => '계정등록',
        'PW_RESET' => '비밀번호변경', 'ROLE_CHANGE' => '역할변경',
        'APPROVE' => '승인처리', 'REJECT' => '반려처리',
    ];
    if (isset($map[$action])) return $map[$action];
    $tMap = [
        'sales' => '실적관리', 'staff' => '인원관리', 'user_account' => '계정관리',
        'approval_flow' => '인센티브검토', 'incentive_review' => '인센티브검토',
        'evaluation' => '인사평가', 'notice' => '공지사항', 'team_notice' => '팀공지',
        'policy_rule' => '정책설정', 'menu_permission' => '메뉴권한',
    ];
    return $tMap[$table] ?? $table;
}

function getActionDesc($log) {
    global $db;
    $action = $log['action'];
    $table = $log['table_name'];
    $new = json_decode($log['new_values'] ?? '{}', true) ?: [];
    $old = json_decode($log['old_values'] ?? '{}', true) ?: [];
    $name = $log['changed_by_name'] ?? '시스템';
    $rid = $log['record_id'] ?? '';

    // 대상자 이름 조회 헬퍼
    $targetName = '';
    if ($rid && $table === 'user_account') {
        try { $t = $db->prepare("SELECT s.name FROM user_account ua JOIN staff s ON ua.staff_id=s.staff_id WHERE ua.user_id=?"); $t->execute([(int)$rid]); $targetName = $t->fetchColumn() ?: ''; } catch(Exception $e) {}
    } elseif ($rid && $table === 'staff') {
        try { $t = $db->prepare("SELECT name FROM staff WHERE staff_id=?"); $t->execute([(int)$rid]); $targetName = $t->fetchColumn() ?: ''; } catch(Exception $e) {}
    }
    $targetLabel = $targetName ? "{$targetName}님" : "#{$rid}";

    if ($action === 'LOGIN') return "{$name}님이 시스템에 로그인했습니다.";
    if ($action === 'REGISTER') return "{$name}님이 새 계정을 등록했습니다. (ID: " . ($new['login_id'] ?? $rid) . ")";
    if ($action === 'PW_RESET') return "{$name}님이 {$targetLabel}의 비밀번호를 변경했습니다.";
    if ($action === 'ROLE_CHANGE') {
        $oldRole = $old['old_role'] ?? $old['old'] ?? '';
        $newRole = $new['new_role'] ?? $new['new'] ?? '';
        $tgtName = $new['target_name'] ?? '';
        $roleMap = ['staff'=>'일반','team_leader'=>'팀장','manager'=>'관리자','ceo'=>'대표','sysadmin'=>'시스템관리자'];
        $oldLabel = $roleMap[$oldRole] ?? $oldRole ?: '이전';
        $newLabel = $roleMap[$newRole] ?? $newRole ?: '신규';
        $whoLabel = $tgtName ? "{$tgtName}님" : $targetLabel;
        return "{$name}님이 {$whoLabel}의 역할을 {$oldLabel} → {$newLabel}(으)로 변경했습니다.";
    }
    if ($action === 'APPROVE') {
        $status = $new['approve_status'] ?? $new['review_status'] ?? '승인';
        $month = $new['approval_month'] ?? '';
        return "{$name}님이 {$targetLabel} " . ($month ? "({$month}) " : '') . "건을 {$status} 처리했습니다.";
    }
    if ($action === 'REJECT') return "{$name}님이 {$targetLabel} 건을 반려 처리했습니다.";
    if ($action === 'INSERT') {
        $details = [];
        foreach (['name','title','company_name','grade','team','login_id','sale_month'] as $k) { if (!empty($new[$k])) $details[] = $new[$k]; }
        $detailStr = $details ? ' (' . implode(', ', array_slice($details, 0, 3)) . ')' : '';
        $tableMap = ['sales'=>'실적','staff'=>'인원','approval_flow'=>'인센티브 검토','notice'=>'공지사항','team_notice'=>'팀 공지','evaluation'=>'인사평가'];
        $tLabel = $tableMap[$table] ?? $table;
        return "{$name}님이 {$tLabel}에 새 데이터를 등록했습니다.{$detailStr}";
    }
    if ($action === 'UPDATE') {
        $changes = [];
        foreach ($new as $k => $v) { $ov = $old[$k] ?? ''; if ((string)$ov !== (string)$v) $changes[] = "{$k}: {$ov} → {$v}"; }
        $changeStr = $changes ? ' [' . implode(', ', array_slice($changes, 0, 3)) . ']' : '';
        $tableMap = ['sales'=>'실적','staff'=>'인원 정보','approval_flow'=>'인센티브 검토','user_account'=>'계정'];
        $tLabel = $tableMap[$table] ?? $table;
        return "{$name}님이 {$targetLabel}의 {$tLabel}을(를) 수정했습니다.{$changeStr}";
    }
    if ($action === 'DELETE' || $action === 'DEACTIVATE') return "{$name}님이 {$targetLabel}을(를) 삭제/비활성화했습니다.";
    $details = $new ? ' ' . json_encode($new, JSON_UNESCAPED_UNICODE) : '';
    return "{$name}님이 {$table}에서 {$action} 작업을 수행했습니다.{$details}";
}
?>

<div class="page-header"><h2>🔍 로그 추적</h2><div class="breadcrumb">시스템 변경 이력 추적</div></div>

<div class="card" style="margin-bottom:1rem;padding:0.75rem 1rem;">
    <form method="GET" style="display:flex;gap:0.75rem;align-items:center;flex-wrap:wrap;">
        <select name="period" onchange="togglePeriodInput(this.value);this.form.submit()" class="dash-filter" style="width:6rem;">
            <option value="">기간</option>
            <option value="year" <?= $filterPeriod==='year'?'selected':'' ?>>년</option>
            <option value="month" <?= $filterPeriod==='month'?'selected':'' ?>>월</option>
            <option value="week" <?= $filterPeriod==='week'?'selected':'' ?>>주</option>
            <option value="day" <?= $filterPeriod==='day'?'selected':'' ?>>일</option>
        </select>
        <?php if ($filterPeriod === 'year'): ?>
        <select name="year" onchange="this.form.submit()" class="dash-filter" style="width:6rem;">
            <?php for($y=date('Y');$y>=2024;$y--): ?><option value="<?= $y ?>" <?= $filterYear==$y?'selected':'' ?>><?= $y ?>년</option><?php endfor; ?>
        </select>
        <?php elseif ($filterPeriod === 'month'): ?>
        <input type="month" name="month" value="<?= $filterMonth ?: date('Y-m') ?>" class="dash-filter" style="width:10rem;" onchange="this.form.submit()">
        <?php elseif ($filterPeriod === 'week'): ?>
        <input type="date" name="week" value="<?= $filterWeek ?: date('Y-m-d', strtotime('monday this week')) ?>" class="dash-filter" style="width:10rem;" onchange="this.form.submit()">
        <span style="font-size:var(--fs-xs);color:var(--text-tertiary);">주 시작일</span>
        <?php elseif ($filterPeriod === 'day'): ?>
        <input type="date" name="date" value="<?= $filterDate ?: date('Y-m-d') ?>" class="dash-filter" style="width:10rem;" onchange="this.form.submit()">
        <?php endif; ?>
        <a href="<?=BASE_URL?>pages/admin_audit.php" class="btn btn-outline" style="padding:0.375rem 1rem;font-size:var(--fs-xs);">초기화</a>
        <span style="font-size:var(--fs-xs);color:var(--text-tertiary);margin-left:auto;">총 <?= number_format($totalCnt) ?>건</span>
    </form>
</div>

<div class="card">
    <div class="table-wrap"><table>
        <thead><tr><th style="width:3rem;">No</th><th>카테고리</th><th>사용자</th><th>액션 내용</th><th>일시</th></tr></thead>
        <tbody>
        <?php $startNo = $totalCnt - $offset; foreach ($logs as $i => $l): $no = $startNo - $i; ?>
        <tr>
            <td style="color:var(--text-tertiary);font-size:var(--fs-xs);"><?= $no ?></td>
            <td><span class="badge <?php
                $cat = getCategory($l['table_name'], $l['action']);
                echo match(true) {
                    str_contains($cat,'로그인') => 'badge-gray',
                    str_contains($cat,'승인') => 'badge-success',
                    str_contains($cat,'반려') || str_contains($cat,'삭제') => 'badge-danger',
                    str_contains($cat,'변경') || str_contains($cat,'수정') => 'badge-warning',
                    str_contains($cat,'등록') => 'badge-info',
                    default => 'badge-gray'
                };
            ?>" style="font-size:var(--fs-xs);"><?= $cat ?></span></td>
            <td style="font-size:var(--fs-xs);"><?= htmlspecialchars($l['changed_by_name'] ?? '-') ?></td>
            <td style="font-size:var(--fs-xs);max-width:28rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="<?= htmlspecialchars(getActionDesc($l)) ?>"><?= htmlspecialchars(getActionDesc($l)) ?></td>
            <td style="font-size:var(--fs-xs);white-space:nowrap;color:var(--text-tertiary);"><?= date('Y-m-d H:i:s', strtotime($l['created_at'])) ?></td>
        </tr>
        <?php endforeach; ?>
        <?php if (empty($logs)): ?><tr><td colspan="5" class="text-muted">로그가 없습니다.</td></tr><?php endif; ?>
        </tbody>
    </table></div>
    <?php if ($totalCnt > 0): ?>
    <div style="display:flex;justify-content:center;align-items:center;gap:0.5rem;padding:1rem;">
        <span style="font-size:var(--fs-xs);color:var(--text-tertiary);">총 <?= number_format($totalCnt) ?>건 (<?= $page ?>/<?= $totalPages ?>)</span>
        <?php if ($totalPages > 1): ?>
        <?php if ($page>1): ?><a href="?<?= http_build_query(array_merge($_GET,['page'=>$page-1])) ?>" class="btn btn-outline" style="padding:0.25rem 0.5rem;font-size:var(--fs-xs);">‹ 이전</a><?php endif; ?>
        <?php for($p=max(1,$page-2);$p<=min($totalPages,$page+2);$p++): ?>
        <a href="?<?= http_build_query(array_merge($_GET,['page'=>$p])) ?>" style="padding:0.25rem 0.5rem;font-size:var(--fs-xs);border-radius:4px;text-decoration:none;<?= $p===$page?'background:var(--accent);color:var(--bg-color);font-weight:700;':'color:var(--text-secondary);' ?>"><?= $p ?></a>
        <?php endfor; ?>
        <?php if ($page<$totalPages): ?><a href="?<?= http_build_query(array_merge($_GET,['page'=>$page+1])) ?>" class="btn btn-outline" style="padding:0.25rem 0.5rem;font-size:var(--fs-xs);">다음 ›</a><?php endif; ?>
        <?php endif; ?>
    </div>
    <?php endif; ?>
</div>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
