<?php
/**
 * HuSNS - 签到管理页面
 */
?>
<div class="admin-content signin-page">
    <div class="page-header">
        <h2><i class="fa fa-calendar-check-o"></i> 签到管理</h2>
        <div class="page-tabs">
            <a href="<?php echo Helper::url('pointSignin'); ?>" class="tab <?php echo ($tab ?? 'stats') === 'stats' ? 'active' : ''; ?>">签到统计</a>
            <a href="<?php echo Helper::url('pointSignin', ['tab' => 'config']); ?>" class="tab <?php echo ($tab ?? '') === 'config' ? 'active' : ''; ?>">签到配置</a>
            <a href="<?php echo Helper::url('pointSignin/logs'); ?>" class="tab">签到记录</a>
            <a href="<?php echo Helper::url('pointSignin', ['tab' => 'leaderboard']); ?>" class="tab <?php echo ($tab ?? '') === 'leaderboard' ? 'active' : ''; ?>">签到排行</a>
        </div>
    </div>

    <?php if (isset($_SESSION['flash_success'])): ?>
    <div class="alert alert-success"><?php echo $_SESSION['flash_success']; unset($_SESSION['flash_success']); ?></div>
    <?php endif; ?>

    <?php if (isset($_SESSION['flash_error'])): ?>
    <div class="alert alert-error"><?php echo $_SESSION['flash_error']; unset($_SESSION['flash_error']); ?></div>
    <?php endif; ?>

    <!-- 签到统计卡片 -->
    <div class="signin-stats-grid">
        <div class="signin-stat-card">
            <div class="stat-icon bg-blue"><i class="fa fa-calendar"></i></div>
            <div class="stat-info">
                <div class="stat-value"><?php echo $stats['today_count']; ?></div>
                <div class="stat-label">今日签到</div>
            </div>
        </div>
        <div class="signin-stat-card">
            <div class="stat-icon bg-gray"><i class="fa fa-calendar-minus-o"></i></div>
            <div class="stat-info">
                <div class="stat-value"><?php echo $stats['yesterday_count']; ?></div>
                <div class="stat-label">昨日签到</div>
            </div>
        </div>
        <div class="signin-stat-card">
            <div class="stat-icon bg-purple"><i class="fa fa-calendar-o"></i></div>
            <div class="stat-info">
                <div class="stat-value"><?php echo $stats['month_count']; ?></div>
                <div class="stat-label">本月签到</div>
            </div>
        </div>
        <div class="signin-stat-card">
            <div class="stat-icon bg-green"><i class="fa fa-line-chart"></i></div>
            <div class="stat-info">
                <div class="stat-value"><?php echo $stats['total_count']; ?></div>
                <div class="stat-label">累计签到</div>
            </div>
        </div>
        <div class="signin-stat-card">
            <div class="stat-icon bg-orange"><i class="fa fa-users"></i></div>
            <div class="stat-info">
                <div class="stat-value"><?php echo $stats['total_users']; ?></div>
                <div class="stat-label">签到用户</div>
            </div>
        </div>
    </div>

    <!-- 签到配置 -->
    <?php if (($tab ?? '') === 'config'): ?>
    <div class="signin-config-section">
        <h3><i class="fa fa-cog"></i> 签到奖励配置</h3>
        <form id="signinConfigForm" class="config-form">
            <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token'] ?? ''; ?>">

            <div class="form-group">
                <label class="checkbox-label">
                    <input type="checkbox" name="enabled" value="1" <?php echo !empty($config['enabled']) ? 'checked' : ''; ?>>
                    启用签到功能
                </label>
            </div>

            <div class="form-group">
                <label>基础签到积分</label>
                <input type="number" name="base_points" value="<?php echo $config['base_points'] ?? 10; ?>" min="0" max="999">
                <small>用户每次签到获得的基础积分</small>
            </div>

            <div class="form-group">
                <label>连续签到奖励</label>
                <div class="continuous-bonus-list" id="bonusList">
                    <?php
                    $bonuses = $config['continuous_bonus'] ?? [];
                    if (empty($bonuses)):
                    ?>
                    <div class="bonus-item">
                        <span>连续</span>
                        <input type="number" name="bonus_days[]" value="" min="1" placeholder="天数">
                        <span>天，额外奖励</span>
                        <input type="number" name="bonus_amount[]" value="" min="0" placeholder="积分">
                        <span>积分</span>
                        <button type="button" class="btn btn-sm btn-danger" onclick="removeBonus(this)">删除</button>
                    </div>
                    <?php else: ?>
                        <?php foreach ($bonuses as $bonus): ?>
                        <div class="bonus-item">
                            <span>连续</span>
                            <input type="number" name="bonus_days[]" value="<?php echo $bonus['days']; ?>" min="1" placeholder="天数">
                            <span>天，额外奖励</span>
                            <input type="number" name="bonus_amount[]" value="<?php echo $bonus['bonus']; ?>" min="0" placeholder="积分">
                            <span>积分</span>
                            <button type="button" class="btn btn-sm btn-danger" onclick="removeBonus(this)">删除</button>
                        </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
                <button type="button" class="btn btn-sm btn-default" onclick="addBonus()"><i class="fa fa-plus"></i> 添加连续签到奖励</button>
                <small>设置连续签到达到指定天数时，额外奖励的积分。例如：连续签到7天额外奖励5积分</small>
            </div>

            <div class="form-actions">
                <button type="submit" class="btn btn-primary"><i class="fa fa-save"></i> 保存配置</button>
            </div>
        </form>
    </div>
    <?php elseif (($tab ?? '') === 'leaderboard'): ?>
    <!-- 签到排行简览 -->
    <div class="signin-chart-section">
        <h3><i class="fa fa-trophy"></i> 签到排行榜 TOP 10</h3>
        <div class="leaderboard-preview" id="leaderboardPreview">
            <div class="chart-loading">加载中...</div>
        </div>
        <div style="text-align: center; margin-top: 15px;">
            <a href="<?php echo Helper::url('pointSignin/leaderboard'); ?>" class="btn btn-default">查看完整排行榜 <i class="fa fa-arrow-right"></i></a>
        </div>
    </div>
    <?php else: ?>
    <!-- 30天签到趋势图表 -->
    <div class="signin-chart-section">
        <h3><i class="fa fa-line-chart"></i> 签到趋势（近30天）</h3>
        <div class="chart-container" id="chartContainer">
            <div class="chart-loading">加载中...</div>
        </div>
    </div>
    <?php endif; ?>
