<?= $this->extend('layouts/main') ?>
<?= $this->section('content') ?>

<div class="d-flex justify-content-between align-items-start mb-3">
    <div>
        <h1 class="h3 mb-1">Communication</h1>
        <p class="text-muted mb-0">Every WhatsApp/SMS message and logged call this hotel has sent/recorded — see Settings to change which channel each automated message type uses.</p>
    </div>
    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#sendMessageModal"><i class="bi bi-send me-1"></i>Send New Message</button>
</div>

<div class="row g-3 mb-3">
    <div class="col-6 col-lg-3">
        <div class="card h-100"><div class="card-body d-flex align-items-center gap-3">
            <div class="rounded-3 bg-primary-subtle text-primary d-flex align-items-center justify-content-center flex-shrink-0" style="width: 44px; height: 44px;"><i class="bi bi-chat-dots-fill fs-5"></i></div>
            <div>
                <div class="text-muted small">SMS</div>
                <div class="fs-4 fw-bold"><?= number_format($stats['sms']) ?></div>
                <div class="text-muted small">Messages</div>
            </div>
        </div></div>
    </div>
    <div class="col-6 col-lg-3">
        <div class="card h-100"><div class="card-body d-flex align-items-center gap-3">
            <div class="rounded-3 bg-success-subtle text-success d-flex align-items-center justify-content-center flex-shrink-0" style="width: 44px; height: 44px;"><i class="bi bi-whatsapp fs-5"></i></div>
            <div>
                <div class="text-muted small">WhatsApp</div>
                <div class="fs-4 fw-bold"><?= number_format($stats['whatsapp']) ?></div>
                <div class="text-muted small">Messages</div>
            </div>
        </div></div>
    </div>
    <div class="col-6 col-lg-3">
        <div class="card h-100"><div class="card-body d-flex align-items-center gap-3">
            <div class="rounded-3 bg-info-subtle text-info d-flex align-items-center justify-content-center flex-shrink-0" style="width: 44px; height: 44px;"><i class="bi bi-telephone-fill fs-5"></i></div>
            <div>
                <div class="text-muted small">Calls</div>
                <div class="fs-4 fw-bold"><?= number_format($stats['calls']) ?></div>
                <div class="text-muted small">Logs</div>
            </div>
        </div></div>
    </div>
    <div class="col-6 col-lg-3">
        <div class="card h-100"><div class="card-body d-flex align-items-center gap-3">
            <div class="rounded-3 bg-danger-subtle text-danger d-flex align-items-center justify-content-center flex-shrink-0" style="width: 44px; height: 44px;"><i class="bi bi-exclamation-triangle-fill fs-5"></i></div>
            <div>
                <div class="text-muted small">Failed</div>
                <div class="fs-4 fw-bold"><?= number_format($stats['failed']) ?></div>
                <div class="text-muted small">Messages</div>
            </div>
        </div></div>
    </div>
</div>

<div class="card shadow-sm mb-3">
    <div class="card-body">
        <form action="<?= site_url('communication') ?>" method="get" class="row g-2 align-items-center">
            <div class="col-md-4">
                <div class="input-group input-group-sm">
                    <span class="input-group-text bg-white"><i class="bi bi-calendar3"></i></span>
                    <input type="date" class="form-control" name="date_from" value="<?= esc($filters['date_from']) ?>" title="From">
                    <input type="date" class="form-control" name="date_to" value="<?= esc($filters['date_to']) ?>" title="To">
                </div>
            </div>
            <div class="col-md-3 col-6">
                <select class="form-select form-select-sm" name="channel">
                    <option value="">All Channels</option>
                    <option value="sms" <?= $filters['channel'] === 'sms' ? 'selected' : '' ?>>SMS</option>
                    <option value="whatsapp" <?= $filters['channel'] === 'whatsapp' ? 'selected' : '' ?>>WhatsApp</option>
                    <option value="call" <?= $filters['channel'] === 'call' ? 'selected' : '' ?>>Call</option>
                    <option value="note" <?= $filters['channel'] === 'note' ? 'selected' : '' ?>>Note</option>
                </select>
            </div>
            <div class="col-md-3 col-6">
                <select class="form-select form-select-sm" name="status">
                    <option value="">All Status</option>
                    <option value="sent" <?= $filters['status'] === 'sent' ? 'selected' : '' ?>>Sent</option>
                    <option value="failed" <?= $filters['status'] === 'failed' ? 'selected' : '' ?>>Failed</option>
                    <option value="logged" <?= $filters['status'] === 'logged' ? 'selected' : '' ?>>Logged</option>
                </select>
            </div>
            <div class="col-md-2">
                <button type="submit" class="btn btn-sm btn-outline-primary w-100"><i class="bi bi-funnel me-1"></i>Filter</button>
            </div>
        </form>
    </div>
