<?php
/**
 * NuriBoard - 출석체크
 */
SEO::setTitle('출석체크');
require dirname(__DIR__) . '/header.php';

$today = date('Y-m-d');
$daysInMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
$firstDow = date('w', mktime(0, 0, 0, $month, 1, $year));
$prevMonth = $month == 1 ? 12 : $month - 1;
$prevYear = $month == 1 ? $year - 1 : $year;
$nextMonth = $month == 12 ? 1 : $month + 1;
$nextYear = $month == 12 ? $year + 1 : $year;
?>

<div class="board-wrap">
<div class="attend-page">

    <!-- 달력 -->
    <div class="attend-card">
        <div class="attend-cal-header">
            <a href="<?= nb_url("attendance?y={$prevYear}&m={$prevMonth}") ?>" class="btn btn-sm">&laquo;</a>
            <strong><?= $year ?>-<?= str_pad($month, 2, '0', STR_PAD_LEFT) ?></strong>
            <a href="<?= nb_url("attendance?y={$nextYear}&m={$nextMonth}") ?>" class="btn btn-sm">&raquo;</a>
        </div>
        <table class="attend-cal">
            <thead><tr><th class="sun">일</th><th>월</th><th>화</th><th>수</th><th>목</th><th>금</th><th class="sat">토</th></tr></thead>
            <tbody>
            <?php
            $dayCount = 1;
            for ($row = 0; $row < 6; $row++):
                if ($dayCount > $daysInMonth) break;
            ?>
            <tr>
                <?php for ($col = 0; $col < 7; $col++):
                    if (($row === 0 && $col < $firstDow) || $dayCount > $daysInMonth):
                ?>
                    <td></td>
                <?php else:
                    $dateStr = sprintf('%d-%02d-%02d', $year, $month, $dayCount);
                    $isAttend = in_array($dateStr, $attendDates);
                    $isToday = ($dateStr === $today);
                    $cls = $col === 0 ? ' sun' : ($col === 6 ? ' sat' : '');
                ?>
                    <td class="<?= $cls ?><?= $isToday ? ' today' : '' ?>">
                        <span class="cal-day"><?= $dayCount ?></span>
                        <?php if ($isAttend): ?>
                            <span class="cal-check">✅</span>
                        <?php endif; ?>
                    </td>
                <?php $dayCount++; endif; endfor; ?>
            </tr>
            <?php endfor; ?>
            </tbody>
        </table>
        <div class="attend-streak">
            🔥 연속 출석 <strong><?= $streak ?>일째</strong>
            <?php if ($streak >= 7): ?><span style="color:#f59e0b;margin-left:8px">7일 연속 보너스 달성!</span><?php endif; ?>
        </div>
    </div>

    <!-- 출석하기 -->
    <?php if (!$todayDone): ?>
    <div class="attend-card">
        <h3>출석체크하고 포인트 받자!</h3>
        <form method="post" action="<?= nb_url('attendance') ?>" class="attend-form">
            <?= Auth::csrfField() ?>
            <div class="attend-input-row">
                <span class="attend-label">한마디 :</span>
                <?php
                $customMsg = nb_setting('attendance_default_msg');
                if ($customMsg) {
                    $defaultMsg = $customMsg;
                } else {
                    $randomMsgs = [
                        '오늘도 출석! 좋은하루 보내세요',
                        '출석완료! 오늘도 화이팅!',
                        '좋은 아침이에요! 출석합니다',
                        '오늘 하루도 행복하세요!',
                        '출석! 오늘도 좋은 일만 가득하길',
                        '매일매일 출석! 습관이 힘이다',
                        '출석하고 좋은 하루 시작!',
                        '오늘도 건강하고 행복한 하루!',
                        '꾸준히 출석하는 내가 대견해!',
                        '출석완료~ 오늘도 즐거운 하루!',
                    ];
                    $defaultMsg = $randomMsgs[array_rand($randomMsgs)];
                }
                ?>
                <input type="text" name="message" value="<?= nb_e($defaultMsg) ?>" class="attend-input" maxlength="100">
                <button type="submit" class="btn btn-primary">확인</button>
            </div>
            <div class="attend-info">
                → 출석포인트 : <?= nb_setting('point_attendance', '5') ?>점
                (7일 연속 시 보너스 <?= nb_setting('point_attendance_bonus', '20') ?>점)
            </div>
        </form>
    </div>
    <?php else: ?>
    <div class="attend-card" style="text-align:center;color:#059669">
        <strong>✅ 오늘 출석 완료!</strong>
    </div>
    <?php endif; ?>

    <!-- 오늘 출석 랭킹 -->
    <div class="attend-card">
        <h3>[<?= date('Y-m-d') ?>] 출석 랭킹</h3>
        <table class="attend-ranking">
            <thead><tr><th style="width:50px">등수</th><th style="width:80px">시간</th><th>닉네임</th><th>한마디</th><th style="width:60px">포인트</th></tr></thead>
            <tbody>
            <?php foreach ($todayList as $i => $a): ?>
            <tr>
                <td class="text-center" style="font-weight:700;color:<?= $i < 3 ? '#f59e0b' : '#94a3b8' ?>"><?= $i + 1 ?>등</td>
                <td style="font-size:12px;color:#64748b"><?= date('H:i:s', strtotime($a['created_at'])) ?></td>
                <td><?= nb_level_icon($a['level'] ?? 2) ?> <?= nb_e($a['nickname'] ?? '') ?></td>
                <td style="font-size:13px;color:#475569"><?= nb_e($a['message'] ?? '') ?></td>
                <td class="text-center" style="color:#059669;font-weight:600"><?= nb_setting('point_attendance', '5') ?>P</td>
            </tr>
            <?php endforeach; ?>
            <?php if (empty($todayList)): ?>
            <tr><td colspan="5" class="text-center" style="padding:30px;color:#94a3b8">아직 출석한 회원이 없습니다.</td></tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>

