<?php
/**
 * 控制台
 */
require_once __DIR__ . '/../includes/config.php';

if (!isAdmin()) {
    redirect(BASE_URL . '/admin/login.php');
}
verify_admin_csrf();
$message = '';
$error = '';

// 处理密码修改
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['change_password'])) {
    $oldPassword = input('old_password', '', 'POST');
    $newPassword = input('new_password', '', 'POST');
    $confirmPassword = input('confirm_password', '', 'POST');
    $captcha = input('captcha', '', 'POST');

    // 验证码校验
    if (!verify_captcha($captcha)) {
        $error = $lang->get('captcha_error');
        clear_captcha();
    } else {
        clear_captcha();
        $adminId = $_SESSION['admin'];
        $admin = $db->fetch($db->query("SELECT password FROM admins WHERE id = ?", [$adminId]));

        if (!password_verify($oldPassword, $admin['password'])) {
            $error = '原密码错误';
        } elseif (strlen($newPassword) < 6) {
            $error = '新密码至少6位';
        } elseif ($newPassword !== $confirmPassword) {
            $error = '两次输入的新密码不一致';
        } else {
            $hashed = password_hash($newPassword, PASSWORD_DEFAULT);
            $db->query("UPDATE admins SET password = ? WHERE id = ?", [$hashed, $adminId]);
            $message = '密码修改成功，请重新登录';
            unset($_SESSION['admin']);
            redirect(BASE_URL . '/admin/login.php');
        }
    }
}

// 统计信息
$novelCount = $db->fetch($db->query("SELECT COUNT(*) as cnt FROM novels"))['cnt'];
$userCount = $db->fetch($db->query("SELECT COUNT(*) as cnt FROM users"))['cnt'];
$chapterCount = $db->fetch($db->query("SELECT COUNT(*) as cnt FROM chapters"))['cnt'];
$blockCount = $db->fetch($db->query("SELECT COUNT(*) as cnt FROM diy_blocks"))['cnt'];
$totalViews = $db->fetch($db->query("SELECT SUM(views) as total FROM novels"))['total'] ?? 0;
$totalFavorites = $db->fetch($db->query("SELECT SUM(favorites) as total FROM novels"))['total'] ?? 0;

// 今日签到相关
$todaySignCount = $db->fetch($db->query("SELECT COUNT(DISTINCT user_id) as cnt FROM gold_logs WHERE type = 'sign' AND DATE(created_at) = CURDATE()"))['cnt'] ?? 0;
$todaySignGold = $db->fetch($db->query("SELECT SUM(gold_change) as total FROM gold_logs WHERE type = 'sign' AND DATE(created_at) = CURDATE()"))['total'] ?? 0;
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=yes">
    <title>管理后台</title>
    <link rel="stylesheet" href="../assets/css/admin.css">
    <link rel="stylesheet" href="/assets/fontawesome/css/all.min.css">
    <style>
        /* 统计卡片区域 */
        .stats {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 1rem;
            margin-bottom: 2rem;
        }
        .stat-box {
            background: white;
            border-radius: 20px;
            padding: 1rem;
            text-align: center;
            box-shadow: 0 1px 3px rgba(0,0,0,0.05);
            border: 1px solid var(--gray-200);
            transition: transform 0.2s;
        }
        .stat-box:hover {
            transform: translateY(-2px);
        }
        .stat-number {
            font-size: 1.8rem;
            font-weight: bold;
            color: var(--primary);
        }
        .stat-label {
            font-size: 0.8rem;
            color: var(--gray-600);
        }
        /* 手机端自适应：小于768px时每行2个，小于480px时每行1个 */
        @media (max-width: 768px) {
            .stats {
                grid-template-columns: repeat(2, 1fr);
                gap: 0.8rem;
            }
            .stat-number {
                font-size: 1.4rem;
            }
        }
        @media (max-width: 480px) {
            .stats {
                grid-template-columns: 1fr;
                gap: 0.6rem;
            }
        }

        /* 管理员密码修改卡片样式 */
        .admin-card {
            background: white;
            border-radius: 20px;
            border: 1px solid var(--gray-200);
            margin-bottom: 1.5rem;
            overflow: hidden;
        }
        .admin-card-header {
            background: var(--gray-50);
            padding: 1rem 1.5rem;
            border-bottom: 1px solid var(--gray-200);
            font-weight: 600;
        }
        .admin-card-body {
            padding: 1.5rem;
        }
        .form-row {
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            gap: 1rem;
            margin-bottom: 1rem;
        }
        .form-row label {
            width: 100px;
            font-weight: 500;
        }
        .form-row input {
            flex: 1;
            min-width: 200px;
            padding: 0.5rem;
            border: 1px solid var(--gray-300);
            border-radius: 8px;
        }
        .captcha-row {
            display: flex;
            gap: 10px;
            align-items: center;
        }
        .captcha-img {
            height: 38px;
            cursor: pointer;
            border-radius: 6px;
        }
        .btn-primary {
            background: var(--primary);
            color: white;
            border: none;
            padding: 0.5rem 1.2rem;
            border-radius: 30px;
            cursor: pointer;
        }
        .alert {
            background: #d4edda;
            color: #155724;
            padding: 0.7rem;
            border-radius: 10px;
            margin-bottom: 1rem;
        }
        .error {
            background: #f8d7da;
            color: #721c24;
            padding: 0.7rem;
            border-radius: 10px;
            margin-bottom: 1rem;
        }
        @media (max-width: 640px) {
            .form-row {
                flex-direction: column;
                align-items: flex-start;
            }
            .form-row label {
                width: auto;
            }
            .form-row input {
                width: 100%;
                min-width: auto;
            }
        }
    </style>
