<?php
session_name('user_session');
session_start();
require '../include/common.php';
require '../include/function.php';


$userId = $_SESSION['user_id'];


if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}


if (isset($_POST['submit_ticket'])) {
    $type = $_POST['type'];
    $content = $_POST['content'];

    
    $stmt = $pdo->prepare("INSERT INTO " . table('tickets') . " (uid, type, content, status, created_at) VALUES (:uid, :type, :content, :status, NOW())");
    $stmt->execute([
        'uid' => $userId,
        'type' => $type,
        'content' => $content,
        'status' => 1 
    ]);
    if ($currentSettings['ticket_email_status'] == 1) {
    $to = $apiCredentials['email_from'];
    $subject = "您的收到了新的工单";
    $body =  "工单内容：". $content;
    $url = $Website_Url. "/user/ajax.php";
    $post_data = array(
        'to' => $to,
        'subject' => $subject,
        'body' => $body
    );
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_POST, true); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data)); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 
    
    
    $response = curl_exec($ch);
    
    
    if (curl_errno($ch)) {
        error_log('cURL 错误: ' . curl_error($ch));
    } else {
        
        $response_data = json_decode($response, true);
        if ($response_data['success']) {
            
            echo "通知邮件发送成功！";
        } else {
            
            echo "通知邮件发送失败：" . $response_data['message'];
        }
    }
    
    
    curl_close($ch);
} else {
    
}
if ($currentSettings['ticket_phone_status'] == 1) {
    
    $sendtouserphone = $apiCredentials['admin_phone'];
    $sms_provider = $currentSettings['sms_interface'];
    $web_apikey = $apiCredentials['web_apikey']; 
    $sms_url = $Website_Url . "/other/sms/". $sms_provider ."/index.php?apikey=".$web_apikey;

    
    $sms_data = array(
        'mobile' => $sendtouserphone,
        'message' => 'newticket'
    );

    
    function post_smsdata($sms_url, $sms_data)
    {
        $ch = curl_init(); 
        if ($ch === false) {
            die('无法初始化 cURL');
        }

        curl_setopt($ch, CURLOPT_URL, $sms_url); 
        curl_setopt($ch, CURLOPT_POST, true); 
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($sms_data)); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 

        $response = curl_exec($ch); 

        if ($response === false) {
            echo "cURL 执行失败: " . curl_error($ch); 
        }

        curl_close($ch); 
        return $response; 
    }

    
    $response = post_smsdata($sms_url, $sms_data);

    
    echo "短信发送响应：" . $response;
} else {
    
}
    
    header("Location: tickets.php");
    exit();
}


if (isset($_POST['reply_ticket'])) {
    $ticketId = intval($_POST['tid']);
    $content = $_POST['content'];

    
    $stmt = $pdo->prepare("INSERT INTO " . table('ticketcontent') . " (tid, uid, content) VALUES (:tid, :uid, :content)");
    $stmt->execute([
        'tid' => $ticketId,
        'uid' => $userId,
        'content' => $content
    ]);
    if ($currentSettings['ticket_email_status'] == 1) {
    $to = $apiCredentials['email_from'];
    $subject = "有用户回复了您的工单";
    $body = "回复内容：". $content;
    $url = $Website_Url. "/user/ajax.php";
    $post_data = array(
        'to' => $to,
        'subject' => $subject,
        'body' => $body
    );
    
    
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_POST, true); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data)); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 
    
    
    $response = curl_exec($ch);
    
    
    if (curl_errno($ch)) {
        error_log('cURL 错误: ' . curl_error($ch));
    } else {
        
        $response_data = json_decode($response, true);
        if ($response_data['success']) {
            
            echo "通知邮件发送成功！";
        } else {
            
            echo "通知邮件发送失败：" . $response_data['message'];
        }
    }
    
    
    curl_close($ch);
} else {
    echo "邮件通知功能已关闭。";
}
if ($currentSettings['ticket_phone_status'] == 1) {
    
    $sendtouserphone = $apiCredentials['admin_phone'];
    $sms_provider = $currentSettings['sms_interface'];
    $web_apikey = $apiCredentials['web_apikey']; 
    $sms_url = $Website_Url . "/other/sms/". $sms_provider ."/index.php?apikey=".$web_apikey;

    
    $sms_data = array(
        'mobile' => $sendtouserphone,
        'message' => 'userreply'
    );

    
    function post_smsdata($sms_url, $sms_data)
    {
        $ch = curl_init(); 
        if ($ch === false) {
            die('无法初始化 cURL');
        }

        curl_setopt($ch, CURLOPT_URL, $sms_url); 
        curl_setopt($ch, CURLOPT_POST, true); 
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($sms_data)); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 

        $response = curl_exec($ch); 

        if ($response === false) {
            echo "cURL 执行失败: " . curl_error($ch); 
        }

        curl_close($ch); 
        return $response; 
    }

    
    $response = post_smsdata($sms_url, $sms_data);

    
    echo "短信发送响应：" . $response;
} else {
    
}
    
    $stmt = $pdo->prepare("UPDATE " . table('tickets') . " SET status = 3 WHERE tid = :tid");
    $stmt->execute(['tid' => $ticketId]);

    header("Location: tickets.php"); 
    exit();
}