</div>

<style>
.signin-page .page-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 20px;
    flex-wrap: wrap;
    gap: 15px;
}

.signin-page .page-header h2 {
    margin: 0;
    font-size: 18px;
    color: #333;
}

.signin-page .page-tabs {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
}

.signin-page .page-tabs .tab {
    padding: 8px 16px;
    background: #f5f5f5;
    border-radius: 4px;
    text-decoration: none;
    color: #666;
    font-size: 13px;
    transition: all 0.2s;
}

.signin-page .page-tabs .tab:hover {
    background: #e8e8e8;
}

.signin-page .page-tabs .tab.active {
    background: #3498db;
    color: #fff;
}

.signin-page .signin-stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
    gap: 15px;
    margin-bottom: 20px;
}

.signin-page .signin-stat-card {
    display: flex;
    align-items: center;
    gap: 14px;
    padding: 18px;
    background: #fff;
    border-radius: 10px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.06);
    transition: transform 0.2s;
}

.signin-page .signin-stat-card:hover {
    transform: translateY(-2px);
}

.signin-page .signin-stat-card .stat-icon {
    width: 44px;
    height: 44px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    color: #fff;
    flex-shrink: 0;
}

.signin-page .signin-stat-card .stat-icon.bg-blue { background: #3498db; }
.signin-page .signin-stat-card .stat-icon.bg-gray { background: #95a5a6; }
.signin-page .signin-stat-card .stat-icon.bg-purple { background: #9b59b6; }
.signin-page .signin-stat-card .stat-icon.bg-green { background: #27ae60; }
.signin-page .signin-stat-card .stat-icon.bg-orange { background: #e67e22; }

.signin-page .signin-stat-card .stat-info {
    flex: 1;
}

.signin-page .signin-stat-card .stat-value {
    font-size: 26px;
    font-weight: 600;
    color: #2c3e50;
    line-height: 1.2;
}

.signin-page .signin-stat-card .stat-label {
    font-size: 13px;
    color: #888;
    margin-top: 3px;
}

.signin-page .signin-chart-section,
.signin-page .signin-config-section {
    background: #fff;
    border-radius: 10px;
    padding: 24px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.06);
}

.signin-page .signin-chart-section h3,
.signin-page .signin-config-section h3 {
    margin: 0 0 20px 0;
    font-size: 16px;
    color: #333;
}

.signin-page .config-form {
    max-width: 600px;
}

.signin-page .config-form .form-group {
    margin-bottom: 22px;
}

.signin-page .config-form .form-group label {
    display: block;
    font-weight: 500;
    margin-bottom: 8px;
    color: #333;
}

.signin-page .config-form .form-group label.checkbox-label {
    display: flex;
    align-items: center;
    gap: 8px;
    cursor: pointer;
}

.signin-page .config-form .form-group input[type="number"] {
    width: 120px;
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
}

.signin-page .config-form .form-group small {
    display: block;
    margin-top: 6px;
    color: #888;
    font-size: 12px;
}

.signin-page .continuous-bonus-list {
    margin-bottom: 12px;
}

.signin-page .bonus-item {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 10px;
    padding: 12px;
    background: #f9f9f9;
    border-radius: 6px;
    flex-wrap: wrap;
}

.signin-page .bonus-item span {
    color: #666;
}

.signin-page .bonus-item input {
    width: 80px !important;
}

.signin-page .form-actions {
    margin-top: 25px;
    padding-top: 20px;
    border-top: 1px solid #eee;
}

/* 图表样式 */
.signin-page .chart-container {
    height: 280px;
    display: flex;
    flex-direction: column;
}

.signin-page .chart-loading {
    text-align: center;
    color: #888;
    padding: 60px;
}

.signin-page .chart-bars {
    display: flex;
    align-items: flex-end;
    justify-content: space-between;
    height: 220px;
    padding: 10px 0;
    border-bottom: 1px solid #eee;
}

.signin-page .chart-bar-wrapper {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    height: 100%;
    justify-content: flex-end;
}

.signin-page .chart-bar {
    width: 10px;
    background: linear-gradient(180deg, #3498db 0%, #69b1ff 100%);
    border-radius: 2px 2px 0 0;
    min-height: 2px;
    transition: height 0.3s ease;
}

.signin-page .chart-bar:hover {
    background: linear-gradient(180deg, #4096ff 0%, #91caff 100%);
}

.signin-page .chart-label {
    font-size: 9px;
    color: #888;
    margin-top: 6px;
}

.signin-page .alert {
    padding: 12px 16px;
    border-radius: 6px;
    margin-bottom: 15px;
}

.signin-page .alert-success {
    background: #d4edda;
    color: #155724;
    border: 1px solid #c3e6cb;
}

.signin-page .alert-error {
    background: #f8d7da;
    color: #721c24;
    border: 1px solid #f5c6cb;
}
</style>

<script>
var csrfToken = '<?php echo $_SESSION['csrf_token'] ?? ''; ?>';

// 添加奖励行
function addBonus() {
    var list = document.getElementById('bonusList');
    var item = document.createElement('div');
    item.className = 'bonus-item';
    item.innerHTML = '<span>连续</span>' +
        '<input type="number" name="bonus_days[]" value="" min="1" placeholder="天数">' +
        '<span>天，额外奖励</span>' +
        '<input type="number" name="bonus_amount[]" value="" min="0" placeholder="积分">' +
        '<span>积分</span>' +
        '<button type="button" class="btn btn-sm btn-danger" onclick="removeBonus(this)">删除</button>';
    list.appendChild(item);
}

// 删除奖励行
function removeBonus(btn) {
    var items = document.querySelectorAll('.bonus-item');
    if (items.length > 1) {
        btn.parentElement.remove();
    } else {
        alert('至少保留一行');
    }
}

// 提交配置
document.getElementById('signinConfigForm')?.addEventListener('submit', function(e) {
    e.preventDefault();

    var formData = new FormData(this);

    // 处理checkbox
    formData.set('enabled', document.querySelector('input[name="enabled"]').checked ? '1' : '0');

    fetch('<?php echo Helper::url('pointSignin/config'); ?>', {
        method: 'POST',
        body: formData
    })
    .then(function(r) { return r.json(); })
    .then(function(data) {
        if (data.code === 0) {
            alert('配置保存成功');
            location.reload();
        } else {
            alert(data.message || '保存失败');
        }
    })
    .catch(function() {
        alert('保存失败');
    });
});

// 加载图表数据
function loadChart() {
    var container = document.getElementById('chartContainer');
    if (!container) return;

    fetch('<?php echo Helper::url('pointSignin/stats'); ?>', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'csrf_token=' + encodeURIComponent(csrfToken)
    })
    .then(function(r) { return r.json(); })
    .then(function(data) {
        if (data.code === 0 && data.data.daily) {
            renderChart(data.data.daily);
        }
    })
    .catch(function() {
        container.innerHTML = '<div class="chart-loading">加载失败</div>';
    });
}

// 渲染图表
function renderChart(dailyData) {
    var container = document.getElementById('chartContainer');
    if (!container || !dailyData.length) return;

    var maxCount = Math.max(...dailyData.map(function(d) { return d.count; }), 10);

    var html = '<div class="chart-bars">';
    dailyData.forEach(function(item) {
        var height = maxCount > 0 ? Math.max((item.count / maxCount) * 100, 2) : 2;
        var date = item.date.substring(5); // MM-DD
        html += '<div class="chart-bar-wrapper">' +
            '<div class="chart-bar" style="height:' + height + '%" title="' + item.date + ': ' + item.count + '人签到"></div>' +
            '<div class="chart-label">' + date + '</div>' +
        '</div>';
    });
    html += '</div>';

    container.innerHTML = html;
}

// 页面加载完成后获取图表
document.addEventListener('DOMContentLoaded', function() {
    var chartSection = document.querySelector('.signin-chart-section');
    if (chartSection) {
        loadChart();
    }
});
</script>
