# 마인크래프트 접속자 수 차트 추가 작업 지시서

## 작업 목적
`index` 페이지의 **"Powered by AMP"** 텍스트 오른쪽에 미니 라인 차트를 추가한다.
차트를 클릭하면 **시간대별 마인크래프트 서버 접속자 수**를 보여주는 전용 페이지로 이동한다.

---

## 데이터 구조

### 데이터 출처
- 기존 `mc_ping.php` 크론잡(1분마다 실행)이 `status.json`을 갱신하고 있음
- 이 크론잡을 수정하여 **시간대별 이력 데이터도 파일로 누적 저장**하도록 변경 필요

### 저장 파일 구조 (새로 추가)
```
{웹루트}/
├── mc_ping.php          ← 기존 파일 (수정 필요)
├── status.json          ← 기존 파일 (현재 상태, 유지)
└── data/
    └── history.json     ← 신규 생성 (시간대별 누적 이력)
```

### history.json 포맷
```json
[
  {
    "time": "2026-03-19T12:00:00+09:00",
    "total": 5,
    "servers": [
      { "name": "서버 0", "online": 3 },
      { "name": "서버 1", "online": 2 }
    ]
  },
  {
    "time": "2026-03-19T12:01:00+09:00",
    "total": 6,
    "servers": [
      { "name": "서버 0", "online": 4 },
      { "name": "서버 1", "online": 2 }
    ]
  }
]
```
- 1분마다 항목 추가 (append)
- 최대 **1,440개** 유지 (24시간치), 초과 시 오래된 항목 삭제
- 파일 경로: `{웹루트}/data/history.json`

---

## mc_ping.php 수정 사항

기존 `status.json` 저장 로직 뒤에 아래 내용 추가:

```php
// history.json 누적 저장
$historyFile = __DIR__ . '/data/history.json';

// data/ 디렉토리 없으면 생성
if (!is_dir(__DIR__ . '/data')) {
    mkdir(__DIR__ . '/data', 0755, true);
}

$history = [];
if (file_exists($historyFile)) {
    $history = json_decode(file_get_contents($historyFile), true) ?? [];
}

// 이번 시각 데이터 추가
$totalOnline = array_sum(array_column(
    array_map(fn($s) => ['online' => $s['players']['online']], $results),
    'online'
));

$history[] = [
    'time'    => date('c'),
    'total'   => $totalOnline,
    'servers' => array_map(fn($s) => [
        'name'   => $s['name'],
        'online' => $s['players']['online'],
    ], $results),
];

// 최대 1440개 (24시간) 유지
if (count($history) > 1440) {
    $history = array_slice($history, -1440);
}

file_put_contents($historyFile, json_encode($history, JSON_UNESCAPED_UNICODE));
```

---

## 추가할 파일

### 1. api/history.php — 이력 데이터 API

```php
<?php
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-cache');

// GET 파라미터: ?hours=24 (기본 24시간, 최대 24)
$hours = min((int)($_GET['hours'] ?? 24), 24);
$limit = $hours * 60; // 분 단위

$historyFile = __DIR__ . '/../data/history.json';

if (!file_exists($historyFile)) {
    echo json_encode([]);
    exit;
}

$history = json_decode(file_get_contents($historyFile), true) ?? [];
$history = array_slice($history, -$limit);

echo json_encode($history, JSON_UNESCAPED_UNICODE);
```

---

### 2. stats.php — 시간대별 상세 차트 페이지 (신규)

- URL: `/stats.php` (또는 기존 사이트 라우팅 방식에 맞게 조정)
- `api/history.php?hours=24` 를 fetch하여 Chart.js로 라인 차트 렌더링
- 차트 구성:
  - X축: 시간 (HH:MM 형식)
  - Y축: 접속자 수 (0 이상 정수)
  - 라인: 전체 합산 1개 + 서버별 라인 (서버 수만큼)
  - 범례 표시
  - 시간 범위 선택 버튼: `1시간 / 6시간 / 24시간`
