<?php
ob_start();
require_once dirname(__DIR__, 2) . '/config.php';

$user_id = $_SESSION['user_id'];
$ticket_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

// 如果没有工单ID，跳转回工单列表
if ($ticket_id <= 0) {
    redirect('?page=tickets');
    exit;
}

$ticket = $db->fetchOne("SELECT * FROM tickets WHERE id = $ticket_id AND user_id = $user_id");
if (!$ticket) {
    redirect('?page=tickets');
    exit;
}
// 关闭工单
if (isset($_GET['close'])) {
    $db->query("UPDATE tickets SET status = 'closed' WHERE id = $ticket_id AND user_id = $user_id");
    redirect("?page=tickets");
    exit;
}

$user = currentUser();

// 获取回复
$replies = $db->fetchAll("
    SELECT tr.*, u.username, u.avatar, u.role 
    FROM ticket_replies tr 
    JOIN users u ON tr.user_id = u.id 
    WHERE tr.ticket_id = $ticket_id 
    ORDER BY tr.id ASC
");
?>

<div class="ticket-view-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="">
            工单详情 - #<?php echo $ticket['id']; ?>
        </h2>
        <a href="?page=tickets" class="btn btn-secondary">
            <img src="https://api.iconify.design/mdi:arrow-left.svg?color=currentColor" width="18" height="18" style="vertical-align: middle; margin-right: 6px;" alt="">
            返回列表
        </a>
    </div>
    
    <!-- 工单信息卡片 -->
    <div class="ticket-info-card">
        <div class="ticket-header">
            <div class="ticket-title-wrapper">
                <img src="https://api.iconify.design/mdi:ticket.svg?color=%23667eea" width="20" height="20" alt="">
                <h3><?php echo htmlspecialchars($ticket['title']); ?></h3>
            </div>
            <div class="ticket-badges">
                <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>
                <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>
            </div>
        </div>
        <div class="ticket-meta">
            <div class="meta-item">
                <img src="https://api.iconify.design/mdi:calendar.svg?color=%236b7280" width="16" height="16" alt="">
                <span>创建时间：<?php echo date('Y-m-d H:i', strtotime($ticket['created_at'])); ?></span>
            </div>
            <div class="meta-item">
                <img src="https://api.iconify.design/mdi:clock-outline.svg?color=%236b7280" width="16" height="16" alt="">
                <span>最后更新：<?php echo date('Y-m-d H:i', strtotime($ticket['updated_at'])); ?></span>
            </div>
        </div>
    </div>
    
    <!-- 对话记录 -->
    <div class="ticket-replies">
        <div class="reply-section-title">
            <img src="https://api.iconify.design/mdi:message-text.svg?color=%23667eea" width="20" height="20" alt="">
            <span>对话记录</span>
        </div>
        
        <!-- 原始工单内容 -->
        <div class="reply-item original">
            <div class="reply-avatar">
                <img src="<?php echo htmlspecialchars($user['avatar'] ?? '/assets/uploads/default_avatar.png'); ?>" alt="avatar" onerror="this.src='/assets/uploads/default_avatar.png'">
            </div>
            <div class="reply-content">
                <div class="reply-header">
                    <strong><?php echo htmlspecialchars($user['username']); ?></strong>
                    <span class="user-badge user">用户</span>
                    <span class="reply-time">
                        <img src="https://api.iconify.design/mdi:clock-outline.svg?color=%239ca3af" width="12" height="12" alt="">
                        <?php echo date('Y-m-d H:i', strtotime($ticket['created_at'])); ?>
                    </span>
                </div>
                <div class="reply-text"><?php echo nl2br(htmlspecialchars($ticket['content'])); ?></div>
            </div>
        </div>
        
        <!-- 回复列表 -->
        <?php foreach ($replies as $reply): ?>
            <div class="reply-item <?php echo ($reply['role'] == 'admin' || $reply['role'] == 'employee') ? 'staff-reply' : ''; ?>">
                <div class="reply-avatar">
                    <img src="<?php echo htmlspecialchars($reply['avatar'] ?? '/assets/uploads/default_avatar.png'); ?>" alt="avatar" onerror="this.src='/assets/uploads/default_avatar.png'">
                </div>
                <div class="reply-content">
                    <div class="reply-header">
                        <strong><?php echo htmlspecialchars($reply['username']); ?></strong>
                        <?php if ($reply['role'] == 'admin'): ?>
                            <span class="user-badge admin">
                                <img src="https://api.iconify.design/mdi:shield.svg?color=white" width="10" height="10" alt="">
                                管理员
                            </span>
                        <?php elseif ($reply['role'] == 'employee'): ?>
                            <span class="user-badge staff">
                                <img src="https://api.iconify.design/mdi:account-tie.svg?color=white" width="10" height="10" alt="">
                                客服
                            </span>
                        <?php else: ?>
                            <span class="user-badge user">用户</span>
                        <?php endif; ?>
                        <span class="reply-time">
                            <img src="https://api.iconify.design/mdi:clock-outline.svg?color=%239ca3af" width="12" height="12" alt="">
                            <?php echo date('Y-m-d H:i', strtotime($reply['created_at'])); ?>
                        </span>
                    </div>
                    <div class="reply-text"><?php echo nl2br(htmlspecialchars($reply['content'])); ?></div>
                </div>
            </div>
        <?php endforeach; ?>
        
        <?php if (empty($replies)): ?>
            <div class="empty-replies">
                <img src="https://api.iconify.design/mdi:message-outline.svg?color=%239ca3af" width="32" height="32" alt="">
                <p>暂无回复，等待客服处理</p>
            </div>
        <?php endif; ?>
    </div>
    
    <!-- 回复表单 -->
    <?php if ($ticket['status'] != 'closed'): ?>
        <div class="reply-form-card">
            <div class="reply-form-header">
                <img src="https://api.iconify.design/mdi:reply.svg?color=%23667eea" width="20" height="20" alt="">
                <h4>添加回复</h4>
            </div>
            <form id="replyForm">
                <input type="hidden" name="ticket_id" value="<?php echo $ticket_id; ?>">
                <textarea name="content" rows="4" placeholder="请输入您的回复内容..." required></textarea>
                <div class="form-actions">
                    <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: 6px;" alt="">
                        发送回复
                    </button>
                    <a href="?page=ticket_view&id=<?php echo $ticket_id; ?>&close=1" class="btn btn-secondary" onclick="return confirm('确定关闭此工单吗？关闭后您将无法继续回复。')">
                        <img src="https://api.iconify.design/mdi:check-circle.svg?color=currentColor" width="16" height="16" style="margin-right: 6px;" alt="">
                        关闭工单
                    </a>
                </div>
            </form>
        </div>
    <?php else: ?>
        <div class="closed-notice">
            <img src="https://api.iconify.design/mdi:check-circle.svg?color=%2310b981" width="24" height="24" alt="">
            <span>此工单已关闭</span>
        </div>
    <?php endif; ?>
</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);
    --radius-sm: 8px;
    --radius-md: 12px;
    --radius-lg: 16px;
}

