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

// ========== 处理新建工单（必须在任何输出之前） ==========
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['action']) && $_GET['action'] === 'create') {
    
    
    
    $title = $db->escape($title);
    $content = $db->escape($content);
    $db->query("INSERT INTO tickets (user_id, title, content, priority) VALUES ($user_id, '$title', '$content', '$priority')");
    
    
}

// 获取总数
$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
");

// 统计数据
$stats = [
    'total' => $total,
    'open' => $db->fetchOne("SELECT COUNT(*) as cnt FROM tickets WHERE user_id = $user_id AND status = 'open'")['cnt'],
    'processing' => $db->fetchOne("SELECT COUNT(*) as cnt FROM tickets WHERE user_id = $user_id AND status = 'processing'")['cnt'],
    'closed' => $db->fetchOne("SELECT COUNT(*) as cnt FROM tickets WHERE user_id = $user_id AND status = 'closed'")['cnt'],
];
?>

<div class="tickets-container">
    <!-- 页面头部 -->
    <div class="page-header">
        <h2>
            <img src="https://api.iconify.design/mdi:ticket.svg?color=%23667eea" width="26" height="26" style="vertical-align: middle; margin-right: 10px;" alt="">
            我的工单
        </h2>
        <button class="btn btn-primary" id="newTicketBtn">
            <img src="https://api.iconify.design/mdi:plus.svg?color=white" width="18" height="18" style="margin-right: 6px;" alt="">
            新建工单
        </button>
    </div>
    
    <!-- 统计卡片 -->
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-icon">
                <img src="https://api.iconify.design/mdi:ticket.svg?color=%23667eea" width="28" height="28" alt="">
            </div>
            <div class="stat-content">
                <span class="stat-value"><?php echo $stats['total']; ?></span>
                <span class="stat-label">总工单</span>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">
                <img src="https://api.iconify.design/mdi:alert-circle.svg?color=%23f59e0b" width="28" height="28" alt="">
            </div>
            <div class="stat-content">
                <span class="stat-value"><?php echo $stats['open']; ?></span>
                <span class="stat-label">待处理</span>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">
                <img src="https://api.iconify.design/mdi:progress-clock.svg?color=%238b5cf6" width="28" height="28" alt="">
            </div>
            <div class="stat-content">
                <span class="stat-value"><?php echo $stats['processing']; ?></span>
                <span class="stat-label">处理中</span>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">
                <img src="https://api.iconify.design/mdi:check-circle.svg?color=%2310b981" width="28" height="28" alt="">
            </div>
            <div class="stat-content">
                <span class="stat-value"><?php echo $stats['closed']; ?></span>
                <span class="stat-label">已关闭</span>
            </div>
        </div>
    </div>
    
    <!-- 工单列表 -->
    <div class="table-wrapper">
        <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">
                            <div class="empty-state">
                                <img src="https://api.iconify.design/mdi:ticket-outline.svg?color=%239ca3af" width="48" height="48" alt="">
                                <p>暂无工单</p>
                                <span>点击"新建工单"提交您的问题</span>
                            </div>
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($tickets as $ticket): ?>
                        <tr>
                            <td>
                                <div class="ticket-title">
                                    <img src="https://api.iconify.design/mdi:ticket.svg?color=%23667eea" width="16" height="16" alt="">
                                    <strong><?php echo htmlspecialchars($ticket['title']); ?></strong>
                                </div>
                            </td>
                            <td>
                                <span class="status-badge status-<?php echo $ticket['status']; ?>">
                                    <span class="status-dot"></span>
                                    <?php 
                                    $status_map = ['open' => '待处理', 'processing' => '处理中', 'closed' => '已关闭'];
                                    echo $status_map[$ticket['status']] ?? $ticket['status'];
                                    ?>
                                </span>
                            </td>
                            <td>
                                <span class="priority-badge priority-<?php echo $ticket['priority']; ?>">
                                    <?php 
                                    $priority_map = [
                                        'low' => ['icon' => 'chevron-down', 'label' => '低', 'color' => '10b981'],
                                        'medium' => ['icon' => 'minus', 'label' => '中', 'color' => 'f59e0b'],
                                        'high' => ['icon' => 'chevron-up', 'label' => '高', 'color' => 'ef4444']
                                    ];
                                    $p = $priority_map[$ticket['priority']] ?? ['icon' => 'circle', 'label' => $ticket['priority'], 'color' => '6b7280'];
                                    ?>
                                    <img src="https://api.iconify.design/mdi:<?php echo $p['icon']; ?>.svg?color=%23<?php echo $p['color']; ?>" width="14" height="14" alt="">
                                    <?php echo $p['label']; ?>
                                </span>
                            </td>
                            <td>
                                <span class="datetime">
                                    <img src="https://api.iconify.design/mdi:calendar.svg?color=%236b7280" width="14" height="14" style="margin-right: 4px;" alt="">
                                    <?php echo date('Y-m-d H:i', strtotime($ticket['created_at'])); ?>
                                </span>
                            </td>
                            <td>
                                <span class="datetime">
                                    <img src="https://api.iconify.design/mdi:clock-outline.svg?color=%236b7280" width="14" height="14" style="margin-right: 4px;" alt="">
                                    <?php echo date('Y-m-d H:i', strtotime($ticket['updated_at'])); ?>
                                </span>
                            </td>
                            <td>
                                <a href="?page=ticket_view&id=<?php echo $ticket['id']; ?>" class="btn-view">
                                    <img src="https://api.iconify.design/mdi:eye.svg?color=%23667eea" width="16" height="16" style="margin-right: 4px;" alt="">
                                    查看详情
                                </a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <!-- 分页 -->
    <?php if ($total > $perpage): ?>
        <div class="pagination">
            <?php if ($page > 1): ?>
                <a href="?page=tickets&p=<?php echo $page - 1; ?>" class="page-link page-prev">
                    <img src="https://api.iconify.design/mdi:chevron-left.svg?color=currentColor" width="16" height="16" alt="">
                </a>
            <?php endif; ?>
            
            <?php
            $total_pages = ceil($total / $perpage);
            $start_page = max(1, $page - 2);
            $end_page = min($total_pages, $page + 2);
            
            if ($start_page > 1): ?>
                <a href="?page=tickets&p=1" class="page-link">1</a>
                <?php if ($start_page > 2): ?>
                    <span class="page-ellipsis">...</span>
                <?php endif; ?>
            <?php endif; ?>
            
            <?php for ($i = $start_page; $i <= $end_page; $i++): ?>
                <a href="?page=tickets&p=<?php echo $i; ?>" class="page-link <?php echo $i == $page ? 'active' : ''; ?>">
                    <?php echo $i; ?>
                </a>
            <?php endfor; ?>
            
            <?php if ($end_page < $total_pages): ?>
                <?php if ($end_page < $total_pages - 1): ?>
                    <span class="page-ellipsis">...</span>
                <?php endif; ?>
                <a href="?page=tickets&p=<?php echo $total_pages; ?>" class="page-link"><?php echo $total_pages; ?></a>
            <?php endif; ?>
            
            <?php if ($page < $total_pages): ?>
                <a href="?page=tickets&p=<?php echo $page + 1; ?>" class="page-link page-next">
                    <img src="https://api.iconify.design/mdi:chevron-right.svg?color=currentColor" width="16" height="16" alt="">
                </a>
            <?php endif; ?>
        </div>
    <?php endif; ?>
