<div class="rounded-2xl border border-border bg-card shadow-sm">
    <div class="flex items-center justify-between border-b border-border px-5 py-3">
        <h4 class="text-base font-semibold text-foreground" id="myModalLabel"><?= lang('edit') . ' ' . lang('name') . ' ' . lang('for') . ' ' . fullname($chat_details->to_user_id) ?></h4>
        <button type="button" class="text-muted-foreground hover:text-foreground" data-dismiss="modal" aria-label="<?= lang('close') ?>">&times;</button>
    </div>
    <div class="p-5 space-y-4">
        <?php
        $strong = str_replace("<strong>", "", $chat_details->title);
        $title = str_replace("</strong>", "", $strong); ?>
        <?= form_input_group('title', lang('change') . ' ' . lang('title'), $title, 'text', true, array('id' => 'title', 'placeholder' => fullname($chat_details->to_user_id))); ?>

        <div class="flex items-center justify-end gap-2">
            <button type="button" class="btn btn-default" data-dismiss="modal"><?= lang('close') ?></button>
            <button type="button" data-chat_id="<?= $chat_details->private_chat_id ?>"
                    data-id="<?= $chat_details->private_chat_users_id ?>"
                    class="btn btn-primary changed"><?= lang('save') ?></button>
        </div>
    </div>
</div>

<script>
    document.addEventListener("DOMContentLoaded", () => {
        const btn = document.querySelector(".changed");
        if (!btn) return;
        btn.addEventListener("click", async () => {
            const chatUsersId = btn.dataset.id;
            const chatId = btn.dataset.chatId;
            const title = document.querySelector("#title")?.value || "";
            const formData = new FormData();
            formData.append("chat_users_id", chatUsersId);
            formData.append("title", title);

            const res = await fetch(`<?= base_url()?>chat/change_title/${chatUsersId}`, {
                method: "POST",
                headers: { "X-Requested-With": "XMLHttpRequest" },
                body: formData
            });
            const text = await res.text();
            let payload = null;
            try {
                payload = JSON.parse(text);
            } catch (e) {
                payload = null;
            }

            if (payload) {
                const modal = document.querySelector("#myModal");
                if (modal && window.jQuery) {
                    window.jQuery(modal).modal("hide");
                } else if (modal) {
                    modal.classList.remove("in", "show");
                    modal.setAttribute("aria-hidden", "true");
                }
                const titleNode = document.querySelector(`#open_chat_box_${chatId} .chat_title`);
                if (titleNode) titleNode.textContent = title;
            } else {
                alert(<?= json_encode(lang('ajax_problem')) ?>);
            }
        });
    });
</script>
