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

if (!isLoggedIn()) {
    header('Location: /m/login.php');
    exit;
}

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

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

// 查询工单
$ticket = $db->fetchOne("SELECT * FROM tickets WHERE id = $ticket_id AND user_id = $user_id");
if (!$ticket) {
    header('Location: ?page=tickets');
    exit;
}

// 处理回复提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $content = trim($_POST['content'] ?? '');
    $action = $_POST['action'] ?? '';
    
    if ($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");
        }
        header("Location: ?page=ticket_view&id=$ticket_id");
        exit;
    } elseif ($action == 'close') {
        $db->query("UPDATE tickets SET status = 'closed' WHERE id = $ticket_id AND user_id = $user_id");
        header("Location: ?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
");

// 状态映射
$status_map = ['open' => '待处理', 'processing' => '处理中', 'closed' => '已关闭'];
$status_class = ['open' => '#f59e0b', 'processing' => '#8b5cf6', 'closed' => '#6b7280'];
$priority_map = [
    'low' => ['name' => '低', 'color' => '#10b981'],
    'medium' => ['name' => '中', 'color' => '#f59e0b'],
    'high' => ['name' => '高', 'color' => '#ef4444']
];
?>

<!-- 工单信息卡片 -->
<div class="card">
    <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 12px;">
        <div style="display: flex; align-items: center; gap: 8px;">
            <img src="https://api.iconify.design/mdi:ticket.svg?color=%23667eea" width="20" height="20" alt="">
            <span style="font-weight: 600; font-size: 16px;">#<?php echo $ticket_id; ?></span>
        </div>
        <div style="display: flex; gap: 6px;">
            <span style="background: <?php echo $priority_map[$ticket['priority']]['color']; ?>15; color: <?php echo $priority_map[$ticket['priority']]['color']; ?>; padding: 4px 10px; border-radius: 20px; font-size: 12px;">
                <?php echo $priority_map[$ticket['priority']]['name']; ?>优先级
            </span>
            <span style="background: <?php echo $status_class[$ticket['status']]; ?>15; color: <?php echo $status_class[$ticket['status']]; ?>; padding: 4px 10px; border-radius: 20px; font-size: 12px;">
                <?php echo $status_map[$ticket['status']]; ?>
            </span>
        </div>
    </div>
    
    <h3 style="font-size: 18px; margin-bottom: 10px;"><?php echo htmlspecialchars($ticket['title']); ?></h3>
    
    <div style="display: flex; align-items: center; gap: 16px; color: #999; font-size: 13px;">
        <span><img src="https://api.iconify.design/mdi:calendar.svg?color=%23999" width="14" height="14" alt=""> <?php echo date('m-d H:i', strtotime($ticket['created_at'])); ?></span>
        <span><img src="https://api.iconify.design/mdi:clock-outline.svg?color=%23999" width="14" height="14" alt=""> 更新: <?php echo date('m-d H:i', strtotime($ticket['updated_at'])); ?></span>
    </div>
</div>

<!-- 对话记录 -->
<div style="margin: 16px 0;">
    <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 12px;">
        <img src="https://api.iconify.design/mdi:message-text.svg?color=%23667eea" width="20" height="20" alt="">
        <span style="font-weight: 600;">对话记录</span>
    </div>
    
    <!-- 原始内容 -->
    <div class="card" style="background: #f9fafb;">
        <div style="display: flex; gap: 12px;">
            <img src="<?php echo htmlspecialchars($user['avatar'] ?? '/assets/uploads/default_avatar.png'); ?>" 
                 style="width: 40px; height: 40px; border-radius: 50%;" 
                 onerror="this.src='/assets/uploads/default_avatar.png'">
            <div style="flex:1;">
                <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 6px; flex-wrap: wrap;">
                    <strong><?php echo htmlspecialchars($user['username']); ?></strong>
                    <span style="background: #e5e7eb; padding: 2px 8px; border-radius: 20px; font-size: 11px;">用户</span>
                    <span style="color: #999; font-size: 11px; margin-left: auto;"><?php echo date('m-d H:i', strtotime($ticket['created_at'])); ?></span>
                </div>
                <div style="line-height: 1.6; color: #666; word-break: break-word;"><?php echo nl2br(htmlspecialchars($ticket['content'])); ?></div>
            </div>
        </div>
    </div>
    
    <!-- 回复列表 -->
    <?php foreach ($replies as $reply): ?>
    <div class="card" style="<?php echo ($reply['role'] == 'admin' || $reply['role'] == 'employee') ? 'border-left: 3px solid #667eea;' : ''; ?>">
        <div style="display: flex; gap: 12px;">
            <img src="<?php echo htmlspecialchars($reply['avatar'] ?? '/assets/uploads/default_avatar.png'); ?>" 
                 style="width: 40px; height: 40px; border-radius: 50%;" 
                 onerror="this.src='/assets/uploads/default_avatar.png'">
            <div style="flex:1;">
                <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 6px; flex-wrap: wrap;">
                    <strong><?php echo htmlspecialchars($reply['username']); ?></strong>
                    <?php if ($reply['role'] == 'admin'): ?>
                        <span style="background: #667eea; color: white; padding: 2px 8px; border-radius: 20px; font-size: 11px;">管理员</span>
                    <?php elseif ($reply['role'] == 'employee'): ?>
                        <span style="background: #10b981; color: white; padding: 2px 8px; border-radius: 20px; font-size: 11px;">客服</span>
                    <?php else: ?>
                        <span style="background: #e5e7eb; padding: 2px 8px; border-radius: 20px; font-size: 11px;">用户</span>
                    <?php endif; ?>
                    <span style="color: #999; font-size: 11px; margin-left: auto;"><?php echo date('m-d H:i', strtotime($reply['created_at'])); ?></span>
                </div>
                <div style="line-height: 1.6; color: #666; word-break: break-word;"><?php echo nl2br(htmlspecialchars($reply['content'])); ?></div>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
    
    <?php if (empty($replies)): ?>
    <div class="card" style="text-align: center; padding: 30px;">
        <img src="https://api.iconify.design/mdi:message-outline.svg?color=%23999" width="32" height="32" alt="">
        <p style="color: #999; margin-top: 8px;">暂无回复，等待客服处理</p>
    </div>
    <?php endif; ?>
</div>

<!-- 回复表单 -->
<?php if ($ticket['status'] != 'closed'): ?>
<div class="card">
    <form method="POST">
        <input type="hidden" name="action" value="reply">
        <textarea name="content" rows="4" placeholder="请输入回复内容..." 
                  style="width:100%; padding:12px; border:1px solid #e5e7eb; border-radius:8px; font-size:14px; resize:vertical; margin-bottom:12px;" required></textarea>
        <div style="display: flex; gap: 10px;">
            <button type="submit" class="btn btn-primary" style="flex:2;">
                <img src="https://api.iconify.design/mdi:send.svg?color=white" width="16" height="16" alt="">
                发送回复
            </button>
            <button type="submit" name="action" value="close" class="btn" style="flex:1; background:#f5f5f5;" onclick="return confirm('确定关闭此工单吗？关闭后将无法继续回复。')">
                <img src="https://api.iconify.design/mdi:check-circle.svg?color=%23666" width="16" height="16" alt="">
                关闭
            </button>
        </div>
    </form>
</div>
<?php else: ?>
<div class="card" style="text-align: center; color: #10b981;">
    <img src="https://api.iconify.design/mdi:check-circle.svg?color=%2310b981" width="24" height="24" alt="">
    <span style="margin-left: 8px;">此工单已关闭</span>
</div>
<?php endif; ?>