<?php
/**
 * 卡密管理
**/
include("../includes/common.php");
$title='卡密管理';

// ==================== AJAX 请求处理（必须在 head.php 之前） ====================

// 检查登录状态
if($islogin!=1){
	if(isset($_POST['action']) || isset($_POST['do']) || (isset($_GET['do']) && $_GET['do']=='del')){
		exit('{"code":-1,"msg":"未登录"}');
	}
}

// 处理批量操作
if(isset($_POST['ids']) && isset($_POST['do'])){
	$ids = $_POST['ids'];
	$do = $_POST['do'];
	if($do=='del'){
		$quoted = array();
		foreach($ids as $id){
			$quoted[] = "'".intval($id)."'";
		}
		$DB->exec("DELETE FROM pre_card WHERE id IN (" . implode(',', $quoted) . ")");
		exit('{"code":0,"msg":"删除成功"}');
	}
}

// 处理单个删除
if(isset($_GET['do']) && $_GET['do']=='del'){
	$id = intval($_GET['id']);
	$DB->exec("DELETE FROM pre_card WHERE id='{$id}'");
	exit('{"code":0,"msg":"删除成功"}');
}

// 处理生成卡密
if(isset($_POST['action']) && $_POST['action']=='generate'){
	try {
		$count = intval($_POST['count']);
		$type = $_POST['type'];
		$value = intval($_POST['value']);
		$days = intval($_POST['days']);
		
		if($count<1 || $count>100) exit('{"code":-1,"msg":"生成数量必须在1-100之间"}');
		if($value<1) exit('{"code":-1,"msg":"数值必须大于0"}');
		
		$generated = 0;
		for($i=0; $i<$count; $i++){
			$card_code = strtoupper(md5(uniqid(rand(), true)));
			$card_code = substr($card_code, 0, 4).'-'.substr($card_code, 4, 4).'-'.substr($card_code, 8, 4).'-'.substr($card_code, 12, 4);
			
			$storage_quota = 0;
			$traffic_quota = 0;
			if($type=='storage') $storage_quota = $value * 1024 * 1024;
			elseif($type=='traffic') $traffic_quota = $value * 1024 * 1024;
			elseif($type=='both') { $storage_quota = $value * 1024 * 1024; $traffic_quota = $value * 1024 * 1024; }
			
			$admin_uid = 1;
			$result = $DB->exec("INSERT INTO pre_card (card_code,card_type,storage_quota,traffic_quota,expire_days,created_by,created_at) VALUES ('{$card_code}','{$type}',{$storage_quota},{$traffic_quota},{$days},{$admin_uid},NOW())");
			if($result === false) {
				throw new Exception('数据库插入失败');
			}
			$generated++;
		}
		
		exit('{"code":0,"msg":"成功生成 '.$generated.' 张卡密"}');
	} catch (Exception $e) {
		exit('{"code":-1,"msg":"'.$e->getMessage().'"}');
	}
}

// ==================== 页面展示部分 ====================
include './head.php';

if($islogin==1){
}else exit("<script language='javascript'>window.location.href='./login.php';</script>");

function display_status($status){
	if($status=='0')return '<span class="status-badge unused">未使用</span>';
	else return '<span class="status-badge used">已使用</span>';
}

function display_type($type){
	if($type=='storage')return '<span class="type-badge storage">存储扩容</span>';
	elseif($type=='traffic')return '<span class="type-badge traffic">流量包</span>';
	elseif($type=='both')return '<span class="type-badge both">组合套餐</span>';
	else return '<span class="type-badge combo">会员激活</span>';
}

// 获取筛选参数
$kw = isset($_GET['kw']) ? trim($_GET['kw']) : '';
$status = isset($_GET['status']) ? intval($_GET['status']) : -1;
$type = isset($_GET['type']) ? $_GET['type'] : '';

// 构建查询条件
$sql = "1=1";
if($kw){
	$sql .= " AND (card_code LIKE '%{$kw}%' OR used_uid LIKE '%{$kw}%')";
}
if($status>=0){
	$sql .= " AND status={$status}";
}
if($type){
	$sql .= " AND card_type='{$type}'";
}

// 分页
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$pagesize = 20;
$total = $DB->getColumn("SELECT count(*) FROM pre_card WHERE {$sql}");
$pages = ceil($total / $pagesize);
$page = max(1, min($page, $pages));
$offset = ($page - 1) * $pagesize;

