<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once("../php/db_connect.php");

if (!isset($_SESSION["user_id"])) {
    echo "<script>window.location='index.php';</script>";
    exit();
}

$current_user_id = (int)$_SESSION["user_id"];
$receiver_id = isset($_GET["receiver_id"]) ? (int)$_GET["receiver_id"] : 0;
$order_id = isset($_GET["order_id"]) ? (int)$_GET["order_id"] : 0;

$user_role = $_SESSION["role"] ?? "";
$basePage = ($user_role === "customer") ? "customer.php" : "admin.php";

$isPopup = isset($_GET["popup"]) && $_GET["popup"] == "1";

if ($isPopup) {
    $messagePageLink = "messages.php?popup=1";
    $backToMessagesLink = "messages.php?popup=1";
} else {
    $messagePageLink = $basePage . "?page=messages";
    $backToMessagesLink = $basePage . "?page=messages";
}

function h($value) {
    return htmlspecialchars($value ?? "", ENT_QUOTES, "UTF-8");
}

function displayName($row) {
    if (!empty($row["shop_name"])) {
        return $row["shop_name"];
    }

    if (!empty($row["email"])) {
        return $row["email"];
    }

    return "User";
}

function formatTime($date) {
    if (empty($date)) {
        return "";
    }

    return date("M d, Y h:i A", strtotime($date));
}