.ticket-view-container {
    max-width: 900px;
    margin: 0 auto;
    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: 22px;
    font-weight: 600;
    color: var(--text-primary);
    margin: 0;
}

/* 按钮 */
.btn {
    display: inline-flex;
    align-items: center;
    padding: 10px 20px;
    border-radius: var(--radius-md);
    font-size: 14px;
    font-weight: 500;
    text-decoration: none;
    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(-1px);
    box-shadow: 0 4px 8px 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);
    border-color: var(--text-muted);
}

/* 工单信息卡片 */
.ticket-info-card {
    background: var(--bg-primary);
    border-radius: var(--radius-lg);
    padding: 24px;
    margin-bottom: 28px;
    border: 1px solid var(--border-color);
    box-shadow: var(--shadow-sm);
}
.ticket-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 20px;
    flex-wrap: wrap;
    gap: 16px;
}
.ticket-title-wrapper {
    display: flex;
    align-items: center;
    gap: 10px;
}
.ticket-title-wrapper h3 {
    font-size: 20px;
    font-weight: 600;
    color: var(--text-primary);
    margin: 0;
}
.ticket-badges {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
}
.ticket-meta {
    display: flex;
    gap: 24px;
    flex-wrap: wrap;
}
.meta-item {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 14px;
    color: var(--text-secondary);
}