// 获取卡密列表
$rs = $DB->query("SELECT * FROM pre_card WHERE {$sql} ORDER BY id DESC LIMIT {$offset},{$pagesize}");

// 格式化文件大小
function formatBytes($bytes){
	if($bytes >= 1073741824) return round($bytes / 1073741824, 2) . ' GB';
	if($bytes >= 1048576) return round($bytes / 1048576, 2) . ' MB';
	if($bytes >= 1024) return round($bytes / 1024, 2) . ' KB';
	return $bytes . ' B';
}
?>
<div class="container">
    <!-- 页面标题 -->
    <div class="page-header-section">
        <div class="page-title">
            <div class="page-title-icon"><i class="fa fa-gift"></i></div>
            <h1>卡密管理</h1>
        </div>
        <div class="page-actions">
            <button type="button" class="btn btn-success" onclick="showGenerateModal()"><i class="fa fa-plus"></i> 生成卡密</button>
        </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-card-header">
                <div class="stat-icon blue">
                    <i class="fa fa-ticket"></i>
                </div>
                <div class="stat-info">
                    <div class="stat-num"><?php echo $DB->getColumn("SELECT count(*) FROM pre_card"); ?></div>
                    <div class="stat-label">卡密总数</div>
                </div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-card-header">
                <div class="stat-icon green">
                    <i class="fa fa-check-circle"></i>
                </div>
                <div class="stat-info">
                    <div class="stat-num"><?php echo $DB->getColumn("SELECT count(*) FROM pre_card WHERE status=0"); ?></div>
                    <div class="stat-label">未使用</div>
                </div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-card-header">
                <div class="stat-icon orange">
                    <i class="fa fa-times-circle"></i>
                </div>
                <div class="stat-info">
                    <div class="stat-num"><?php echo $DB->getColumn("SELECT count(*) FROM pre_card WHERE status=1"); ?></div>
                    <div class="stat-label">已使用</div>
                </div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-card-header">
                <div class="stat-icon red">
                    <i class="fa fa-calendar"></i>
                </div>
                <div class="stat-info">
                    <div class="stat-num"><?php echo $DB->getColumn("SELECT count(*) FROM pre_card WHERE created_at>'".date("Y-m-d")."'"); ?></div>
                    <div class="stat-label">今日生成</div>
                </div>
            </div>
        </div>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-section">
        <form class="filter-form" method="get" action="">
            <div class="filter-group">
                <label>关键词搜索</label>
                <input type="text" class="form-control" name="kw" value="<?php echo htmlspecialchars($kw); ?>" placeholder="卡密/使用者">
            </div>
            <div class="filter-group">
                <label>卡密状态</label>
                <select class="form-control" name="status">
                    <option value="-1">全部状态</option>
                    <option value="0" <?php echo $status===0?'selected':''; ?>>未使用</option>
                    <option value="1" <?php echo $status===1?'selected':''; ?>>已使用</option>
                </select>
            </div>
            <div class="filter-group">
                <label>卡密类型</label>
                <select class="form-control" name="type">
                    <option value="">全部类型</option>
                    <option value="storage" <?php echo $type==='storage'?'selected':''; ?>>存储扩容</option>
                    <option value="traffic" <?php echo $type==='traffic'?'selected':''; ?>>流量包</option>
                    <option value="both" <?php echo $type==='both'?'selected':''; ?>>组合套餐</option>
                    <option value="vip" <?php echo $type==='vip'?'selected':''; ?>>会员激活</option>
                </select>
            </div>
            <div class="filter-actions">
                <button type="submit" class="btn btn-primary"><i class="fa fa-search"></i> 搜索</button>
                <a href="./card.php" class="btn btn-secondary"><i class="fa fa-refresh"></i> 重置</a>
            </div>
        </form>
    </div>

    <!-- 工具栏 -->
    <div class="toolbar-section">
        <div class="batch-actions">
            <button type="button" class="btn-batch delete" onclick="batchAction('del')"><i class="fa fa-trash"></i> 批量删除</button>
        </div>
        <div class="selected-count">已选择 <span id="selectedCount">0</span> 项</div>
    </div>

    <!-- 卡密列表 -->
    <div class="table-section">
        <div class="table-container">
            <table class="data-table" id="cardTable">
                <thead>
                    <tr>
                        <th><input type="checkbox" id="selectAll"></th>
                        <th>ID</th>
                        <th>卡密</th>
                        <th>类型</th>
                        <th>数值</th>
                        <th>有效期</th>
                        <th>状态</th>
                        <th>使用时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php while($row = $rs->fetch()): ?>
                    <tr>
                        <td><input type="checkbox" name="ids[]" value="<?php echo $row['id']; ?>"></td>
                        <td class="col-id"><?php echo $row['id']; ?></td>
                        <td>
                            <code style="font-family: monospace; background: #f3f4f6; padding: 4px 8px; border-radius: 4px; font-size: 13px;"><?php echo htmlspecialchars($row['card_code']); ?></code>
                        </td>
                        <td><?php echo display_type($row['card_type']); ?></td>
                        <td>
                            <?php if($row['storage_quota']>0): ?>
                            <div><i class="fa fa-hdd-o"></i> <?php echo formatBytes($row['storage_quota']); ?></div>
                            <?php endif; ?>
                            <?php if($row['traffic_quota']>0): ?>
                            <div><i class="fa fa-exchange"></i> <?php echo formatBytes($row['traffic_quota']); ?></div>
                            <?php endif; ?>
                            <?php if($row['expire_days']>0): ?>
                            <div><i class="fa fa-clock-o"></i> <?php echo $row['expire_days']; ?> 天</div>
                            <?php endif; ?>
                        </td>
                        <td><?php echo $row['created_at']; ?></td>
                        <td class="col-status"><?php echo display_status($row['status']); ?></td>
                        <td class="col-date">
                            <?php if($row['status']==1): ?>
                            <div class="primary"><?php echo $row['used_time']; ?></div>
                            <div class="secondary"><?php echo htmlspecialchars($row['used_uid']); ?></div>
                            <?php else: ?>
                            <span class="text-muted">-</span>
                            <?php endif; ?>
                        </td>
                        <td class="col-actions">
                            <div class="action-group">
                                <button type="button" class="btn-action delete" onclick="delCard('<?php echo $row['id']; ?>')" title="删除"><i class="fa fa-trash"></i></button>
                            </div>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
        </div>
        
        <!-- 分页 -->
        <div class="pagination-wrapper">
            <div class="pagination-info">共 <?php echo $total; ?> 条记录，第 <?php echo $page; ?>/<?php echo max(1, $pages); ?> 页</div>
            <ul class="pagination">
                <?php if($page>1): ?>
                <li><a href="?page=<?php echo $page-1; ?>&kw=<?php echo urlencode($kw); ?>&status=<?php echo $status; ?>&type=<?php echo $type; ?>"><i class="fa fa-angle-left"></i></a></li>
                <?php else: ?>
                <li class="disabled"><span><i class="fa fa-angle-left"></i></span></li>
                <?php endif; ?>
                
                <?php
                $start = max(1, $page-2);
                $end = min($pages, $page+2);
                for($i=$start; $i<=$end; $i++):
                ?>
                <?php if($i==$page): ?>
                <li class="active"><span><?php echo $i; ?></span></li>
                <?php else: ?>
                <li><a href="?page=<?php echo $i; ?>&kw=<?php echo urlencode($kw); ?>&status=<?php echo $status; ?>&type=<?php echo $type; ?>"><?php echo $i; ?></a></li>
                <?php endif; ?>
                <?php endfor; ?>
                
                <?php if($page<$pages): ?>
                <li><a href="?page=<?php echo $page+1; ?>&kw=<?php echo urlencode($kw); ?>&status=<?php echo $status; ?>&type=<?php echo $type; ?>"><i class="fa fa-angle-right"></i></a></li>
                <?php else: ?>
                <li class="disabled"><span><i class="fa fa-angle-right"></i></span></li>
                <?php endif; ?>
            </ul>
        </div>
    </div>