</div>

<div class="card shadow-sm">
    <div class="table-scroll">
        <table class="table table-hover mb-0 align-middle small">
            <thead class="table-light">
                <tr><th>Date &amp; Time</th><th>Guest / To</th><th>Type</th><th>Channel</th><th>Message</th><th>Status</th><th>Sent By</th><th class="text-end">Actions</th></tr>
            </thead>
            <tbody>
            <?php if (empty($entries)): ?>
                <tr><td colspan="8" class="text-center text-muted py-4">No messages match this search/filter.</td></tr>
            <?php endif; ?>
            <?php foreach ($entries as $e):
                $channelMeta = [
                    'sms'      => ['label' => 'SMS', 'badge' => 'primary'],
                    'whatsapp' => ['label' => 'WhatsApp', 'badge' => 'success'],
                    'call'     => ['label' => 'Call', 'badge' => 'info'],
                    'note'     => ['label' => 'Note', 'badge' => 'secondary'],
                ][$e->channel] ?? ['label' => ucfirst($e->channel), 'badge' => 'secondary'];

                $statusMeta = [
                    'sent'   => ['label' => 'Delivered', 'badge' => 'success'],
                    'failed' => ['label' => 'Failed', 'badge' => 'danger'],
                    'logged' => ['label' => 'Logged', 'badge' => 'info'],
                ][$e->status] ?? ['label' => ucfirst($e->status), 'badge' => 'secondary'];

                // See CommunicationController's view-data comment / MessageLogModel::logManual():
                // pre-migration manual (call/note) rows kept their text in
                // provider_response; automated rows before this migration
                // have no readable body at all, so they show "—" rather
                // than a raw gateway response dressed up as a message.
                $messageText = $e->body ?? (in_array($e->channel, ['call', 'note'], true) ? $e->provider_response : null);
            ?>
                <tr>
                    <td class="text-nowrap text-muted"><?= esc(date('d M Y, g:i a', strtotime($e->created_at))) ?></td>
                    <td><?= esc($e->guest_name ?? $e->to_phone ?? '—') ?></td>
                    <td class="text-muted"><?= esc(ucwords(str_replace('_', ' ', $e->message_type))) ?></td>
                    <td><span class="badge bg-<?= $channelMeta['badge'] ?>"><?= esc($channelMeta['label']) ?></span></td>
                    <td class="text-truncate" style="max-width: 260px;"><?= esc($messageText ?? '—') ?></td>
                    <td><span class="badge bg-<?= $statusMeta['badge'] ?>"><?= esc($statusMeta['label']) ?></span></td>
                    <td class="text-muted"><?= esc($e->sent_by_name ?? 'System') ?></td>
                    <td class="text-end">
                        <button type="button" class="btn btn-sm btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#viewMessageModal"
                                data-when="<?= esc(date('d M Y, g:i a', strtotime($e->created_at))) ?>"
                                data-to="<?= esc($e->guest_name ?? $e->to_phone ?? '—') ?>"
                                data-phone="<?= esc($e->to_phone ?? '—') ?>"
                                data-type="<?= esc(ucwords(str_replace('_', ' ', $e->message_type))) ?>"
                                data-channel="<?= esc($channelMeta['label']) ?>"
                                data-status="<?= esc($statusMeta['label']) ?>"
                                data-sentby="<?= esc($e->sent_by_name ?? 'System') ?>"
                                data-message="<?= esc($messageText ?? 'No message text recorded for this entry.') ?>">
                            <i class="bi bi-eye"></i>
                        </button>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php if (! empty($entries)): ?>
    <?php
        $current = $pager->getCurrentPage();
        $total   = $pager->getTotal();
        $totalPages = max(1, (int) ceil($total / $perPage));
        $first   = ($current - 1) * $perPage + 1;
        $last    = min($current * $perPage, $total);
        $qs      = array_merge($filters, ['per_page' => $perPage]);
    ?>
    <div class="card-footer bg-white d-flex justify-content-between align-items-center flex-wrap gap-2">
        <span class="text-muted small">Showing <?= $first ?> to <?= $last ?> of <?= number_format($total) ?> messages</span>
        <div class="d-flex align-items-center gap-2">
            <nav>
                <ul class="pagination pagination-sm mb-0">
                    <li class="page-item <?= $current <= 1 ? 'disabled' : '' ?>">
                        <a class="page-link" href="<?= site_url('communication?' . http_build_query(array_merge($qs, ['page' => $current - 1]))) ?>"><i class="bi bi-chevron-left"></i></a>
                    </li>
                    <?php
                        $windowStart = max(1, $current - 2);
                        $windowEnd   = min($totalPages, $current + 2);
                    ?>
                    <?php if ($windowStart > 1): ?><li class="page-item"><a class="page-link" href="<?= site_url('communication?' . http_build_query(array_merge($qs, ['page' => 1]))) ?>">1</a></li><li class="page-item disabled"><span class="page-link">&hellip;</span></li><?php endif; ?>
                    <?php for ($p = $windowStart; $p <= $windowEnd; $p++): ?>
                        <li class="page-item <?= $p === $current ? 'active' : '' ?>">
                            <a class="page-link" href="<?= site_url('communication?' . http_build_query(array_merge($qs, ['page' => $p]))) ?>"><?= $p ?></a>
                        </li>
                    <?php endfor; ?>
                    <?php if ($windowEnd < $totalPages): ?><li class="page-item disabled"><span class="page-link">&hellip;</span></li><li class="page-item"><a class="page-link" href="<?= site_url('communication?' . http_build_query(array_merge($qs, ['page' => $totalPages]))) ?>"><?= $totalPages ?></a></li><?php endif; ?>
                    <li class="page-item <?= $current >= $totalPages ? 'disabled' : '' ?>">
                        <a class="page-link" href="<?= site_url('communication?' . http_build_query(array_merge($qs, ['page' => $current + 1]))) ?>"><i class="bi bi-chevron-right"></i></a>
                    </li>
                </ul>
            </nav>
            <form action="<?= site_url('communication') ?>" method="get" id="perPageForm">
                <?php foreach (['date_from', 'date_to', 'channel', 'status'] as $key): ?>
                    <input type="hidden" name="<?= $key ?>" value="<?= esc($filters[$key]) ?>">
                <?php endforeach; ?>
                <select class="form-select form-select-sm" name="per_page" onchange="document.getElementById('perPageForm').submit();" style="width: auto;">
                    <option value="10" <?= $perPage === 10 ? 'selected' : '' ?>>10 per page</option>
                    <option value="25" <?= $perPage === 25 ? 'selected' : '' ?>>25 per page</option>
                    <option value="50" <?= $perPage === 50 ? 'selected' : '' ?>>50 per page</option>
                </select>
            </form>
        </div>
    </div>
    <?php endif; ?>