</div>

<!-- 新建工单弹窗 -->
<div id="newTicketModal" class="modal" style="display: none;">
    <div class="modal-content">
        <div class="modal-header">
            <h3>
                <img src="/assets/svg/ticket.svg" width="20" height="20" style="margin-right: 8px;" alt="">
                新建工单
            </h3>
            <button type="button" class="modal-close">
                <img src="https://api.iconify.design/mdi:close.svg?color=%239ca3af" width="20" height="20" alt="">
            </button>
        </div>
        <form id="newTicketForm" method="POST">
            <div class="modal-body">
                <div class="form-group">
                    <label>
                        <img src="https://api.iconify.design/mdi:format-title.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">
                        标题 <span class="required">*</span>
                    </label>
                    <input type="text" name="title" required placeholder="请输入工单标题">
                </div>
                <div class="form-group">
                    <label>
                        <img src="https://api.iconify.design/mdi:flag.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">
                        优先级
                    </label>
                    <select name="priority">
                        <option value="low">低</option>
                        <option value="medium" selected>中</option>
                        <option value="high">高</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>
                        <img src="https://api.iconify.design/mdi:text-box.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">
                        问题描述 <span class="required">*</span>
                    </label>
                    <textarea name="content" rows="5" required placeholder="请详细描述您的问题..."></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary cancel-btn">
                    <img src="https://api.iconify.design/mdi:close.svg?color=currentColor" width="16" height="16" style="margin-right: 4px;" alt="">
                    取消
                </button>
                <button type="submit" class="btn btn-primary">
                    <img src="https://api.iconify.design/mdi:send.svg?color=white" width="16" height="16" style="margin-right: 4px;" alt="">
                    提交工单
                </button>
            </div>
        </form>
    </div>