/* 状态徽章 */
.status-badge {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 5px 12px;
    border-radius: 30px;
    font-size: 12px;
    font-weight: 500;
}
.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;
}

/* 对话记录 */
.ticket-replies {
    margin-bottom: 28px;
}
.reply-section-title {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 20px;
    font-size: 16px;
    font-weight: 600;
    color: var(--text-primary);
}
.reply-item {
    display: flex;
    gap: 16px;
    margin-bottom: 16px;
    padding: 20px;
    background: var(--bg-primary);
    border-radius: var(--radius-lg);
    border: 1px solid var(--border-color);
}
.reply-item.original {
    background: var(--bg-secondary);
}
.reply-item.staff-reply {
    border-left: 3px solid var(--primary-color);
}
.reply-avatar img {
    width: 44px;
    height: 44px;
    border-radius: 50%;
    object-fit: cover;
}
.reply-content {
    flex: 1;
}
.reply-header {
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    gap: 10px;
    flex-wrap: wrap;
}
.reply-header strong {
    font-size: 15px;
    color: var(--text-primary);
}
.user-badge {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    font-size: 11px;
    padding: 3px 8px;
    border-radius: 20px;
    font-weight: 500;
}
.user-badge.user {
    background: var(--bg-secondary);
    color: var(--text-secondary);
    border: 1px solid var(--border-color);
}
.user-badge.admin {
    background: #667eea;
    color: white;
}
.user-badge.staff {
    background: #10b981;
    color: white;
}
.reply-time {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 12px;
    color: var(--text-muted);
    margin-left: auto;
}
.reply-text {
    line-height: 1.7;
    color: var(--text-secondary);
    word-break: break-word;
}

/* 空回复 */
.empty-replies {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 48px 20px;
    background: var(--bg-primary);
    border-radius: var(--radius-lg);
    border: 1px dashed var(--border-color);
    text-align: center;
}
.empty-replies p {
    margin-top: 12px;
    color: var(--text-muted);
    font-size: 14px;
}

/* 回复表单 */
.reply-form-card {
    background: var(--bg-primary);
    border-radius: var(--radius-lg);
    padding: 24px;
    border: 1px solid var(--border-color);
    box-shadow: var(--shadow-sm);
}
.reply-form-header {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 16px;
}
.reply-form-header h4 {
    font-size: 16px;
    font-weight: 600;
    color: var(--text-primary);
    margin: 0;
}
.reply-form-card textarea {
    width: 100%;
    padding: 14px 16px;
    border: 1.5px solid var(--border-color);
    border-radius: var(--radius-md);
    font-size: 14px;
    background: var(--bg-primary);
    resize: vertical;
    transition: all 0.2s;
    font-family: inherit;
}
.reply-form-card textarea:focus {
    outline: none;
    border-color: var(--primary-color);
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
.form-actions {
    margin-top: 16px;
    display: flex;
    gap: 12px;
}

/* 已关闭提示 */
.closed-notice {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px 24px;
    background: var(--bg-primary);
    border-radius: var(--radius-lg);
    border: 1px solid var(--border-color);
    color: var(--text-secondary);
    font-size: 15px;
    gap: 10px;
}

/* 响应式 */
@media (max-width: 768px) {
    .ticket-header {
        flex-direction: column;
        align-items: flex-start;
    }
    .reply-header {
        flex-wrap: wrap;
    }
    .reply-time {
        margin-left: 0;
        width: 100%;
    }
    .form-actions {
        flex-direction: column;
    }
    .form-actions .btn {
        width: 100%;
        justify-content: center;
    }
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const replyForm = document.getElementById('replyForm');
    
    if (replyForm) {
        replyForm.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_ticket_reply.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;
                }
            })
            .catch(error => {
                console.error('错误:', error);
                window.showToast && window.showToast('网络错误，请稍后重试', 'error');
                submitBtn.innerHTML = originalHtml;
                submitBtn.disabled = false;
            });
        });
    }
});

// 加载动画样式
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>