<?php
include 'header.php';

// Get the user ID from the URL
$userid = isset($_GET['userid']) ? intval($_GET['userid']) : 0;

if ($userid <= 0) {
    die("Invalid user ID.");
}

// Fetch ticket details (subject and department)
$ticket_details = [];
$query = "SELECT subject, department FROM support_chat WHERE userid = ? LIMIT 1";
$stmt = $link->prepare($query);
if ($stmt) {
    $stmt->bind_param("i", $userid);
    $stmt->execute();
    $result = $stmt->get_result();
    $ticket_details = $result->fetch_assoc();
    $stmt->close();
} else {
    die("Error preparing statement: " . $link->error);
}

// Handle admin reply
if (isset($_POST['admin_reply'])) {
    $message = trim($_POST['message']);

    if (empty($message)) {
        $err = 'Enter your reply';
    } else {
        $message = mysqli_real_escape_string($link, $message); // Sanitize input
        $date = date('Y-m-d H:i:s');
        $subject = $ticket_details['subject']; // Get the subject from ticket details
        $department = $ticket_details['department']; // Get the department from ticket details

        // Insert the admin's reply into the database
        $query = "INSERT INTO support_chat (userid, message, is_admin, created_at, subject, department) VALUES (?, ?, 1, ?, ?, ?)";
        $stmt = $link->prepare($query);
        if ($stmt) {
            $stmt->bind_param("issss", $userid, $message, $date, $subject, $department);
            if ($stmt->execute()) {
                $msg = "Reply Sent Successfully";
            } else {
                $err = "Error: " . $stmt->error;
            }
            $stmt->close();
        } else {
            $err = "Error preparing statement: " . $link->error;
        }
    }
}

// Fetch all messages for the user
$user_messages = [];
$query = "SELECT * FROM support_chat WHERE userid = ? ORDER BY created_at ASC";
$stmt = $link->prepare($query);
if ($stmt) {
    $stmt->bind_param("i", $userid);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $user_messages[] = $row;
    }
    $stmt->close();
} else {
    die("Error preparing statement: " . $link->error);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Support Chat</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f4f6f9;
            margin: 0;
            padding: 0;
        }
        .container {
            max-width: 1200px;
            margin: 20px auto;
            padding: 20px;
            background: #fff;
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }
        .chat-container {
            display: flex;
            flex-direction: column;
            height: 600px;
            border: 1px solid #ddd;
            border-radius: 12px;
            overflow: hidden;
            background: #fff;
        }
        .chat-header {
            background: #007bff;
            color: #fff;
            padding: 15px;
            font-size: 18px;
            font-weight: bold;
            text-align: center;
            border-bottom: 1px solid #ddd;
        }
        .chat-messages {
            flex: 1;
            padding: 15px;
            overflow-y: auto;
            background: #f9f9f9;
        }
        .message {
            margin-bottom: 15px;
            padding: 10px 15px;
            border-radius: 12px;
            max-width: 70%;
            position: relative;
            animation: fadeIn 0.3s ease-in-out;
        }
        .user-message {
            background: #e1f5fe;
            margin-right: auto;
        }
        .admin-message {
            background: #007bff;
            color: #fff;
            margin-left: auto;
        }
        .timestamp {
            font-size: 12px;
            color: #666;
            margin-top: 5px;
            display: block;
            text-align: right;
        }
        .chat-input {
            display: flex;
            border-top: 1px solid #ddd;
            background: #fff;
            padding: 10px;
        }
        .chat-input textarea {
            flex: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 8px;
            resize: none;
            font-size: 14px;
            outline: none;
            transition: border-color 0.3s ease;
        }
        .chat-input textarea:focus {
            border-color: #007bff;
        }
        .chat-input button {
            margin-left: 10px;
            padding: 10px 20px;
            background: #007bff;
            color: #fff;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            transition: background 0.3s ease;
        }
        .chat-input button:hover {
            background: #0056b3;
        }
        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <?php if (isset($err)): ?>
            <div class="alert alert-danger"><?php echo $err; ?></div>
        <?php endif; ?>
        <?php if (isset($msg)): ?>
            <div class="alert alert-success"><?php echo $msg; ?></div>
        <?php endif; ?>

<br><br>
        <!-- Chat Section -->
        <div class="chat-container">
            <div class="chat-header">
                Support Ticket: <?php echo htmlspecialchars($ticket_details['subject'] ?? 'N/A'); ?> (Department: <?php echo htmlspecialchars($ticket_details['department'] ?? 'N/A'); ?>)
            </div>
            <div class="chat-messages" id="chat-messages">
                <?php foreach ($user_messages as $message): ?>
                    <div class="message <?php echo $message['is_admin'] ? 'admin-message' : 'user-message'; ?>">
                        <?php echo htmlspecialchars($message['message']); ?>
                        <div class="timestamp"><?php echo $message['created_at']; ?></div>
                    </div>
                <?php endforeach; ?>
            </div>
            <form method="post" action="admin_chat.php?userid=<?php echo $userid; ?>" class="chat-input">
                <textarea name="message" placeholder="Type your reply here..." required></textarea>
                <button type="submit" name="admin_reply">Send Reply</button>
            </form>
        </div>
    </div>

    <?php include 'footer.php'; ?>
</body>
</html>