</div>

<style>
/* 基础变量 */
:root {
    --primary-color: #667eea;
    --primary-hover: #5a67d8;
    --danger-color: #ef4444;
    --success-color: #10b981;
    --warning-color: #f59e0b;
    --bg-primary: #ffffff;
    --bg-secondary: #f9fafb;
    --text-primary: #1f2937;
    --text-secondary: #6b7280;
    --text-muted: #9ca3af;
    --border-color: #e5e7eb;
    --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
    --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
    --radius-sm: 8px;
    --radius-md: 12px;
    --radius-lg: 16px;
}

.tickets-container {
    max-width: 100%;
    padding: 4px;
}

/* 页面头部 */
.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 28px;
    flex-wrap: wrap;
    gap: 16px;
}
.page-header h2 {
    display: flex;
    align-items: center;
    font-size: 24px;
    font-weight: 600;
    color: var(--text-primary);
    margin: 0;
}

/* 按钮 */
.btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    padding: 10px 20px;
    border-radius: var(--radius-md);
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    border: 1px solid transparent;
}
.btn-primary {
    background: var(--primary-color);
    color: white;
    box-shadow: 0 2px 4px rgba(102, 126, 234, 0.2);
}
.btn-primary:hover {
    background: var(--primary-hover);
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}
.btn-secondary {
    background: var(--bg-primary);
    color: var(--text-primary);
    border-color: var(--border-color);
}
.btn-secondary:hover {
    background: var(--bg-secondary);
}
.btn-view {
    display: inline-flex;
    align-items: center;
    padding: 6px 14px;
    background: var(--bg-secondary);
    border-radius: var(--radius-sm);
    font-size: 13px;
    color: var(--primary-color);
    text-decoration: none;
    transition: all 0.2s;
}
.btn-view:hover {
    background: var(--primary-color);
    color: white;
}
.btn-view:hover img {
    filter: brightness(0) invert(1);
}

/* 统计卡片 */
.stats-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 20px;
    margin-bottom: 28px;
}
.stat-card {
    background: var(--bg-primary);
    border-radius: var(--radius-lg);
    padding: 20px;
    border: 1px solid var(--border-color);
    display: flex;
    align-items: center;
    gap: 16px;
    transition: all 0.2s;
    box-shadow: var(--shadow-sm);
}
.stat-card:hover {
    box-shadow: var(--shadow-md);
    transform: translateY(-2px);
}
.stat-icon {
    width: 52px;
    height: 52px;
    border-radius: var(--radius-md);
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(102, 126, 234, 0.05) 100%);
}
.stat-content {
    display: flex;
    flex-direction: column;
}
.stat-value {
    font-size: 26px;
    font-weight: 700;
    color: var(--text-primary);
    line-height: 1.2;
}
.stat-label {
    font-size: 13px;
    color: var(--text-muted);
    margin-top: 4px;
}