/*
|--------------------------------------------------------------------------
| Get all shops and customers
|--------------------------------------------------------------------------
*/
if ($user_role === "customer") {

    // Customer can message admins only
    $contactsStmt = $conn->prepare("
        SELECT 
            id,
            shop_name,
            email,
            role,
            shop_image
        FROM users
        WHERE id != ?
          AND role = 'admin'
        ORDER BY shop_name ASC, email ASC
    ");

} else {

    // Admin can message admins, superadmin, and customers
    $contactsStmt = $conn->prepare("
        SELECT 
            id,
            shop_name,
            email,
            role,
            shop_image
        FROM users
        WHERE id != ?
          AND role IN ('admin', 'superadmin', 'customer')
        ORDER BY 
            FIELD(role, 'admin', 'superadmin', 'customer'),
            shop_name ASC,
            email ASC
    ");

}

$contactsStmt->bind_param("i", $current_user_id);
$contactsStmt->execute();
$contacts = $contactsStmt->get_result();

/*
|--------------------------------------------------------------------------
| Receiver details
|--------------------------------------------------------------------------
*/
$receiver = null;

if ($receiver_id > 0) {
    $receiverStmt = $conn->prepare("
    SELECT id, shop_name, email, role, shop_image
    FROM users
    WHERE id = ?
    LIMIT 1
");
    $receiverStmt->bind_param("i", $receiver_id);
    $receiverStmt->execute();
    $receiver = $receiverStmt->get_result()->fetch_assoc();

    $readStmt = $conn->prepare("
        UPDATE messages
        SET is_read = 1
        WHERE sender_user_id = ?
          AND receiver_user_id = ?
    ");

    $readStmt->bind_param("ii", $receiver_id, $current_user_id);
    $readStmt->execute();
}

/*
|--------------------------------------------------------------------------
| Conversation
|--------------------------------------------------------------------------
*/
$conversation = null;

if ($receiver_id > 0) {
    $msgStmt = $conn->prepare("
        SELECT *
        FROM messages
        WHERE 
            (
                sender_user_id = ?
                AND receiver_user_id = ?
            )
            OR
            (
                sender_user_id = ?
                AND receiver_user_id = ?
            )
        ORDER BY created_at ASC
    ");

    $msgStmt->bind_param(
        "iiii",
        $current_user_id,
        $receiver_id,
        $receiver_id,
        $current_user_id
    );

    $msgStmt->execute();
    $conversation = $msgStmt->get_result();
}
?>

<div class="container-fluid px-0 messenger-page">

    <div class="d-flex justify-content-between align-items-center flex-wrap gap-3 mb-4">
        <div>
            <h1 class="fw-bold mb-1">Messages</h1>
            <p class="text-muted mb-0">
                Chat with customers and partner shops in the system.
            </p>
        </div>
    </div>

    <div class="messenger-card">

        <!-- LEFT SIDE: CONTACTS -->
        <div class="messenger-sidebar">

            <div class="messenger-sidebar-header">
                <h5 class="fw-bold mb-3">Chats</h5>

                <div class="search-chat-box">
                    <i class="fa-solid fa-magnifying-glass text-muted"></i>
                    <input type="text" id="searchChat" placeholder="Search user...">
                </div>
            </div>

            <div class="conversation-list" id="conversationList">

                <?php if ($contacts && $contacts->num_rows > 0): ?>
                    <?php while ($contact = $contacts->fetch_assoc()): ?>

                        <?php
                            $contactName = displayName($contact);
                            $contactRole = !empty($contact["role"]) ? ucfirst($contact["role"]) : "User";
                        ?>

                        <a 
                           href="<?php echo $messagePageLink; ?>&receiver_id=<?php echo (int)$contact["id"]; ?>"
                            class="conversation-item <?php echo $receiver_id === (int)$contact["id"] ? "active" : ""; ?>"
                            data-name="<?php echo strtolower(h($contactName)); ?>"
                        >
                            <div class="avatar">
                                <?php if (!empty($contact["shop_image"])): ?>
                                    <img src="../uploads/<?php echo h($contact["shop_image"]); ?>" alt="Profile">
                                <?php else: ?>
                                    <i class="fa-solid <?php echo strtolower($contact["role"]) === "customer" ? "fa-user" : "fa-shop"; ?>"></i>
                                <?php endif; ?>
                            </div>

                            <div class="conversation-info">
                                <strong><?php echo h($contactName); ?></strong>
                                <small><?php echo h($contactRole); ?></small>
                            </div>
                        </a>

                    <?php endwhile; ?>
                <?php else: ?>
                    <div class="empty-side">
                        <i class="fa-solid fa-comments"></i>
                        <p>No users found.</p>
                    </div>
                <?php endif; ?>

            </div>

        </div>

        <!-- RIGHT SIDE: CHAT -->
        <div class="messenger-chat">

            <?php if ($receiver_id > 0 && $receiver): ?>

                <div class="chat-header">

    <?php if ($isPopup): ?>
       <a href="<?php echo $backToMessagesLink; ?>" class="popup-back-btn">
    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" stroke="#0ea5e9" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-arrow-left">
        <line x1="19" y1="12" x2="5" y2="12"/>
        <polyline points="12 19 5 12 12 5"/>
    </svg>
</a>
        
    <?php endif; ?>

    <div class="avatar">
                        <?php if (!empty($receiver["shop_image"])): ?>
                            <img src="../uploads/<?php echo h($receiver["shop_image"]); ?>" alt="Profile">
                        <?php else: ?>
                            <i class="fa-solid <?php echo strtolower($receiver["role"]) === "customer" ? "fa-user" : "fa-shop"; ?>"></i>
                        <?php endif; ?>
                    </div>

                    <div>
                        <h5 class="fw-bold mb-0"><?php echo h(displayName($receiver)); ?></h5>
                        <small class="text-muted">
                            <?php echo h(!empty($receiver["role"]) ? ucfirst($receiver["role"]) : "User"); ?>
                        </small>
                    </div>

                </div>

                <div class="chat-body" id="chatBody">

                    <?php if ($conversation && $conversation->num_rows > 0): ?>
                        <?php while ($msg = $conversation->fetch_assoc()): ?>

                            <?php $isMine = (int)$msg["sender_user_id"] === $current_user_id; ?>

                            <div class="message-row <?php echo $isMine ? "mine" : "theirs"; ?>">
                                <div class="message-bubble">
                                    <p><?php echo nl2br(h($msg["message_text"])); ?></p>
                                    <small><?php echo h(formatTime($msg["created_at"])); ?></small>
                                </div>
                            </div>

                        <?php endwhile; ?>
                    <?php else: ?>
                        <div class="empty-chat">
                            <i class="fa-solid fa-message"></i>
                            <p>No messages yet. Start the conversation.</p>
                        </div>
                    <?php endif; ?>

                </div>

    <form action="send_message.php" method="POST" class="chat-form">
    <input type="hidden" name="receiver_user_id" value="<?php echo (int)$receiver_id; ?>">
    <input type="hidden" name="order_id" value="<?php echo (int)$order_id; ?>">

    <textarea 
        name="message_text" 
        class="form-control" 
        placeholder="Aa"
        required
    ></textarea>

    <button type="submit" class="send-btn">
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="#fff" viewBox="0 0 24 24">
            <path d="M2 21l21-9L2 3v7l15 2-15 2v7z"/>
        </svg>
    </button>
</form>

            <?php else: ?>

                <div class="empty-chat-main">
                    <i class="fa-solid fa-comments"></i>
                    <h5 class="fw-bold mb-1">Select a conversation</h5>
                    <p class="text-muted mb-0">Choose a customer or shop to start chatting.</p>
                </div>

            <?php endif; ?>

        </div>

    </div>

</div>

<style>

   <?php if ($isPopup): ?>

html,
body {
    height: 100%;
    margin: 0 !important;
    padding: 0 !important;
    overflow: hidden !important;
    background: #ffffff !important;
}

.messenger-page {
     height: 100% !important;
    width: 100% !important;
    padding: 0 !important;
    margin: 0 !important;
}

.messenger-page > .d-flex {
    display: none !important;
}

.messenger-card {
     height: 100% !important;
    min-height: 0 !important;
    border-radius: 0 !important;
    box-shadow: none !important;
    overflow: hidden !important;
    display: grid !important;
    background: #ffffff !important;
}

/* Default popup view: show only list of people */
<?php if ($receiver_id <= 0): ?>

.messenger-card {
    grid-template-columns: 1fr !important;
}

.messenger-sidebar {
    display: block !important;
    height: 100vh !important;
    border-right: none !important;
}

.messenger-chat {
    display: none !important;
}

<?php else: ?>

/* Conversation view: hide people list and show only chat */
.messenger-card {
    grid-template-columns: 1fr !important;
}

.messenger-sidebar {
    display: none !important;
}

.messenger-chat {
    display: flex !important;
     height: 100% !important;
}

<?php endif; ?>

.messenger-sidebar-header {
    padding: 18px !important;
}

.messenger-sidebar-header h5 {
    font-size: 22px !important;
    margin-bottom: 14px !important;
}

.search-chat-box {
    padding: 12px 14px !important;
}

.search-chat-box input {
    font-size: 14px !important;
}

.conversation-list {
    height: calc(100vh - 100px) !important;
    max-height: none !important;
    overflow-y: auto !important;
    padding: 10px !important;
}

.conversation-item {
    padding: 12px !important;
    gap: 12px !important;
    border-radius: 16px !important;
}

.avatar {
    width: 46px !important;
    height: 46px !important;
}

.conversation-info strong {
    font-size: 15px !important;
}

.conversation-info small {
    font-size: 12px !important;
}

.chat-header {
    height: 64px !important;
    padding: 10px 14px !important;
    flex-shrink: 0 !important;
}

.popup-back-btn {
    width: 46px;
    height: 46px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    background-color: #f1f1f1;
    cursor: pointer;
    transition: 0.3s;
}

.popup-back-btn:hover {
    background-color: #e2f0ff;
}



.chat-header h5 {
    font-size: 16px !important;
}

.chat-header small {
    font-size: 12px !important;
}

.chat-body {
    flex: 1 !important;
    min-height: 0 !important;
    height: auto !important;
    overflow-y: auto !important;
    padding: 14px !important;
}

.message-bubble {
    max-width: 78% !important;
    padding: 10px 13px !important;
    font-size: 14px !important;
}
.chat-form {
    display: flex;          /* keep items in a row */
    align-items: center;
    gap: 10px;
    padding: 10px 14px;
    background: #fff;
    border-top: 1px solid #eef2f7;
}

/* Make textarea fill all remaining space and prevent shrinking */
.chat-form textarea {
    flex: 1;                /* important! */
    min-height: 46px;
    max-height: 90px;
    resize: none;
    border-radius: 999px;
    padding: 12px 16px;
    font-size: 14px;
    border: 1px solid #d1d5db;
}

/* Keep send button on the right, fixed size */
.send-btn {
    width: 46px;
    height: 46px;
    border-radius: 50%;
    background-color: #0ea5e9;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    flex-shrink: 0;          /* prevents shrinking */
}

.send-btn:hover {
    background-color: #0284c7;
}

.empty-chat,
.empty-chat-main {
    min-height: 0 !important;
    height: 100% !important;
    padding: 16px !important;
}

@media (max-width: 600px) {
    .message-bubble {
        max-width: 84% !important;
    }
}

<?php endif; ?>

.messenger-page h1 {
    font-size: clamp(26px, 2.2vw, 38px);
    color: #111827;
}

.messenger-card {
    background: #fff;
    border-radius: 24px;
    box-shadow: 0 8px 26px rgba(0,0,0,0.06);
    overflow: hidden;
    height: calc(100vh - 190px);
    min-height: 580px;
    display: grid;
    grid-template-columns: 340px minmax(0, 1fr);
}

.messenger-sidebar {
    border-right: 1px solid #eef2f7;
    background: #fff;
    min-width: 0;
    overflow: hidden;
}

.messenger-sidebar-header {
    padding: 20px;
    border-bottom: 1px solid #eef2f7;
}

.search-chat-box {
    background: #f3f5f8;
    border-radius: 999px;
    padding: 9px 14px;
    display: flex;
    align-items: center;
    gap: 10px;
}

.search-chat-box input {
    border: none;
    outline: none;
    background: transparent;
    width: 100%;
    font-size: 14px;
}

.conversation-list {
    height: calc(100% - 115px);
    overflow-y: auto;
    padding: 12px;
}

.conversation-item {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 12px;
    border-radius: 16px;
    text-decoration: none;
    color: #111827;
    transition: 0.2s ease;
}

.conversation-item:hover,
.conversation-item.active {
    background: #e0f2fe;
}

.avatar {
    width: 46px;
    height: 46px;
    border-radius: 50%;
    background: #0ea5e9;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    flex-shrink: 0;
}

.avatar img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.conversation-info {
    min-width: 0;
}

.conversation-info strong {
    display: block;
    color: #111827;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.conversation-info small {
    color: #6b7280;
}

.messenger-chat {
    min-width: 0;
    display: flex;
    flex-direction: column;
    background: #f8fafc;
}

.chat-header {
    height: 72px;
    background: #fff;
    border-bottom: 1px solid #eef2f7;
    padding: 14px 20px;
    display: flex;
    align-items: center;
    gap: 12px;
    flex-shrink: 0;
}

.chat-body {
    flex: 1;
    overflow-y: auto;
    padding: 22px;
}

.message-row {
    display: flex;
    margin-bottom: 12px;
}

.message-row.mine {
    justify-content: flex-end;
}

.message-row.theirs {
    justify-content: flex-start;
}

.message-bubble {
    max-width: min(70%, 560px);
    padding: 12px 14px;
    border-radius: 20px;
    word-wrap: break-word;
}

.message-row.mine .message-bubble {
    background: #0ea5e9;
    color: #fff;
    border-bottom-right-radius: 5px;
}

.message-row.theirs .message-bubble {
    background: #fff;
    color: #111827;
    border: 1px solid #eef2f7;
    border-bottom-left-radius: 5px;
}

.message-bubble p {
    margin: 0 0 6px;
}

.message-bubble small {
    font-size: 11px;
    opacity: 0.8;
}

.chat-form {
    background: #fff;
    border-top: 1px solid #eef2f7;
    padding: 14px;
    display: flex;
    align-items: center;
    gap: 10px;
    flex-shrink: 0;
}

.chat-form textarea {
    resize: none;
    border-radius: 999px;
    padding: 12px 16px;
    min-height: 46px;
    max-height: 90px;
}

.send-btn {
    width: 46px;
    height: 46px;
    border: none;
    border-radius: 50%;
    background: #0ea5e9;
    color: #fff;
    display: grid;
    place-items: center;
    flex-shrink: 0;
}

.send-btn:hover {
    background: #0284c7;
}

.empty-chat,
.empty-chat-main,
.empty-side {
    height: 100%;
    min-height: 260px;
    color: #6b7280;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    text-align: center;
}

.empty-chat i,
.empty-chat-main i,
.empty-side i {
    font-size: 42px;
    color: #9ca3af;
    margin-bottom: 12px;
}

@media (max-width: 992px) {
    .messenger-card {
        height: auto;
        min-height: auto;
        grid-template-columns: 1fr;
    }

    .messenger-sidebar {
        border-right: 0;
        border-bottom: 1px solid #eef2f7;
    }

    .conversation-list {
        max-height: 280px;
    }

    .chat-body {
        height: 430px;
    }

    .message-bubble {
        max-width: 88%;
    }

    /* =========================
   MOBILE POPUP MESSAGE SIZE FIX
========================= */
<?php if ($isPopup): ?>

@media (max-width: 767.98px) {
    html,
    body {
        width: 100%;
        height: 100%;
        overflow: hidden !important;
    }

    .messenger-page {
        height: 100% !important;
        width: 100% !important;
        padding: 0 !important;
        margin: 0 !important;
    }

    .messenger-card {
        height: 100% !important;
        min-height: 0 !important;
        border-radius: 0 !important;
        display: grid !important;
        grid-template-columns: 1fr !important;
    }

    .messenger-chat {
        height: 100% !important;
        min-height: 0 !important;
        display: flex !important;
        flex-direction: column !important;
    }

    .chat-header {
        height: 54px !important;
        min-height: 54px !important;
        padding: 7px 10px !important;
        gap: 8px !important;
    }

    .popup-back-btn {
        width: 36px !important;
        height: 36px !important;
        flex: 0 0 36px !important;
    }

    .popup-back-btn svg {
        width: 20px !important;
        height: 20px !important;
    }

    .avatar {
        width: 36px !important;
        height: 36px !important;
        flex: 0 0 36px !important;
    }

    .chat-header h5 {
        font-size: 14px !important;
        line-height: 1.1 !important;
    }

    .chat-header small {
        font-size: 10px !important;
    }

    .chat-body {
        flex: 1 1 auto !important;
        min-height: 0 !important;
        height: auto !important;
        overflow-y: auto !important;
        overflow-x: hidden !important;
        padding: 10px !important;
    }

    .message-row {
        margin-bottom: 8px !important;
    }

    .message-bubble {
        max-width: 74% !important;
        padding: 8px 11px !important;
        border-radius: 16px !important;
        font-size: 12px !important;
        line-height: 1.25 !important;
    }

    .message-bubble p {
        margin: 0 0 4px !important;
        font-size: 12px !important;
        line-height: 1.25 !important;
    }

    .message-bubble small {
        font-size: 9px !important;
        line-height: 1 !important;
    }

    .chat-form {
        padding: 8px 10px !important;
        gap: 8px !important;
        min-height: 56px !important;
    }

    .chat-form textarea {
        min-height: 38px !important;
        max-height: 70px !important;
        padding: 9px 13px !important;
        font-size: 12px !important;
        line-height: 1.2 !important;
    }

    .send-btn {
        width: 38px !important;
        height: 38px !important;
        flex: 0 0 38px !important;
    }

    .send-btn svg {
        width: 20px !important;
        height: 20px !important;
    }
}

@media (max-width: 480px) {
    .chat-header {
        height: 50px !important;
        min-height: 50px !important;
        padding: 6px 8px !important;
    }

    .popup-back-btn,
    .avatar {
        width: 34px !important;
        height: 34px !important;
        flex: 0 0 34px !important;
    }

    .message-bubble {
        max-width: 72% !important;
        font-size: 11.5px !important;
        padding: 7px 10px !important;
    }

    .message-bubble p {
        font-size: 11.5px !important;
    }

    .chat-form {
        padding: 7px 8px !important;
    }

    .chat-form textarea {
        min-height: 36px !important;
        font-size: 12px !important;
    }

    .send-btn {
        width: 36px !important;
        height: 36px !important;
        flex: 0 0 36px !important;
    }
}

<?php endif; ?>
}
</style>

<script>
document.querySelector('.chat-form').addEventListener('submit', function(e) {
    e.preventDefault(); // stop normal form submission

    const form = this;
    const formData = new FormData(form);

    fetch(form.action, { method: 'POST', body: formData })
        .then(res => res.json())
        .then(res => {
            if(res.status === 'success') {
                const chatBody = document.getElementById('chatBody');
                const div = document.createElement('div');
                div.className = 'message-row mine';
                div.innerHTML = `<div class="message-bubble">
                                    <p>${res.message_text}</p>
                                    <small>${res.created_at}</small>
                                 </div>`;
                chatBody.appendChild(div);
                chatBody.scrollTop = chatBody.scrollHeight;
                form.querySelector('textarea').value = '';
            } else {
                console.error(res.error);
                alert("Failed to send message.");
            }
        });
});
</script>