$stmt = $pdo->prepare("SELECT * FROM " . table('tickets') . " WHERE uid = :uid ORDER BY created_at DESC");
$stmt->execute(['uid' => $userId]);
$tickets = $stmt->fetchAll(PDO::FETCH_ASSOC);


$replies = [];
foreach ($tickets as $ticket) {
    $stmt = $pdo->prepare("SELECT * FROM " . table('ticketcontent') . " WHERE tid = :tid ORDER BY recoverytime ASC");
    $stmt->execute(['tid' => $ticket['tid']]);
    $replies[$ticket['tid']] = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
?>

<?php include 'header.php'; ?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>工单管理</title>
    <style>
    .reply-container {
    max-height: 300px; 
    overflow-y: auto; 
    scrollbar-width: thin; 
    scrollbar-color: #888 #f1f1f1; 
}


.reply-container::-webkit-scrollbar {
    width: 10px; 
}

.reply-container::-webkit-scrollbar-track {
    background: #f1f1f1; 
    border-radius: 5px; 
}

.reply-container::-webkit-scrollbar-thumb {
    background-color: #888; 
    border-radius: 5px; 
}

.reply-container::-webkit-scrollbar-thumb:hover {
    background-color: #555; 
}

</style>

</head>
<body>
<div class="main-content">
    <div class="page-content">
        <div class="container-fluid">
    <h1>工单管理</h1>

    <!-- 提交工单的按钮 -->
    <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#submitTicketModal">提交工单</button>

    <!-- 提交工单的模态框 -->
    <div class="modal fade" id="submitTicketModal" tabindex="-1" aria-labelledby="submitTicketModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="submitTicketModalLabel">提交工单</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form method="POST" action="tickets.php">
                        <div class="mb-3">
                            <label for="type" class="form-label">工单类型</label>
                            <select class="form-select" name="type" id="type" required>
                                <option value="0">账号问题</option>
                                <option value="1">域名问题</option>
                                <option value="2">解析问题</option>
                                <option value="3">充值问题</option>
                                <option value="4">其他问题</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="content" class="form-label">工单内容</label>
                            <textarea class="form-control" name="content" id="content" rows="4" required></textarea>
                        </div>
                        <button type="submit" name="submit_ticket" class="btn btn-success">提交</button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- 工单列表 -->
    <table class="table table-bordered table-striped mt-3">
        <thead>
            <tr>
                <th>ID</th>
                <th>类型</th>
                <th>内容</th>
                <th>状态</th>
                <th>创建时间</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($tickets as $ticket): ?>
                <tr>
                    <td><?php echo htmlspecialchars($ticket['tid']); ?></td>
                    <td><?php
                        $types = ['账号问题', '域名问题', '解析问题', '充值问题', '其他问题'];
                        echo htmlspecialchars($types[$ticket['type']]);
                    ?></td>
                    <td><?php echo htmlspecialchars($ticket['content']); ?></td>
                    <td><?php
                $statuses = ['未处理', '待处理', '等待回复', '等待您回复', '完成'];
                $statusColors = ['red', 'orange', 'orange', 'blue', 'green'];
                $statusIndex = $ticket['status'] - 1;
                $statusText = htmlspecialchars($statuses[$statusIndex]);
                $statusColor = htmlspecialchars($statusColors[$statusIndex]);
            ?>
            <span style="color: <?php echo $statusColor; ?>"><?php echo $statusText; ?></span></td>
                    <td><?php echo htmlspecialchars($ticket['created_at']); ?></td>
                    
                    <td>
                    <?php if ($ticket['status'] != 5) {
                        echo '<button class="btn btn-info" data-bs-toggle="modal" data-bs-target="#replyModal'. $ticket['tid']. '">回复</button>';
                    }else{
                        echo '<button class="btn btn-secondary" data-bs-toggle="modal" data-bs-target="#viewModal'. $ticket['tid']. '">查看</button>';
                        }
                         ?>
                    </td>
                </tr>
                <!-- 回复工单的模态框 -->
<div class="modal fade" id="replyModal<?php echo $ticket['tid']; ?>" tabindex="-1" aria-labelledby="replyModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="replyModalLabel">回复工单</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>

            </div>
            <div class="modal-body">
                <div>
                <?php
                        $types = ['账号问题', '域名问题', '解析问题', '充值问题', '其他问题'];
                        echo htmlspecialchars('工单类型:'.$types[$ticket['type']]);
                    ?></div>
                    <div><?php echo htmlspecialchars('工单内容:'.$ticket['content']); ?></div>
                    </div>
            <div class="modal-body">
                <!-- 显示回复内容 -->
                <div class="reply-container" style="max-height: 300px; overflow-y: auto;">
                    <?php if (isset($replies[$ticket['tid']]) && count($replies[$ticket['tid']]) > 0): ?>
                        <?php foreach ($replies[$ticket['tid']] as $reply): ?>
                            <div class="mb-3" style="background-color: WhiteSmoke;">
                                
                                <strong>回复人:</strong> 
                                <?php 
                                    if ($reply['uid'] == 0) {
                                        echo htmlspecialchars('管理员');
                                    } else if ($reply['uid'] == $userId) {
                                        echo htmlspecialchars('您');
                                    }
                                ?>
                                <br>
                                
                                <strong>内容:</strong><br>
                                <a><?php echo htmlspecialchars($reply['content']); ?></a><br>
                                <a style="font-size: 12px; color: DarkGray;"><strong>回复时间:</strong> <?php echo htmlspecialchars($reply['recoverytime']); ?></a>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <p>暂无回复。</p>
                    <?php endif; ?>
                </div>

                <!-- 回复输入框 -->
                <form method="POST" action="tickets.php">
                    <input type="hidden" name="tid" value="<?php echo htmlspecialchars($ticket['tid']); ?>">
                    <div class="mb-3">
                        <label for="content" class="form-label">回复内容</label>
                        <textarea class="form-control" name="content" id="content" rows="4" required></textarea>
                    </div>
                    <button type="submit" name="reply_ticket" class="btn btn-success">发送回复</button>
                </form>
            </div>
        </div>
    </div>
</div>
<!-- 查看回复的模态框 -->
<div class="modal fade" id="viewModal<?php echo $ticket['tid']; ?>" tabindex="-1" aria-labelledby="viewModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="viewModalLabel">查看工单详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div>
                <?php
                        $types = ['账号问题', '域名问题', '解析问题', '充值问题', '其他问题'];
                        echo htmlspecialchars('工单类型:'.$types[$ticket['type']]);
                    ?></div>
                    <div><?php echo htmlspecialchars('工单内容:'.$ticket['content']); ?></div>
                    </div>
            <div class="modal-body">
                <!-- 显示回复内容 -->
                <div class="view-container" style="max-height: 300px; overflow-y: auto;">
                    <?php if (isset($replies[$ticket['tid']]) && count($replies[$ticket['tid']]) > 0): ?>
                        <?php foreach ($replies[$ticket['tid']] as $reply): ?>
                            <div class="mb-3" style="background-color: WhiteSmoke;">
                                
                                <strong>回复人:</strong> 
                                <?php 
                                    if ($reply['uid'] == 0) {
                                        echo htmlspecialchars('管理员');
                                    } else if ($reply['uid'] == $userId) {
                                        echo htmlspecialchars('您');
                                    }
                                ?>
                                <br>
                                
                                <strong>内容:</strong><br>
                                <a><?php echo htmlspecialchars($reply['content']); ?></a><br>
                                <a style="font-size: 12px; color: DarkGray;"><strong>回复时间:</strong> <?php echo htmlspecialchars($reply['recoverytime']); ?></a>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <p>暂无回复。</p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

</div>
    </div>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>
</body>
</html>