/* 表格 */
.table-wrapper {
    overflow-x: auto;
    background: var(--bg-primary);
    border-radius: var(--radius-lg);
    border: 1px solid var(--border-color);
    box-shadow: var(--shadow-sm);
}
.data-table {
    width: 100%;
    border-collapse: collapse;
    min-width: 800px;
}
.data-table th {
    padding: 16px 16px;
    text-align: left;
    font-weight: 600;
    font-size: 13px;
    color: var(--text-secondary);
    background: var(--bg-secondary);
    border-bottom: 1px solid var(--border-color);
    text-transform: uppercase;
    letter-spacing: 0.3px;
}
.data-table td {
    padding: 16px;
    border-bottom: 1px solid var(--border-color);
    font-size: 14px;
    vertical-align: middle;
}
.data-table tbody tr {
    transition: background 0.2s;
}
.data-table tbody tr:hover {
    background: var(--bg-secondary);
}
.data-table tbody tr:last-child td {
    border-bottom: none;
}

/* 单元格样式 */
.ticket-title {
    display: flex;
    align-items: center;
    gap: 8px;
}
.datetime {
    display: inline-flex;
    align-items: center;
    color: var(--text-secondary);
    font-size: 13px;
}

/* 状态徽章 */
.status-badge {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 5px 12px;
    border-radius: 30px;
    font-size: 12px;
    font-weight: 500;
    white-space: nowrap;
}
.status-dot {
    width: 6px;
    height: 6px;
    border-radius: 50%;
}
.status-open {
    background: #fef3c7;
    color: #92400e;
}
.status-open .status-dot {
    background: #f59e0b;
}
.status-processing {
    background: #ede9fe;
    color: #6d28d9;
}
.status-processing .status-dot {
    background: #8b5cf6;
}
.status-closed {
    background: #e5e7eb;
    color: #4b5563;
}
.status-closed .status-dot {
    background: #6b7280;
}

/* 优先级徽章 */
.priority-badge {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding: 5px 12px;
    border-radius: 30px;
    font-size: 12px;
    font-weight: 500;
}
.priority-low {
    background: #d1fae5;
    color: #065f46;
}
.priority-medium {
    background: #fef3c7;
    color: #92400e;
}
.priority-high {
    background: #fee2e2;
    color: #991b1b;
}

/* 空状态 */
.empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 48px 20px;
    text-align: center;
}
.empty-state img {
    opacity: 0.4;
    margin-bottom: 12px;
}
.empty-state p {
    color: var(--text-muted);
    font-size: 15px;
    margin: 0 0 4px;
}
.empty-state span {
    color: var(--text-muted);
    font-size: 13px;
}

/* 分页 */
.pagination {
    display: flex;
    gap: 6px;
    justify-content: center;
    margin-top: 28px;
}
.page-link {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 38px;
    height: 38px;
    padding: 0 8px;
    border: 1px solid var(--border-color);
    border-radius: var(--radius-sm);
    text-decoration: none;
    color: var(--text-primary);
    font-size: 14px;
    font-weight: 500;
    background: var(--bg-primary);
    transition: all 0.2s;
}
.page-link:hover {
    border-color: var(--primary-color);
    color: var(--primary-color);
    background: rgba(102, 126, 234, 0.05);
}
.page-link.active {
    background: var(--primary-color);
    color: white;
    border-color: var(--primary-color);
}
.page-ellipsis {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 38px;
    height: 38px;
    color: var(--text-muted);
}

