Viewing File: /home/quiczmwg/sellixdigital.org/admin/admin-message.php

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

include 'head.php';
include 'header.php';
include 'sidebar.php';

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

$product_id = $_GET['product_id'] ?? '';
$user_id = $_GET['user_id'] ?? '';
$feedback = '';

$all_products = mysqli_query($conn, "SELECT product_id, product_name FROM products ORDER BY created_at DESC");
$all_users = mysqli_query($conn, "SELECT userid, full_name FROM user_login ORDER BY created_at DESC");

$product = null;
$chats = [];

if (!empty($product_id) && !empty($user_id)) {
    $stmt = $conn->prepare("SELECT * FROM products WHERE product_id = ?");
    $stmt->bind_param("s", $product_id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows > 0) {
        $product = $result->fetch_assoc();
    }

    // Handle form submission
    if ($_SERVER["REQUEST_METHOD"] === "POST") {
        $message = trim($_POST['message']);
        $image_name = "";

        if (!empty($_FILES['image']['name'])) {
            $upload_dir = "../dashboard/uploads/";
            if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
            $image_name = time() . "_" . basename($_FILES["image"]["name"]);
            move_uploaded_file($_FILES["image"]["tmp_name"], $upload_dir . $image_name);
        }

        $admin_id = 'admin';
        $stmt = $conn->prepare("INSERT INTO product_messages (product_id, sender_role, sender_id, receiver_id, message, image, sent_at) VALUES (?, 'admin', ?, ?, ?, ?, NOW())");
        $stmt->bind_param("sssss", $product_id, $admin_id, $user_id, $message, $image_name);

        if ($stmt->execute()) {
            $feedback = '<div class="alert alert-success">Message sent successfully.</div>';
        } else {
            $feedback = '<div class="alert alert-danger">Failed to send message. Please try again.</div>';
        }
    }

    // Load messages
    // Load messages between admin and selected user for the selected product
$messages = $conn->prepare("
SELECT * FROM product_messages 
WHERE product_id = ? 
  AND (
      (sender_id = 'admin' AND receiver_id = ?) OR
      (sender_id = ? AND receiver_id = 'admin')
  )
ORDER BY sent_at ASC
");

if (!$messages) {
die("Prepare failed: (" . $conn->errno . ") " . $conn->error);
}

$messages->bind_param("sss", $product_id, $user_id, $user_id);
$messages->execute();
$chats = $messages->get_result();

}
?>

<div class="page-wrapper">
    <section>
        <div class="container-fluid">
            <div class="card">
                <div class="card-header bg-primary text-white fw-bold">
                    Message a User about a Product
                </div>
                <div class="card-body">
                    <form method="get" class="row g-3 mb-4">
                        <div class="col-md-6">
                            <label for="product_id" class="form-label">Select Product</label>
                            <select name="product_id" id="product_id" class="form-select" required>
                                <option value="">-- Choose Product --</option>
                                <?php while ($prod = mysqli_fetch_assoc($all_products)) : ?>
                                    <option value="<?php echo $prod['product_id']; ?>" <?php echo ($product_id === $prod['product_id']) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($prod['product_name']); ?>
                                    </option>
                                <?php endwhile; ?>
                            </select>
                        </div>

                        <div class="col-md-6">
                            <label for="user_id" class="form-label">Select User</label>
                            <select name="user_id" id="user_id" class="form-select" required>
                                <option value="">-- Choose User --</option>
                                <?php while ($user = mysqli_fetch_assoc($all_users)) : ?>
                                    <option value="<?php echo $user['userid']; ?>" <?php echo ($user_id === $user['userid']) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($user['full_name']); ?>
                                    </option>
                                <?php endwhile; ?>
                            </select>
                        </div>

                        <div class="col-12">
                            <button type="submit" class="btn btn-primary">Load Chat</button>
                        </div>
                    </form>

                    <?php echo $feedback; ?>

                    <?php if ($product && $user_id) : ?>
                        <h5 class="mb-3 fw-bold text-primary">Chat with <?php echo htmlspecialchars($user_id); ?> on: <?php echo htmlspecialchars($product['product_name']); ?></h5>
                        <div class="chat-box mb-4" id="admin-chat-messages" style="height:400px; overflow-y:auto; background:#f9f9f9; padding:10px; border-radius:8px;">
                            <?php while ($msg = $chats->fetch_assoc()) : ?>
                                <div class="<?php echo $msg['sender_role'] === 'admin' ? 'text-end' : 'text-start'; ?>">
                                    <div class="p-2 my-1" style="background-color:<?php echo $msg['sender_role'] === 'admin' ? '#dcf8c6' : '#ffffff'; ?>; border-radius:10px; display:inline-block;">
                                        <?php echo nl2br(htmlspecialchars($msg['message'])); ?>
                                        <?php if ($msg['image']) : ?>
                                            <br><img src="../dashboard/uploads/<?php echo $msg['image']; ?>" alt="image" style="max-width:200px; border-radius:8px;">
                                        <?php endif; ?>
                                        <div class="small text-muted"><?php echo date("M d, Y h:i A", strtotime($msg['sent_at'])); ?></div>
                                    </div>
                                </div>
                            <?php endwhile; ?>
                        </div>

                        <form method="POST" enctype="multipart/form-data" class="mt-3 border p-3 rounded bg-light">
                            <div class="mb-3">
                                <label for="message" class="form-label">Message</label>
                                <textarea name="message" class="form-control" rows="3" required></textarea>
                            </div>
                            <div class="mb-3">
                                <label for="image" class="form-label">Optional Image</label>
                                <input type="file" name="image" class="form-control">
                            </div>
                            <button type="submit" class="btn btn-success">Send Message</button>
                        </form>
                    <?php else : ?>
                        <div class="alert alert-warning mt-4">Please select both a product and a user to start a conversation.</div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </section>
</div>

<?php include 'footer.php'; ?>
<script>
    document.getElementById("admin-chat-form").addEventListener("submit", function(e) {
        e.preventDefault();

        const form = e.target;
        const formData = new FormData(form);
        formData.append("product_id", "<?php echo $product_id; ?>");

        fetch("admin-send-message.php", {
                method: "POST",
                body: formData
            })
            .then(res => res.text())
            .then(res => {
                if (res.trim() === "success") {
                    form.reset();
                    loadAdminMessages();
                }
            });
    });

    function loadAdminMessages() {
        fetch("admin-load-messages.php?product_id=<?php echo $product_id; ?>")
            .then(res => res.text())
            .then(html => {
                document.getElementById("admin-chat-messages").innerHTML = html;
                document.getElementById("admin-chat-messages").scrollTop = document.getElementById("admin-chat-messages").scrollHeight;
            });
    }

    // Optional auto-refresh every 5s
    setInterval(loadAdminMessages, 5000);
</script>
Back to Directory File Manager
<