</head>
<body>
    <div class="admin-container">
        <?php include 'sidebar.php'; ?>
        <div class="content">
            <h1><i class="fas fa-tachometer-alt"></i> 控制台</h1>

            <?php if ($message): ?>
                <div class="alert"><?= h($message) ?></div>
            <?php endif; ?>
            <?php if ($error): ?>
                <div class="error"><?= h($error) ?></div>
            <?php endif; ?>

            <!-- 统计卡片 -->
            <div class="stats">
                <div class="stat-box">
                    <div class="stat-number"><?= number_format($novelCount) ?></div>
                    <div class="stat-label">小说数量</div>
                </div>
                <div class="stat-box">
                    <div class="stat-number"><?= number_format($userCount) ?></div>
                    <div class="stat-label">用户数量</div>
                </div>
                <div class="stat-box">
                    <div class="stat-number"><?= number_format($chapterCount) ?></div>
                    <div class="stat-label">章节数量</div>
                </div>
                <div class="stat-box">
                    <div class="stat-number"><?= number_format($blockCount) ?></div>
                    <div class="stat-label">Diy缓存块</div>
                </div>
                <div class="stat-box">
                    <div class="stat-number"><?= number_format($totalViews) ?></div>
                    <div class="stat-label">总阅读次数</div>
                </div>
                <div class="stat-box">
                    <div class="stat-number"><?= number_format($totalFavorites) ?></div>
                    <div class="stat-label">总收藏数</div>
                </div>
                <div class="stat-box">
                    <div class="stat-number"><?= number_format($todaySignCount) ?></div>
                    <div class="stat-label">今日签到人次</div>
                </div>
                <div class="stat-box">
                    <div class="stat-number"><?= number_format($todaySignGold) ?></div>
                    <div class="stat-label">今日赠送金币</div>
                </div>
            </div>

            <!-- 管理员密码修改 -->
            <div class="admin-card">
                <div class="admin-card-header"><i class="fas fa-key"></i> 修改管理员密码</div>
                <div class="admin-card-body">
                    <form method="post">
                        <?= csrf_field() ?>
                        <div class="form-row">
                            <label>原密码</label>
                            <input type="password" name="old_password" required>
                        </div>
                        <div class="form-row">
                            <label>新密码</label>
                            <input type="password" name="new_password" required>
                        </div>
                        <div class="form-row">
                            <label>确认新密码</label>
                            <input type="password" name="confirm_password" required>
                        </div>
                        <div class="form-row">
                            <label>验证码</label>
                            <div class="captcha-row">
                                <input type="text" name="captcha" required style="width:120px;">
                                <img src="/api/captcha.php" class="captcha-img" onclick="this.src='/api/captcha.php?'+Math.random()" alt="验证码">
                            </div>
                        </div>
                        <div class="form-row">
                            <label></label>
                            <button type="submit" name="change_password" class="btn-primary"><i class="fas fa-save"></i> 修改密码</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</body>
</html>