<?php
/**
 * 芋头CMS
 * ============================================================================
 * 版权所有 2016-2028 沅陵县乌托邦网络服务有限公司，并保留所有权利。
 * 网站地址: http://www.yutoucms.cn
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 芋头 <mxgsf@qq.com>
 * Date: 2026-5-20
 */

$action = isset($_GET['action']) ? $_GET['action'] : 'list';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($action === 'save') {
        $id = intval($_POST['id']);
        $data = [
            'vote_title' => trim($_POST['vote_title']),
            'vote_type' => intval($_POST['vote_type'] ?? 1),
            'vote_options' => json_encode($_POST['vote_options'] ?? [], JSON_UNESCAPED_UNICODE),
            'start_time' => !empty($_POST['start_time']) ? strtotime($_POST['start_time']) : 0,
            'end_time' => !empty($_POST['end_time']) ? strtotime($_POST['end_time']) : 0,
            'is_enabled' => isset($_POST['is_enabled']) ? 1 : 0,
        ];
        if ($id > 0) {
            $db->update('vote', $data, 'id = ?', [$id]);
            addLog('修改', '投票管理', '修改投票 ' . $data['vote_title']);
            echo '<script>alert("保存成功");location.href="?act=vote";</script>';
        } else {
            $data['create_time'] = time();
            $db->insert('vote', $data);
            addLog('添加', '投票管理', '添加投票 ' . $data['vote_title']);
            echo '<script>alert("添加成功");location.href="?act=vote";</script>';
        }
        exit;
    }
    if ($action === 'delete') {
        $id = intval($_POST['id'] ?? 0);
        $v = $db->fetch("SELECT vote_title FROM {$db->table('vote')} WHERE id = ?", [$id]);
        $db->delete('vote', 'id = ?', [$id]);
        addLog('删除', '投票管理', '删除投票 ' . ($v['vote_title'] ?? $id));
        echo json_encode(['code' => 200, 'msg' => '删除成功']);
        exit;
    }
}

if ($action === 'list') {
    $votes = $db->fetchAll("SELECT * FROM {$db->table('vote')} ORDER BY id DESC");
    $totalVotes = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('vote')}")['cnt'];
    $activeVotes = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('vote')} WHERE is_enabled = 1")['cnt'];
    ?>
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-icon" style="background:#eff6ff;color:#2563eb;"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="20" x2="18" y2="10"/><line x1="12" y1="20" x2="12" y2="4"/><line x1="6" y1="20" x2="6" y2="14"/></svg></div>
            <div class="stat-info"><div class="stat-value"><?php echo $totalVotes; ?></div><div class="stat-label">投票总数</div></div>
        </div>
        <div class="stat-card">
            <div class="stat-icon" style="background:#ecfdf5;color:#10b981;"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg></div>
            <div class="stat-info"><div class="stat-value"><?php echo $activeVotes; ?></div><div class="stat-label">进行中</div></div>
        </div>
    </div>
    <div class="filter-bar">
        <a href="?act=vote&action=add" class="btn btn-primary"><svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg> 添加投票</a>
    </div>
    <div class="content-card">
        <?php if (empty($votes)): ?>
        <div class="empty-state">
            <div class="empty-icon"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="20" x2="18" y2="10"/><line x1="12" y1="20" x2="12" y2="4"/><line x1="6" y1="20" x2="6" y2="14"/></svg></div>
            <h3>暂无投票</h3>
            <p>创建第一个投票</p>
            <a href="?act=vote&action=add" class="btn btn-primary">添加投票</a>
        </div>
        <?php else: ?>
        <table class="data-table">
            <thead>
                <tr><th style="width:50px;">ID</th><th>投票主题</th><th style="width:100px;">状态</th><th style="width:150px;">截止时间</th><th style="width:200px;">操作</th></tr>
            </thead>
            <tbody>
                <?php foreach ($votes as $item): ?>
                <tr>
                    <td class="id-cell"><?php echo $item['id']; ?></td>
                    <td style="font-weight:600;"><?php echo htmlspecialchars($item['vote_title']); ?></td>
                    <td>
                        <?php if ($item['is_enabled']): ?>
                        <span class="badge badge-success">进行中</span>
                        <?php else: ?>
                        <span class="badge badge-gray">已结束</span>
                        <?php endif; ?>
                    </td>
                    <td style="font-size:12px;color:#64748b;"><?php echo $item['end_time'] ? date('Y-m-d H:i', $item['end_time']) : '-'; ?></td>
                    <td>
                        <div class="btn-group">
                            <a href="?act=vote&action=edit&id=<?php echo $item['id']; ?>" class="btn btn-sm btn-primary"><svg style="width:12px;height:12px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg> 编辑</a>
                            <a href="javascript:delVote(<?php echo $item['id']; ?>);" class="btn btn-sm btn-danger"><svg style="width:12px;height:12px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg> 删除</a>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <?php endif; ?>
    </div>
    <script>
    function delVote(id) { if (confirm('确定删除?')) { fetch('?act=vote&action=delete', {method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'id='+id}).then(r=>r.json()).then(d=>{alert(d.msg);if(d.code==200)location.reload();}); } }
    </script>
    <?php
}

