<?php
require_once 'config.php';
requireEncryptLogin();

$user = getEncryptUser();
$has_permission = hasEncryptPermission($user);

// ========== 处理邮件通知开关 ==========
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['email_notify_action'])) {
    $notify = isset($_POST['email_notify']) ? 1 : 0;
    $db->query("UPDATE users SET email_notify = $notify WHERE id = {$user['id']}");
    $user = getEncryptUser();
    header('Location: /encrypt/user.php');
    exit;
}
// ========== 处理结束 ==========

// 获取加密历史
$history = $db->fetchAll("SELECT * FROM encrypt_history WHERE user_id = {$user['id']} ORDER BY id DESC LIMIT 20");

// 获取服务购买记录
$service = $db->fetchOne("SELECT * FROM encrypt_services WHERE user_id = {$user['id']} AND status = 1");
?>
<?php include 'header.php'; ?>
<div class="encrypt-container">
    <h2>用户中心</h2>
    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; margin-top: 30px;">
        <div class="info-card" style="background: var(--bg-primary); border-radius: 20px; padding: 20px; border: 1px solid var(--border-color);">
            <h3>账户信息</h3>
            <p>用户名：<?php echo htmlspecialchars($user['username']); ?></p>
            <p>邮箱：<?php echo htmlspecialchars($user['email']); ?></p>
            <p>余额：¥<?php echo number_format($user['balance'], 2); ?></p>
            <p>会员类型：
                <?php if ($user['role'] == 'admin'): ?>管理员（免费）
                <?php elseif ($user['is_agent'] == 1): ?>代理商（免费）
                <?php elseif ($has_permission): ?>已购买加密服务
                <?php else: ?>普通用户（未购买）
                <?php endif; ?>
            </p>
            <div style="margin-top: 15px;">
                <a href="/encrypt/buy.php" class="btn btn-primary">购买服务</a>
            </div>
        </div>
        <div class="service-card" style="background: var(--bg-primary); border-radius: 20px; padding: 20px; border: 1px solid var(--border-color);">
            <h3>加密服务状态</h3>
            <?php 
            $service = getUserEncryptService($user);
            $remaining = getServiceRemainingDays($service);
            ?>
            <?php if ($has_permission): ?>
                <p style="color: #10b981;">✅ 已激活</p>
                <?php if ($service && $service['expire_date']): ?>
                    <p>到期时间：<?php echo date('Y-m-d H:i:s', strtotime($service['expire_date'])); ?></p>
                    <p>剩余天数：
                        <strong style="color: <?php echo $remaining <= 7 ? '#ef4444' : '#10b981'; ?>;">
                            <?php echo $remaining; ?> 天
                        </strong>
                        <?php if ($remaining <= 7 && $remaining > 0): ?>
                            <span style="color: #ef4444;">⚠️ 即将到期</span>
                        <?php elseif ($remaining <= 0): ?>
                            <span style="color: #ef4444;">⚠️ 已过期</span>
                        <?php endif; ?>
                    </p>
                <?php else: ?>
                    <p>🎉 永久有效</p>
                <?php endif; ?>
                <div style="margin-top: 15px; display: flex; gap: 10px; flex-wrap: wrap;">
                    <a href="/encrypt/encrypt.php" class="btn btn-primary">开始加密</a>
                    <a href="/encrypt/buy.php" class="btn btn-secondary">续费/升级</a>
                </div>
            <?php else: ?>
                <p style="color: #ef4444;">❌ 未激活</p>
                <p>请购买加密服务后使用</p>
                <a href="/encrypt/buy.php" class="btn btn-primary">立即购买</a>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- 通知设置 -->
<div style="margin-top: 30px;">
    <div class="info-card" style="background: var(--bg-primary); border-radius: 20px; padding: 20px; border: 1px solid var(--border-color);">
        <h3>🔔 通知设置</h3>
        <form method="POST" action="" id="notifyForm">
            <input type="hidden" name="email_notify_action" value="1">
            <label style="display: flex; align-items: center; gap: 10px; cursor: pointer; padding: 5px 0;">
                <input type="checkbox" name="email_notify" value="1" <?php echo ($user['email_notify'] ?? 1) ? 'checked' : ''; ?> onchange="document.getElementById('notifyForm').submit();">
                <span>📧 接收邮件通知</span>
                <span style="font-size: 12px; color: var(--text-muted);">（购买成功、服务到期提醒等）</span>
            </label>
        </form>
        <?php if (empty($user['email'])): ?>
            <p style="color: #ef4444; font-size: 12px; margin-top: 10px;">⚠️ 您尚未绑定邮箱，无法接收邮件通知</p>
        <?php endif; ?>
    </div>
</div>
    
    <?php if (!empty($history)): ?>
    <div style="margin-top: 40px;">
        <h3>加密历史记录</h3>
        <div class="table-container" style="overflow-x: auto;">
            <table class="data-table" style="width: 100%;">
                <thead>
                    <tr>
                        <th>文件名</th>
                        <th>原始大小</th>
                        <th>加密后大小</th>
                        <th>时间</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($history as $item): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($item['original_name']); ?></td>
                            <td><?php echo $item['file_size'] ? round($item['file_size']/1024,2).' KB' : '-'; ?></td>
                            <td><?php echo $item['encrypted_size'] ? round($item['encrypted_size']/1024,2).' KB' : '-'; ?></td>
                            <td><?php echo $item['created_at']; ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>
</div>
<?php include 'footer.php'; ?>