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

header('Content-Type: application/json');

// 检查登录状态
if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => '请先登录']);
    exit;
}

$user_id = $_SESSION['user_id'];

// 获取参数
$ticket_id = intval($_POST['ticket_id'] ?? 0);
$content = trim($_POST['content'] ?? '');

if ($ticket_id <= 0) {
    echo json_encode(['success' => false, 'message' => '工单不存在']);
    exit;
}

if (empty($content)) {
    echo json_encode(['success' => false, 'message' => '请输入回复内容']);
    exit;
}

// 验证工单是否属于当前用户
$ticket = $db->fetchOne("SELECT * FROM tickets WHERE id = $ticket_id AND user_id = $user_id");
if (!$ticket) {
    echo json_encode(['success' => false, 'message' => '工单不存在']);
    exit;
}

if ($ticket['status'] == 'closed') {
    echo json_encode(['success' => false, 'message' => '工单已关闭，无法回复']);
    exit;
}

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

echo json_encode(['success' => true, 'message' => '回复成功']);
exit;