</div>

<!-- Send New Message: a real SMS via Hubtel, not WhatsApp (see CommunicationController::send()'s doc comment for why). -->
<div class="modal fade" id="sendMessageModal" tabindex="-1">
    <div class="modal-dialog">
        <form action="<?= site_url('communication/send') ?>" method="post" class="modal-content">
            <?= csrf_field() ?>
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-send me-2"></i>Send New Message</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3 position-relative">
                    <label class="form-label small fw-semibold">Find a Guest <span class="text-muted fw-normal">(optional)</span></label>
                    <input type="text" class="form-control" id="guestSearchInput" placeholder="Search by name or phone..." autocomplete="off">
                    <input type="hidden" name="guest_id" id="guestIdField">
                    <div id="guestSearchResults" class="list-group position-absolute w-100 shadow-sm" style="z-index: 10; max-height: 200px; overflow-y: auto;"></div>
                    <div id="guestSelectedInfo" class="small text-success mt-1 d-none"></div>
                </div>
                <div class="mb-3">
                    <label class="form-label small fw-semibold">Phone Number</label>
                    <input type="text" class="form-control" name="to_phone" id="toPhoneField" required placeholder="e.g. 0244123456">
                </div>
                <div class="mb-1">
                    <label class="form-label small fw-semibold">Message</label>
                    <textarea class="form-control" name="message" rows="4" maxlength="480" required placeholder="Type your message..." id="messageField"></textarea>
                </div>
                <div class="text-muted small text-end" id="charCount">0 / 480</div>
                <div class="alert alert-warning small mb-0"><i class="bi bi-info-circle me-1"></i>Sends a real SMS via this hotel's Hubtel account — this uses your SMS credits.</div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" class="btn btn-primary"><i class="bi bi-send me-1"></i>Send Message</button>
            </div>
        </form>
    </div>
</div>

<!-- Shared view-details modal, populated from the clicked row's data-* attributes rather than one modal per row. -->
<div class="modal fade" id="viewMessageModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-chat-square-text me-2"></i>Message Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body small">
                <div class="row row-cols-2 g-3 mb-3">
                    <div class="col"><span class="text-muted">Date &amp; Time</span><br><span class="fw-semibold" id="vm-when"></span></div>
                    <div class="col"><span class="text-muted">To</span><br><span class="fw-semibold" id="vm-to"></span></div>
                    <div class="col"><span class="text-muted">Phone</span><br><span class="fw-semibold" id="vm-phone"></span></div>
                    <div class="col"><span class="text-muted">Type</span><br><span class="fw-semibold" id="vm-type"></span></div>
                    <div class="col"><span class="text-muted">Channel</span><br><span class="fw-semibold" id="vm-channel"></span></div>
                    <div class="col"><span class="text-muted">Status</span><br><span class="fw-semibold" id="vm-status"></span></div>
                    <div class="col"><span class="text-muted">Sent By</span><br><span class="fw-semibold" id="vm-sentby"></span></div>
                </div>
                <div class="text-muted mb-1">Message</div>
                <p class="border rounded p-2 mb-0" id="vm-message"></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<script>
document.getElementById('viewMessageModal').addEventListener('show.bs.modal', function (event) {
    const btn = event.relatedTarget;
    document.getElementById('vm-when').textContent = btn.dataset.when;
    document.getElementById('vm-to').textContent = btn.dataset.to;
    document.getElementById('vm-phone').textContent = btn.dataset.phone;
    document.getElementById('vm-type').textContent = btn.dataset.type;
    document.getElementById('vm-channel').textContent = btn.dataset.channel;
    document.getElementById('vm-status').textContent = btn.dataset.status;
    document.getElementById('vm-sentby').textContent = btn.dataset.sentby;
    document.getElementById('vm-message').textContent = btn.dataset.message;
});

document.getElementById('messageField').addEventListener('input', function () {
    document.getElementById('charCount').textContent = this.value.length + ' / 480';
});

let guestSearchDebounce;
const guestSearchInput = document.getElementById('guestSearchInput');
const guestSearchResults = document.getElementById('guestSearchResults');

guestSearchInput.addEventListener('input', function () {
    clearTimeout(guestSearchDebounce);
    document.getElementById('guestIdField').value = '';
    const q = this.value.trim();

    if (q.length < 2) {
        guestSearchResults.innerHTML = '';
        return;
    }

    guestSearchDebounce = setTimeout(function () {
        fetch('<?= site_url('guests/search-ajax') ?>?q=' + encodeURIComponent(q))
            .then((r) => r.json())
            .then((data) => {
                guestSearchResults.innerHTML = '';
                data.results.forEach(function (g) {
                    const item = document.createElement('button');
                    item.type = 'button';
                    item.className = 'list-group-item list-group-item-action small';
                    item.textContent = g.full_name + (g.phone ? ' — ' + g.phone : '');
                    item.addEventListener('click', function () {
                        document.getElementById('guestIdField').value = g.id;
                        document.getElementById('toPhoneField').value = g.phone || '';
                        guestSearchInput.value = g.full_name;
                        guestSearchResults.innerHTML = '';
                        const info = document.getElementById('guestSelectedInfo');
                        info.textContent = 'Selected: ' + g.full_name;
                        info.classList.remove('d-none');
                    });
                    guestSearchResults.appendChild(item);
                });
            });
    }, 300);
});
</script>

<?= $this->endSection() ?>