</div>
</div>

<style>
.attend-page{max-width:860px;margin:0 auto}
.attend-card{background:#fff;border:1px solid var(--border);border-radius:12px;padding:20px;margin-bottom:12px}
.attend-card h3{font-size:16px;font-weight:700;margin-bottom:14px}

/* 달력 */
.attend-cal-header{display:flex;align-items:center;justify-content:center;gap:16px;margin-bottom:14px;font-size:18px}
.attend-cal{width:100%;border-collapse:collapse;text-align:center}
.attend-cal th{padding:8px;font-size:12px;color:#64748b;border-bottom:1px solid #e2e8f0}
.attend-cal td{padding:10px 4px;vertical-align:top;height:52px;border-bottom:1px solid #f8fafc;position:relative}
.attend-cal .sun,.attend-cal .sun{color:#dc2626}
.attend-cal .sat{color:#2563eb}
.attend-cal .today{background:#fffbeb}
.cal-day{font-size:13px;font-weight:500}
.cal-check{display:block;font-size:18px;margin-top:2px}
.attend-streak{text-align:center;padding:12px 0 0;font-size:14px;color:#475569;border-top:1px solid #f1f5f9;margin-top:8px}

/* 출석 폼 */
.attend-form{margin-top:8px}
.attend-input-row{display:flex;align-items:center;gap:8px}
.attend-label{font-weight:600;font-size:14px;flex-shrink:0}
.attend-input{flex:1;padding:10px 14px;border:1px solid #d1d5db;border-radius:8px;font-size:14px}
.attend-info{margin-top:10px;font-size:12px;color:#94a3b8}

/* 랭킹 */
.attend-ranking{width:100%;border-collapse:collapse}
.attend-ranking th{padding:10px 8px;font-size:12px;color:#64748b;border-bottom:2px solid #e2e8f0;text-align:left}
.attend-ranking td{padding:8px;font-size:13px;border-bottom:1px solid #f8fafc}
.text-center{text-align:center}

@media(max-width:768px){
    .attend-input-row{flex-wrap:wrap}
    .attend-input{width:100%}
    .attend-cal td{height:40px;padding:6px 2px}
    .cal-check{font-size:14px}
}
</style>

<?php require dirname(__DIR__) . '/footer.php'; ?>
