<?php
$user_id = $_SESSION['user_id'];
$page = isset($_GET['p']) ? intval($_GET['p']) : 1;
$perpage = 15;

// 获取总数
$total_result = $db->query("SELECT COUNT(*) as cnt FROM tickets WHERE user_id = $user_id");
$total = $total_result->fetch_assoc()['cnt'];
$offset = ($page - 1) * $perpage;

// 获取工单列表
$tickets = $db->fetchAll("
    SELECT * FROM tickets 
    WHERE user_id = $user_id 
    ORDER BY 
        CASE status 
            WHEN 'open' THEN 1 
            WHEN 'processing' THEN 2 
            ELSE 3 
        END,
        id DESC 
    LIMIT $offset, $perpage
");
?>

<div class="tickets-container">
    <div class="page-header">
        <h2>我的工单</h2>
        <button class="btn btn-primary" id="newTicketBtn">+ 新建工单</button>
    </div>
    
    <div class="table-container">
        <table class="data-table">
            <thead>
                <tr>
                    <th>标题</th>
                    <th>状态</th>
                    <th>优先级</th>
                    <th>创建时间</th>
                    <th>最后更新</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                <?php if (empty($tickets)): ?>
                    <tr><td colspan="6" style="text-align: center;">暂无工单</td></tr>
                <?php else: ?>
                    <?php foreach ($tickets as $ticket): ?>
                        <tr>
                            <td><strong><?php echo htmlspecialchars($ticket['title']); ?></strong></td>
                            <td>
                                <span class="status-badge status-<?php echo $ticket['status']; ?>">
                                    <?php 
                                    $status_map = ['open' => '待处理', 'processing' => '处理中', 'closed' => '已关闭'];
                                    echo $status_map[$ticket['status']] ?? $ticket['status'];
                                    ?>
                                </span>
                            </td>
                            <td>
                                <span class="priority-<?php echo $ticket['priority']; ?>">
                                    <?php 
                                    $priority_map = ['low' => '低', 'medium' => '中', 'high' => '高'];
                                    echo $priority_map[$ticket['priority']] ?? $ticket['priority'];
                                    ?>
                                </span>
                            </td>
                            <td><?php echo $ticket['created_at']; ?></td>
                            <td><?php echo $ticket['updated_at']; ?></td>
                            <td>
<a href="?page=ticket_view&id=<?php echo $ticket['id']; ?>" class="btn-small">查看详情</a></td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <!-- 分页 -->
    <?php if ($total > $perpage): ?>
        <div class="pagination">
            <?php
            $total_pages = ceil($total / $perpage);
            for ($i = 1; $i <= $total_pages; $i++):
            ?>
                <a href="?page=tickets&p=<?php echo $i; ?>" class="page-link <?php echo $i == $page ? 'active' : ''; ?>">
                    <?php echo $i; ?>
                </a>
            <?php endfor; ?>
        </div>
    <?php endif; ?>
</div>

<!-- 新建工单弹窗 -->
<div id="newTicketModal" class="modal" style="display: none;">
    <div class="modal-content" style="max-width: 500px;">
        <div class="modal-header">
            <h3>新建工单</h3>
            <span class="close">&times;</span>
        </div>
        <form id="newTicketForm" method="POST">
            <div class="modal-body">
                <div class="form-group">
                    <label>标题</label>
                    <input type="text" name="title" required placeholder="请输入工单标题">
                </div>
                <div class="form-group">
                    <label>优先级</label>
                    <select name="priority">
                        <option value="low">低</option>
                        <option value="medium" selected>中</option>
                        <option value="high">高</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>问题描述</label>
                    <textarea name="content" rows="5" required placeholder="请详细描述您的问题..."></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary cancel-btn">取消</button>
                <button type="submit" class="btn btn-primary">提交工单</button>
            </div>
        </form>
    </div>
</div>

<style>
.tickets-container .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
}
.status-badge {
    padding: 3px 8px;
    border-radius: 20px;
    font-size: 12px;
}
.status-open, .status-processing {
    background: #d1fae5;
    color: #065f46;
}
.status-closed {
    background: #fee2e2;
    color: #991b1b;
}
.priority-low {
    color: #6b7280;
}
.priority-medium {
    color: #f59e0b;
}
.priority-high {
    color: #ef4444;
}
.modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 10000;
}
.modal-content {
    background: var(--bg-primary);
    border-radius: var(--radius-md);
    width: 90%;
    max-width: 500px;
}
.modal-header {
    padding: 15px 20px;
    border-bottom: 1px solid var(--border-color);
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.modal-body {
    padding: 20px;
}
.modal-footer {
    padding: 15px 20px;
    border-top: 1px solid var(--border-color);
    display: flex;
    gap: 10px;
    justify-content: flex-end;
}
.close {
    cursor: pointer;
    font-size: 24px;
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const modal = document.getElementById('newTicketModal');
    const newBtn = document.getElementById('newTicketBtn');
    
    function closeModal() {
        modal.style.display = 'none';
    }
    
    newBtn.addEventListener('click', function() {
        modal.style.display = 'flex';
    });
    
    document.querySelectorAll('.close, .cancel-btn').forEach(el => {
        el.addEventListener('click', closeModal);
    });
    
    // 在 tickets.php 中找到这部分，确保 URL 正确
document.getElementById('newTicketForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const formData = new FormData(this);
    
    // 修改这里：确保 URL 正确
    fetch(window.location.pathname + '?page=tickets&action=create', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            window.showToast('工单提交成功', 'success');
            setTimeout(() => location.reload(), 1000);
        } else {
            window.showToast(data.message || '提交失败', 'error');
        }
        closeModal();
    })
    .catch(error => {
        console.error('错误:', error);
        window.showToast('网络错误，请稍后重试', 'error');
        closeModal();
    });
});
    
    modal.addEventListener('click', function(e) {
        if (e.target === modal) closeModal();
    });
});
</script>

<?php
// 处理新建工单
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['action']) && $_GET['action'] === 'create') {
    header('Content-Type: application/json');
    $title = trim($_POST['title'] ?? '');
    $content = trim($_POST['content'] ?? '');
    $priority = $_POST['priority'] ?? 'medium';
    
    if (empty($title) || empty($content)) {
        echo json_encode(['success' => false, 'message' => '请填写完整信息']);
        exit;
    }
    
    $title = $db->escape($title);
    $content = $db->escape($content);
    $db->query("INSERT INTO tickets (user_id, title, content, priority) VALUES ($user_id, '$title', '$content', '$priority')");
    
    echo json_encode(['success' => true]);
    exit;
}
?>