</div>

<!-- 生成卡密模态框 -->
<div class="custom-modal-overlay" id="generateModal">
    <div class="custom-modal">
        <div class="custom-modal-header">
            <h4><i class="fa fa-plus-circle"></i> 生成卡密</h4>
            <button type="button" class="custom-modal-close" onclick="closeGenerateModal()">&times;</button>
        </div>
        <div class="custom-modal-body">
            <form id="generateForm">
                <div class="form-row">
                    <label class="form-label">生成数量</label>
                    <input type="number" class="form-input" name="count" value="10" min="1" max="100" required>
                    <div class="help-text">一次最多生成100张</div>
                </div>
                <div class="form-row">
                    <label class="form-label">卡密类型</label>
                    <select class="form-select" name="type" id="cardType" onchange="updateValueLabel()">
                        <option value="storage">存储扩容</option>
                        <option value="traffic">流量包</option>
                        <option value="both">组合套餐</option>
                        <option value="vip">会员激活</option>
                    </select>
                </div>
                <div class="form-row">
                    <label class="form-label" id="valueLabel">存储空间 (MB)</label>
                    <div class="input-group">
                        <input type="number" class="form-input" name="value" value="1024" min="1" required>
                        <span class="input-group-addon" id="valueUnit">MB</span>
                    </div>
                </div>
                <div class="form-row">
                    <label class="form-label">有效期 (天)</label>
                    <input type="number" class="form-input" name="days" value="0" min="0">
                    <div class="help-text">0表示永久有效</div>
                </div>
            </form>
        </div>
        <div class="custom-modal-footer">
            <button type="button" class="btn btn-secondary" onclick="closeGenerateModal()">取消</button>
            <button type="button" class="btn btn-success" onclick="generateCards()"><i class="fa fa-check"></i> 确认生成</button>
        </div>
    </div>