if ($action === 'add' || $action === 'edit') {
    $editData = ['id'=>'','vote_title'=>'','vote_type'=>1,'vote_options'=>'[]','start_time'=>'','end_time'=>date('Y-m-d', strtotime('+30 days')),'is_enabled'=>1];
    if ($action === 'edit' && isset($_GET['id'])) {
        $editData = $db->fetch("SELECT * FROM {$db->table('vote')} WHERE id = ?", [intval($_GET['id'])]);
        $editData['start_time'] = $editData['start_time'] ? date('Y-m-d', $editData['start_time']) : '';
        $editData['end_time'] = $editData['end_time'] ? date('Y-m-d', $editData['end_time']) : '';
    }
    $isEdit = $action === 'edit';
    $options = json_decode($editData['vote_options'] ?? '[]', true);
    if (!is_array($options) || empty($options)) { $options = [['text'=>'','votes'=>0],['text'=>'','votes'=>0]]; }
    ?>
    <div class="page-container fade-in">
        <div class="page-header">
            <div class="page-title">
                <div class="page-icon"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg></div>
                <div><h1><?php echo $isEdit ? '编辑投票' : '添加投票'; ?></h1><p style="font-size:12px;color:#64748b;margin:0;">填写投票信息</p></div>
            </div>
            <div class="page-actions"><a href="?act=vote" class="btn btn-secondary">&larr; 返回</a></div>
        </div>
        <form method="post" action="?act=vote&action=save">
            <input type="hidden" name="id" value="<?php echo $editData['id']; ?>">
            <div class="form-section">
                <div class="form-section-header"><svg style="width:16px;height:16px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg> 基本信息</div>
                <div class="form-section-body">
                    <div class="form-row">
                        <div class="form-group" style="flex:1;">
                            <label>投票标题 <span class="required">*</span></label>
                            <input type="text" name="vote_title" class="form-control" value="<?php echo htmlspecialchars($editData['vote_title']); ?>" placeholder="请输入投票标题" required>
                        </div>
                        <div class="form-group" style="width:160px;">
                            <label>投票类型</label>
                            <select name="vote_type" class="form-control">
                                <option value="1" <?php echo $editData['vote_type']==1?'selected':''; ?>>单选</option>
                                <option value="2" <?php echo $editData['vote_type']==2?'selected':''; ?>>多选</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group"><label>开始时间</label><input type="date" name="start_time" class="form-control" value="<?php echo $editData['start_time']; ?>"></div>
                        <div class="form-group"><label>截止时间</label><input type="date" name="end_time" class="form-control" value="<?php echo $editData['end_time']; ?>"></div>
                    </div>
                    <div class="form-group">
                        <label>&nbsp;</label>
                        <label style="display:flex;align-items:center;gap:12px;cursor:pointer;padding-top:8px;">
                            <input type="checkbox" name="is_enabled" value="1" <?php echo $editData['is_enabled']?'checked':''; ?> id="statusToggle" style="display:none;">
                            <div id="statusSwitch" style="width:44px;height:24px;background:<?php echo $editData['is_enabled']?'#10b981':'#cbd5e1'; ?>;border-radius:12px;position:relative;transition:all 0.2s;"><div style="width:18px;height:18px;background:#fff;border-radius:50%;position:absolute;top:3px;left:<?php echo $editData['is_enabled']?'23px':'3px'; ?>;transition:all 0.2s;"></div></div>
                            <span id="statusLabel" style="font-weight:500;color:<?php echo $editData['is_enabled']?'#10b981':'#64748b'; ?>;"><?php echo $editData['is_enabled']?'进行中':'已结束'; ?></span>
                        </label>
                    </div>
                </div>
            </div>
            <div class="form-section">
                <div class="form-section-header"><svg style="width:16px;height:16px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg> 投票选项</div>
                <div class="form-section-body">
                    <div id="optionsContainer">
                        <?php $optCount = count($options); for ($i = 0; $i < max(2, $optCount); $i++): ?>
                        <div class="form-row" style="align-items:flex-end;">
                            <div class="form-group" style="flex:1;">
                                <label>选项 <?php echo $i+1; ?></label>
                                <input type="text" name="vote_options[<?php echo $i; ?>][text]" class="form-control" value="<?php echo htmlspecialchars($options[$i]['text'] ?? ''); ?>" placeholder="选项描述">
                            </div>
                            <div class="form-group" style="width:120px;">
                                <label>票数</label>
                                <input type="number" name="vote_options[<?php echo $i; ?>][votes]" class="form-control" value="<?php echo intval($options[$i]['votes'] ?? 0); ?>" min="0">
                            </div>
                        </div>
                        <?php endfor; ?>
                    </div>
                    <div style="margin-top:12px;">
                        <button type="button" onclick="addOption()" class="btn btn-secondary"><svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg> 添加选项</button>
                        <button type="button" onclick="removeOption()" class="btn btn-secondary" style="margin-left:8px;"><svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="5" y1="12" x2="19" y2="12"/></svg> 删除</button>
                    </div>
                </div>
            </div>
            <div class="form-actions"><button type="submit" class="btn btn-success btn-lg">OK <?php echo $isEdit?'保存':'添加'; ?></button><a href="?act=vote" class="btn btn-secondary btn-lg">取消</a></div>
        </form>
    </div>
    <script>
    var optCount = <?php echo max(2, $optCount); ?>;
    function addOption() {
        var container = document.getElementById('optionsContainer');
        var div = document.createElement('div');
        div.className = 'form-row';
        div.style.alignItems = 'flex-end';
        div.innerHTML = '<div class="form-group" style="flex:1;"><label>选项 ' + (optCount + 1) + '</label><input type="text" name="vote_options[' + optCount + '][text]" class="form-control" placeholder="选项描述"></div><div class="form-group" style="width:120px;"><label>票数</label><input type="number" name="vote_options[' + optCount + '][votes]" class="form-control" value="0" min="0"></div>';
        container.appendChild(div);
        optCount++;
    }
    function removeOption() {
        var container = document.getElementById('optionsContainer');
        if (container.children.length > 2) { container.removeChild(container.lastChild); optCount--; }
    }
    document.getElementById('statusToggle').addEventListener('change', function() {
        var sw = document.getElementById('statusSwitch');
        var lb = document.getElementById('statusLabel');
        if (this.checked) { sw.style.background = '#10b981'; sw.querySelector('div').style.left = '23px'; lb.textContent = '进行中'; lb.style.color = '#10b981'; }
        else { sw.style.background = '#cbd5e1'; sw.querySelector('div').style.left = '3px'; lb.textContent = '已结束'; lb.style.color = '#64748b'; }
    });
    </script>
    <?php
}
?>
<script>lucide.createIcons();</script>