<?php
requireAdmin();

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

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

// 查询工单，同时获取用户名
$ticket = $db->fetchOne("
    SELECT t.*, u.username 
    FROM tickets t 
    JOIN users u ON t.user_id = u.id 
    WHERE t.id = $ticket_id
");

// 如果工单不存在，跳转回工单列表
if (!$ticket) {
    $_SESSION['error'] = '工单不存在';
    redirect('?page=tickets');
    exit;
}

// 获取回复
$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
");

// 处理回复提交
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $content = trim($_POST['content'] ?? '');
    if ($_POST['action'] == 'reply' && !empty($content)) {
        $content = $db->escape($content);
        $db->query("INSERT INTO ticket_replies (ticket_id, user_id, content) VALUES ($ticket_id, {$user['id']}, '$content')");
        
        if ($ticket['status'] == 'open') {
            $db->query("UPDATE tickets SET status = 'processing' WHERE id = $ticket_id");
        }
        redirect("?page=ticket_view&id=$ticket_id");
    } elseif ($_POST['action'] == 'close') {
        $db->query("UPDATE tickets SET status = 'closed' WHERE id = $ticket_id");
        redirect("?page=tickets");
    } elseif ($_POST['action'] == 'reopen') {
        $db->query("UPDATE tickets SET status = 'processing' WHERE id = $ticket_id");
        redirect("?page=ticket_view&id=$ticket_id");
    }
}
?>

<div class="ticket-view-container">
    <div class="page-header">
        <h2>工单详情 - #<?php echo $ticket['id']; ?></h2>
        <a href="?page=tickets" class="btn btn-secondary">返回列表</a>
    </div>
    
    <?php if (isset($_SESSION['error'])): ?>
        <div class="alert alert-error"><?php echo $_SESSION['error']; unset($_SESSION['error']); ?></div>
    <?php endif; ?>
    
    <div class="ticket-info">
        <div class="ticket-title">
            <h3><?php echo htmlspecialchars($ticket['title']); ?></h3>
            <div class="ticket-meta">
                <span>用户：<?php echo htmlspecialchars($ticket['username']); ?></span>
                <span class="status-badge status-<?php echo $ticket['status']; ?>">
                    <?php 
                    $status_map = ['open' => '待处理', 'processing' => '处理中', 'closed' => '已关闭'];
                    echo $status_map[$ticket['status']] ?? $ticket['status'];
                    ?>
                </span>
                <span class="priority-<?php echo $ticket['priority']; ?>">
                    <?php 
                    $priority_map = ['low' => '低优先级', 'medium' => '中优先级', 'high' => '高优先级'];
                    echo $priority_map[$ticket['priority']] ?? $ticket['priority'];
                    ?>
                </span>
                <span>创建时间：<?php echo $ticket['created_at']; ?></span>
            </div>
        </div>
    </div>
    
    <!-- 对话记录 -->
    <div class="ticket-replies">
        <div class="reply-item original">
            <div class="reply-avatar">
                <img src="<?php echo htmlspecialchars($user['avatar'] ?? '/assets/uploads/default_avatar.png'); ?>" alt="avatar">
            </div>
            <div class="reply-content">
                <div class="reply-header">
                    <strong><?php echo htmlspecialchars($ticket['username']); ?></strong>
                    <span class="reply-time"><?php echo $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') ? 'admin-reply' : ''; ?>">
                <div class="reply-avatar">
                    <img src="<?php echo htmlspecialchars($reply['avatar'] ?? '/assets/uploads/default_avatar.png'); ?>" alt="avatar">
                </div>
                <div class="reply-content">
                    <div class="reply-header">
                        <strong><?php echo htmlspecialchars($reply['username']); ?></strong>
                        <?php if ($reply['role'] == 'admin'): ?>
                            <span class="admin-badge">管理员</span>
                        <?php elseif ($reply['role'] == 'employee'): ?>
                            <span class="staff-badge">客服</span>
                        <?php endif; ?>
                        <span class="reply-time"><?php echo $reply['created_at']; ?></span>
                    </div>
                    <div class="reply-text"><?php echo nl2br(htmlspecialchars($reply['content'])); ?></div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
    
    <!-- 回复表单 -->
    <?php if ($ticket['status'] != 'closed'): ?>
        <div class="reply-form">
            <h4>回复工单</h4>
            <form method="POST">
                <input type="hidden" name="action" value="reply">
                <textarea name="content" rows="5" placeholder="请输入您的回复..." required></textarea>
                <div class="form-actions">
                    <button type="submit" class="btn btn-primary">发送回复</button>
                    <button type="submit" name="action" value="close" class="btn btn-secondary" onclick="return confirm('确定关闭此工单吗？')">关闭工单</button>
                </div>
            </form>
        </div>
    <?php else: ?>
        <div class="alert alert-info">
            此工单已关闭
            <form method="POST" style="display: inline; margin-left: 10px;">
                <input type="hidden" name="action" value="reopen">
                <button type="submit" class="btn-small">重新打开</button>
            </form>
        </div>
    <?php endif; ?>
</div>

<style>
.ticket-view-container {
    max-width: 900px;
    margin: 0 auto;
}
.ticket-info {
    background: var(--bg-primary);
    border-radius: var(--radius-md);
    padding: 20px;
    margin-bottom: 20px;
    border: 1px solid var(--border-color);
}
.ticket-title h3 {
    margin-bottom: 10px;
}
.ticket-meta {
    display: flex;
    gap: 15px;
    align-items: center;
    flex-wrap: wrap;
}
.ticket-replies {
    margin-bottom: 20px;
}
.reply-item {
    display: flex;
    gap: 15px;
    margin-bottom: 20px;
    padding: 15px;
    background: var(--bg-primary);
    border-radius: var(--radius-md);
    border: 1px solid var(--border-color);
}
.reply-item.original {
    background: var(--bg-secondary);
}
.reply-item.admin-reply {
    border-left: 3px solid var(--primary-color);
}
.reply-avatar img {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    object-fit: cover;
}
.reply-content {
    flex: 1;
}
.reply-header {
    margin-bottom: 8px;
    display: flex;
    align-items: center;
    gap: 10px;
    flex-wrap: wrap;
}
.reply-time {
    font-size: 12px;
    color: var(--text-muted);
}
.admin-badge, .staff-badge {
    font-size: 11px;
    padding: 2px 6px;
    border-radius: 10px;
    background: var(--primary-light);
    color: var(--primary-color);
}
.reply-text {
    line-height: 1.6;
}
.reply-form {
    background: var(--bg-primary);
    border-radius: var(--radius-md);
    padding: 20px;
    border: 1px solid var(--border-color);
}
.reply-form textarea {
    width: 100%;
    padding: 12px;
    border: 1px solid var(--border-color);
    border-radius: var(--radius-sm);
    background: var(--bg-secondary);
    resize: vertical;
}
.form-actions {
    margin-top: 15px;
    display: flex;
    gap: 10px;
}
.btn-small {
    padding: 5px 12px;
    background: var(--primary-color);
    color: white;
    border-radius: 5px;
    text-decoration: none;
    font-size: 12px;
    border: none;
    cursor: pointer;
}
</style>