</div>

<script>
// 全选/取消全选
document.getElementById('selectAll').addEventListener('change', function() {
    var checkboxes = document.querySelectorAll('input[name="ids[]"]');
    checkboxes.forEach(function(cb) {
        cb.checked = this.checked;
    }, this);
    updateSelectedCount();
});

// 监听单个复选框变化
document.querySelectorAll('input[name="ids[]"]').forEach(function(cb) {
    cb.addEventListener('change', updateSelectedCount);
});

// 更新已选择数量
function updateSelectedCount() {
    var count = document.querySelectorAll('input[name="ids[]"]:checked').length;
    document.getElementById('selectedCount').textContent = count;
}

// 获取选中的ID
function getSelectedIds() {
    var ids = [];
    document.querySelectorAll('input[name="ids[]"]:checked').forEach(function(cb) {
        ids.push(cb.value);
    });
    return ids;
}

// 批量操作
function batchAction(action) {
    var ids = getSelectedIds();
    if(ids.length === 0) {
        alert('请选择要操作的卡密');
        return;
    }
    
    if(!confirm('确定要删除选中的 ' + ids.length + ' 张卡密吗？')) return;
    
    $.post('./card.php', {ids: ids, do: action}, function(data) {
        if(data.code === 0) {
            alert(data.msg);
            location.reload();
        } else {
            alert(data.msg || '操作失败');
        }
    }, 'json').fail(function(xhr, status, error) {
        alert('请求失败: ' + status + ' - ' + error);
    });
}

// 删除卡密
function delCard(id) {
    if(!confirm('确定要删除该卡密吗？')) return;
    $.get('./card.php?do=del&id=' + id, function(data) {
        if(data.code === 0) {
            alert(data.msg);
            location.reload();
        } else {
            alert(data.msg || '删除失败');
        }
    }, 'json').fail(function(xhr, status, error) {
        alert('请求失败: ' + status + ' - ' + error);
    });
}

// 显示生成模态框
function showGenerateModal() {
    document.getElementById('generateModal').classList.add('show');
}

// 关闭生成模态框
function closeGenerateModal() {
    document.getElementById('generateModal').classList.remove('show');
}

// 更新数值标签
function updateValueLabel() {
    var type = document.getElementById('cardType').value;
    var label = document.getElementById('valueLabel');
    var unit = document.getElementById('valueUnit');
    
    if(type === 'storage' || type === 'both') {
        label.textContent = '存储空间 (MB)';
        unit.textContent = 'MB';
    } else if(type === 'traffic') {
        label.textContent = '流量 (MB)';
        unit.textContent = 'MB';
    } else if(type === 'vip') {
        label.textContent = 'VIP天数';
        unit.textContent = '天';
    }
}

// 生成卡密
function generateCards() {
    var form = document.getElementById('generateForm');
    var formData = new FormData(form);
    
    $.ajax({
        url: './card.php',
        type: 'POST',
        data: {
            action: 'generate',
            count: formData.get('count'),
            type: formData.get('type'),
            value: formData.get('value'),
            days: formData.get('days')
        },
        dataType: 'json',
        success: function(data) {
            if(data.code === 0) {
                alert(data.msg);
                closeGenerateModal();
                location.reload();
            } else {
                alert(data.msg || '生成失败');
            }
        },
        error: function(xhr, status, error) {
            alert('请求失败: ' + status + ' - ' + error);
        }
    });
}

// 点击遮罩关闭模态框
document.getElementById('generateModal').addEventListener('click', function(e) {
    if(e.target === this) {
        closeGenerateModal();
    }
});
</script>

</body>
</html>