/* 弹窗 */
.modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    backdrop-filter: blur(4px);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 10000;
}
.modal-content {
    background: var(--bg-primary);
    border-radius: var(--radius-lg);
    width: 90%;
    max-width: 500px;
    box-shadow: var(--shadow-lg);
}
.modal-header {
    padding: 20px 24px;
    border-bottom: 1px solid var(--border-color);
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.modal-header h3 {
    display: flex;
    align-items: center;
    font-size: 18px;
    font-weight: 600;
    margin: 0;
}
.modal-close {
    background: none;
    border: none;
    cursor: pointer;
    padding: 4px;
    border-radius: var(--radius-sm);
    transition: background 0.2s;
    display: flex;
}
.modal-close:hover {
    background: var(--bg-secondary);
}
.modal-body {
    padding: 24px;
}
.modal-footer {
    padding: 16px 24px 24px;
    display: flex;
    gap: 12px;
    justify-content: flex-end;
}
.form-group {
    margin-bottom: 20px;
}
.form-group label {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
    font-weight: 500;
    font-size: 14px;
}
.required {
    color: var(--danger-color);
    margin-left: 2px;
}
.form-group input,
.form-group select,
.form-group textarea {
    width: 100%;
    padding: 12px 16px;
    border: 1.5px solid var(--border-color);
    border-radius: var(--radius-md);
    font-size: 14px;
    background: var(--bg-primary);
    transition: all 0.2s;
}
.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
    outline: none;
    border-color: var(--primary-color);
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
.form-group textarea {
    resize: vertical;
    font-family: inherit;
}

/* 响应式 */
@media (max-width: 1024px) {
    .stats-grid {
        grid-template-columns: repeat(2, 1fr);
    }
}
@media (max-width: 768px) {
    .stats-grid {
        grid-template-columns: 1fr;
    }
    .page-header {
        flex-direction: column;
        align-items: flex-start;
    }
    .data-table th,
    .data-table td {
        padding: 12px;
    }
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const modal = document.getElementById('newTicketModal');
    const newBtn = document.getElementById('newTicketBtn');
    
    function closeModal() {
        modal.style.display = 'none';
        document.getElementById('newTicketForm').reset();
    }
    
    newBtn.addEventListener('click', function() {
        modal.style.display = 'flex';
    });
    
    document.querySelector('.modal-close')?.addEventListener('click', closeModal);
    document.querySelector('.cancel-btn')?.addEventListener('click', closeModal);
    
    document.getElementById('newTicketForm').addEventListener('submit', function(e) {
        e.preventDefault();
        const formData = new FormData(this);
        const submitBtn = this.querySelector('button[type="submit"]');
        const originalHtml = submitBtn.innerHTML;
        
        submitBtn.innerHTML = '<span class="loading-spinner"></span> 提交中...';
        submitBtn.disabled = true;
        
        fetch('/api/user_create_ticket.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                window.showToast && window.showToast(data.message || '工单提交成功', 'success');
                setTimeout(() => location.reload(), 1000);
            } else {
                window.showToast && window.showToast(data.message || '提交失败', 'error');
                submitBtn.innerHTML = originalHtml;
                submitBtn.disabled = false;
            }
            closeModal();
        })
        .catch(error => {
            console.error('错误:', error);
            window.showToast && window.showToast('网络错误，请稍后重试', 'error');
            submitBtn.innerHTML = originalHtml;
            submitBtn.disabled = false;
            closeModal();
        });
    });
    
    modal.addEventListener('click', function(e) {
        if (e.target === modal) closeModal();
    });
});

// 加载动画样式
const style = document.createElement('style');
style.textContent = `
    .loading-spinner {
        display: inline-block;
        width: 16px;
        height: 16px;
        border: 2px solid rgba(255, 255, 255, 0.3);
        border-radius: 50%;
        border-top-color: white;
        animation: spin 0.6s linear infinite;
        margin-right: 8px;
    }
    @keyframes spin {
        to { transform: rotate(360deg); }
    }
`;
document.head.appendChild(style);
</script>