- 디자인: 기존 index 페이지 스타일과 통일

---

### 3. index 페이지 수정 — 미니 차트 추가

#### 위치
기존 HTML에서 `Powered by AMP` 텍스트를 찾아 오른쪽에 미니 차트 삽입:

```html
<!-- 기존 -->
<span>Powered by AMP</span>

<!-- 수정 후 -->
<span>Powered by AMP</span>
<a href="/stats.php" title="접속자 현황 보기" style="margin-left:12px; text-decoration:none;">
  <canvas id="miniChart" width="80" height="28" style="cursor:pointer; vertical-align:middle;"></canvas>
</a>
```

#### 미니 차트 JS (index 페이지 하단 `<script>` 추가)
```javascript
(async () => {
  const res  = await fetch('/api/history.php?hours=1');
  const data = await res.json();

  const labels = data.map(d => {
    const t = new Date(d.time);
    return t.getHours().toString().padStart(2,'0') + ':' + t.getMinutes().toString().padStart(2,'0');
  });
  const values = data.map(d => d.total);

  const ctx = document.getElementById('miniChart').getContext('2d');
  new Chart(ctx, {
    type: 'line',
    data: {
      labels,
      datasets: [{
        data: values,
        borderColor: '#4ade80',
        borderWidth: 1.5,
        pointRadius: 0,
        tension: 0.4,
        fill: true,
        backgroundColor: 'rgba(74,222,128,0.15)',
      }]
    },
    options: {
      animation: false,
      plugins: { legend: { display: false }, tooltip: { enabled: false } },
      scales:  { x: { display: false }, y: { display: false, min: 0 } },
    }
  });
})();
```

#### Chart.js CDN (index 페이지 `<head>` 또는 `<body>` 하단에 없으면 추가)
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.min.js"></script>
```

---

## 에이전트 작업 순서 (STEP)

### STEP 1 — 파일 구조 파악
- 웹루트 경로 확인
- `index` 파일 위치 확인 (index.html / index.php 등)
- `Powered by AMP` 텍스트가 있는 파일 및 라인 찾기
- 기존 `mc_ping.php`, `status.json` 경로 확인

### STEP 2 — mc_ping.php 수정
- 위 `history.json 누적 저장` 코드 블록을 기존 파일 하단에 추가
- `data/` 디렉토리 생성 및 권한 설정:
  ```bash
  mkdir -p {웹루트}/data
  chown www-data:www-data {웹루트}/data
  chmod 755 {웹루트}/data
  ```

### STEP 3 — api/history.php 생성
- 위 코드 그대로 `{웹루트}/api/history.php` 에 저장

### STEP 4 — stats.php 생성
- 기존 index 페이지 디자인(CSS, 헤더, 푸터) 참고하여 통일된 스타일로 작성
- Chart.js 라인 차트로 시간대별 접속자 수 시각화
- 1시간 / 6시간 / 24시간 버튼으로 범위 전환 기능 포함

### STEP 5 — index 페이지 수정
- `Powered by AMP` 위치 찾아 미니 차트 `<canvas>` 및 `<a>` 태그 삽입
- Chart.js CDN이 없으면 추가
- 미니 차트 JS 스니펫 삽입

### STEP 6 — 동작 확인
```bash
# 크론잡 수동 실행 후 파일 생성 확인
php {웹루트}/mc_ping.php
cat {웹루트}/data/history.json

# API 응답 확인
curl https://yj.kang.kr/api/history.php?hours=1
```

---

## 주의사항
- `data/history.json`은 웹에서 직접 접근 가능하므로 필요 시 Apache `.htaccess`로 차단:
  ```apacheconf
  <Directory "{웹루트}/data">
      Require all denied
  </Directory>
  ```
- Chart.js는 index 페이지에 이미 로드된 경우 중복 추가 금지
- 기존 index 파일의 CSS 클래스명, 레이아웃 구조를 반드시 확인 후 삽입 위치 결정
