<?php
include_once "../global.php";

$pageTitle = "WhatsApp Inbox - ";
include_once '../header.php';
?>

<style>
    .wa-bubble{
        max-width: 70%;
        padding: 10px 12px;
        margin: 6px 0;
        word-wrap: break-word;
        white-space: pre-wrap;
    }
    .wa-bubble.wa-out{
        background-color: #242626;
        margin-left: auto;
    }
    .wa-bubble.wa-in{
        background-color: #144d37;
    }
</style>
<!--breadcrumb-->
<div class="page-breadcrumb d-none d-sm-flex align-items-center mb-3">
    <div class="breadcrumb-title pe-3">WhatsApp Management</div>
    <div class="ps-3">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb mb-0 p-0">
                <li class="breadcrumb-item"><a href="javascript:;"></a>
                </li>
                <li class="breadcrumb-item active" aria-current="page">Inbox</li>
            </ol>
        </nav>
    </div>
</div>
<!--end breadcrumb-->
<div class="card">
    <div class="card-body p-4">
        <h5 class="mb-4">Inbox</h5>
        <div class="row g-3">
            <div class="col-md-4" id="waList">
                <div class="form-group mb-2">
                    <input type="text" id="waSearch" class="form-control" placeholder="Search name or phone...">
                </div>
                <div class="border border-2 border-light rounded p-2">
                    <ul id="waListBody" class="list-group list-group-flush"></ul>
                </div>
            </div>
            <div class="col-md-8" id="waThread">
                <div class="border border-2 border-light rounded p-2 mb-2">
                    <div>
                        <div id="threadName" class="fw-bold"></div>
                        <div id="threadPhone" class="text-muted"></div>
                    </div>
                    <div><span id="threadMeta" class="text-muted"></span></div>
                </div>
                <div class="border border-2 border-light rounded p-3 mb-2" id="waThreadBody">
                    <div class="text-muted">Select a conversation from the left.</div>
                </div>
                <div class="form-group mb-2">
                    <textarea id="waMsg" class="form-control" placeholder="Type a message…"></textarea>
                </div>
                <div class="form-group mb-2">
                    <input type="url" id="waMedia" class="form-control" placeholder="Media URL (optional)">
                </div>
                <div class="form-group">
                    <button id="waSend" class="btn btn-grd-primary">Send</button>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    let currentPhone = null;
    let autoRefresh = null;

    function loadList(q = '') {
        $.post('<?php echo WEB_URL; ?>/ajax_call?page=waList', {
            q
        }, function(html) {
            $('#waListBody').html(html);
        });
    }

    function bindListClicks() {
        $('#waListBody').on('click', '.wa-item', function() {
            const phone = $(this).data('phone');
            const name = $(this).data('name') || '';
            openThread(phone, name);
        });
    }

    function openThread(phone, name) {
        currentPhone = phone;
        $('#threadName').text(name || '(unknown)');
        $('#threadPhone').text(phone);
        $('#waThreadBody').html('<div class="muted">Loading…</div>');
        refreshThread();

        if (autoRefresh) clearInterval(autoRefresh);
        autoRefresh = setInterval(refreshThread, 5000);
    }

    function refreshThread() {
        if (!currentPhone) return;
        $.post('<?php echo WEB_URL; ?>/ajax_call?page=waLoadThread', {
            phone: currentPhone
        }, function(html) {
            $('#waThreadBody').html(html);
            const el = document.getElementById('waThreadBody');
            el.scrollTop = el.scrollHeight;
        });
    }

    function sendFromThread() {
        if (!currentPhone) return;
        const body = $('#waMsg').val().trim();
        const media = $('#waMedia').val().trim();
        if (body === '' && media === '') {
            showAlert('Type a message or provide a media URL.');
            return;
        }

        $("#spinner-overlay").fadeIn('fast');
        $.post('<?php echo WEB_URL; ?>/ajax_call?page=waSendFromThread', {
            to: currentPhone,
            body,
            media
        }, function(res) {
            try {
                res = JSON.parse(res);
            } catch (e) {}
            if (res && res.status === 'success') {
                $('#waMsg').val('');
                $('#waMedia').val('');
                refreshThread();
            } else {
                showAlert(res && res.message ? res.message : 'Failed to send.');
            }
        }).always(function() {
            $("#spinner-overlay").fadeOut('fast');
        });
    }

    $('#waSend').on('click', sendFromThread);
    $('#waMsg').on('keypress', function(e) {
        if (e.which === 13 && !e.shiftKey) {
            e.preventDefault();
            sendFromThread();
        }
    });
    $('#waSearch').on('input', function() {
        loadList($(this).val().trim());
    });

    $(function() {
        loadList();
        bindListClicks();
    });
</script>

<?php include_once '../footer.php'; ?>