<?php
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;
}

$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
");

// 处理回复提交
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'reply') {
    $content = trim($_POST['content'] ?? '');
    if (!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");
        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;
}

// 所有 PHP 处理完成后，开始输出 HTML
?>
<div class="ticket-view-container" style="max-width: 900px; margin: 20px auto; padding: 20px;">
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
        <h2>工单详情</h2>
        <a href="?page=tickets" class="btn btn-secondary" style="padding: 8px 16px; background: var(--bg-secondary); border: 1px solid var(--border-color); border-radius: 8px; text-decoration: none;">← 返回列表</a>
    </div>
    
    <div style="background: var(--bg-primary); border-radius: 12px; padding: 20px; margin-bottom: 20px; border: 1px solid var(--border-color);">
        <h3 style="margin-bottom: 10px;"><?php echo htmlspecialchars($ticket['title']); ?></h3>
        <div style="display: flex; gap: 15px; flex-wrap: wrap;">
            <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 style="display: flex; gap: 15px; margin-bottom: 20px; padding: 16px; background: var(--bg-secondary); border-radius: 12px; border: 1px solid var(--border-color);">
        <div>
            <img src="<?php echo htmlspecialchars($user['avatar'] ?? '/assets/uploads/default_avatar.png'); ?>" style="width: 40px; height: 40px; border-radius: 50%;">
        </div>
        <div style="flex: 1;">
            <div style="margin-bottom: 8px;">
                <strong><?php echo htmlspecialchars($user['username']); ?></strong>
                <span style="font-size: 12px; color: var(--text-muted); margin-left: 10px;"><?php echo $ticket['created_at']; ?></span>
            </div>
            <div style="line-height: 1.6;"><?php echo nl2br(htmlspecialchars($ticket['content'])); ?></div>
        </div>
    </div>
    
    <!-- 回复列表 -->
    <?php foreach ($replies as $reply): ?>
        <div style="display: flex; gap: 15px; margin-bottom: 20px; padding: 16px; background: var(--bg-primary); border-radius: 12px; border: 1px solid var(--border-color); <?php echo ($reply['role'] == 'admin' || $reply['role'] == 'employee') ? 'border-left: 3px solid var(--primary-color);' : ''; ?>">
            <div>
                <img src="<?php echo htmlspecialchars($reply['avatar'] ?? '/assets/uploads/default_avatar.png'); ?>" style="width: 40px; height: 40px; border-radius: 50%;">
            </div>
            <div style="flex: 1;">
                <div style="margin-bottom: 8px;">
                    <strong><?php echo htmlspecialchars($reply['username']); ?></strong>
                    <?php if ($reply['role'] == 'admin'): ?>
                        <span style="font-size: 11px; padding: 2px 8px; border-radius: 12px; background: var(--primary-light); color: var(--primary-color); margin-left: 8px;">管理员</span>
                    <?php elseif ($reply['role'] == 'employee'): ?>
                        <span style="font-size: 11px; padding: 2px 8px; border-radius: 12px; background: var(--primary-light); color: var(--primary-color); margin-left: 8px;">客服</span>
                    <?php endif; ?>
                    <span style="font-size: 12px; color: var(--text-muted); margin-left: 10px;"><?php echo $reply['created_at']; ?></span>
                </div>
                <div style="line-height: 1.6;"><?php echo nl2br(htmlspecialchars($reply['content'])); ?></div>
            </div>
        </div>
    <?php endforeach; ?>
    
    <!-- 回复表单 -->
    <?php if ($ticket['status'] != 'closed'): ?>
        <div style="background: var(--bg-primary); border-radius: 12px; padding: 20px; border: 1px solid var(--border-color);">
            <h4 style="margin-bottom: 15px;">添加回复</h4>
            <form method="POST">
                <input type="hidden" name="action" value="reply">
                <textarea name="content" rows="5" placeholder="请输入您的回复..." required style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px; background: var(--bg-secondary); resize: vertical;"></textarea>
                <div style="margin-top: 15px; display: flex; gap: 10px;">
                    <button type="submit" class="btn btn-primary" style="padding: 8px 20px; background: var(--primary-color); color: white; border: none; border-radius: 8px; cursor: pointer;">发送回复</button>
                    <a href="?page=ticket_view&id=<?php echo $ticket_id; ?>&close=1" class="btn btn-secondary" style="padding: 8px 20px; background: var(--bg-secondary); border: 1px solid var(--border-color); border-radius: 8px; text-decoration: none; color: var(--text-primary);" onclick="return confirm('确定关闭此工单吗？')">关闭工单</a>
                </div>
            </form>
        </div>
    <?php else: ?>
        <div style="background: var(--primary-light); padding: 15px; border-radius: 12px; text-align: center;">
            此工单已关闭
        </div>
    <?php endif; ?>
</div>

<style>
.status-badge {
    padding: 4px 12px;
    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;
}
</style>