<?php
$currentPage = max(1, (int)($conversationMeta['page'] ?? 1));
$totalPages = max(1, (int)($conversationMeta['pages'] ?? 1));
$queryTail = qs_without(['page', 'route']);
$pageBase = 'index.php?route=' . urlencode((string)($inboxRoute ?? 'messages/inboxSms'));
if ($queryTail !== '') {
    $pageBase .= '&' . $queryTail;
}
$pageBase .= '&page=';
?>
<section class="workspace-hero">
    <div>
        <h2><?= e($inboxTitle ?? 'Inbox') ?></h2>
        <p><?= e($inboxDescription ?? '') ?></p>
    </div>
    <div class="workspace-actions">
        <?php if (($inboxChannel ?? 'sms') === 'email'): ?>
            <a class="btn secondary small" href="index.php?route=messages/mailCenter">Open Mail Center</a>
        <?php endif; ?>
        <?php if (can_access('messages.campaigns')): ?>
            <a class="btn secondary small" href="index.php?route=messages/campaignDashboard">Campaign Dashboard</a>
            <a class="btn secondary small" href="index.php?route=messages/campaignStudio">Campaign Studio</a>
        <?php endif; ?>
    </div>
</section>

<section class="grid two">
    <div class="card spaced-card">
        <div class="toolbar"><h2>Send Individual <?= ($inboxChannel ?? 'sms') === 'email' ? 'Email' : 'Message' ?></h2><span class="badge"><?= strtoupper(e($inboxChannel ?? 'sms')) ?></span></div>
        <?php if (($inboxChannel ?? 'sms') === 'email'): ?>
            <form method="post" action="index.php?route=messages/sendEmail" enctype="multipart/form-data">
                <?= csrf_input() ?>
                <div class="form-grid">
                    <select name="contact_id">
                        <option value="">Choose contact</option>
                        <?php foreach (($contacts ?? []) as $contact): if (empty($contact['email'])) continue; ?>
                            <option value="<?= (int)$contact['id'] ?>"><?= e(trim(($contact['first_name'] ?? '') . ' ' . ($contact['last_name'] ?? '')) ?: ($contact['email'] ?? '')) ?> · <?= e($contact['email']) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <input name="to_address" placeholder="Or enter email address">
                </div>
                <select class="template-picker" data-target-body="email-body" data-target-subject="email-subject">
                    <option value="">Optional email template</option>
                    <?php foreach (($emailTemplates ?? []) as $template): ?>
                        <option value="<?= (int)$template['id'] ?>" data-subject="<?= e($template['subject']) ?>" data-body="<?= e($template['body']) ?>"><?= e($template['name']) ?></option>
                    <?php endforeach; ?>
                </select>
                <div class="form-grid">
                    <input id="email-subject" name="subject" placeholder="Subject line">
                    <input type="file" name="attachment">
                </div>
                <textarea id="email-body" name="body" rows="8" placeholder="HTML or plain text body"></textarea>
                <button class="btn primary">Send Email</button>
            </form>
        <?php else: ?>
            <form method="post" action="index.php?route=messages/sendSms">
                <?= csrf_input() ?>
                <div class="form-grid">
                    <select name="contact_id">
                        <option value="">Choose contact</option>
                        <?php foreach (($contacts ?? []) as $contact): if (empty($contact['phone'])) continue; ?>
                            <option value="<?= (int)$contact['id'] ?>"><?= e(trim(($contact['first_name'] ?? '') . ' ' . ($contact['last_name'] ?? '')) ?: ($contact['phone'] ?? '')) ?> · <?= e($contact['phone']) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <input name="to_address" placeholder="Or enter phone number">
                </div>
                <select class="template-picker" data-target-body="sms-body" data-target-subject="">
                    <option value="">Optional SMS template</option>
                    <?php foreach (($smsTemplates ?? []) as $template): ?>
                        <option value="<?= (int)$template['id'] ?>" data-body="<?= e($template['body']) ?>"><?= e($template['name']) ?></option>
                    <?php endforeach; ?>
                </select>
                <input name="media_url" placeholder="Optional media URL for MMS">
                <textarea id="sms-body" name="body" rows="8" placeholder="Message body"></textarea>
                <button class="btn primary">Send SMS/MMS</button>
            </form>
        <?php endif; ?>
    </div>
    <div class="card spaced-card">
        <div class="toolbar"><h2>Workspace Features</h2><span class="badge">Conversation tools</span></div>
        <div class="metric-strip">
            <div class="metric-chip"><strong><?= (int)(($conversationMeta['total'] ?? 0)) ?></strong><span class="small muted">matching conversations</span></div>
            <div class="metric-chip"><strong><?= (int)count($thread ?? []) ?></strong><span class="small muted">messages in current thread</span></div>
            <div class="metric-chip"><strong><?= (int)count($cannedReplies ?? []) ?></strong><span class="small muted">canned replies available</span></div>
        </div>
        <ul class="feature-list small">
            <li>Conversation workflow with assignment, status, and internal notes.</li>
            <?php if (($inboxChannel ?? 'sms') === 'email'): ?><li>Mail Center adds Inbox, Outbox, Sent, Junk, Trash, and custom folders for Gmail-style organization.</li><?php endif; ?>
            <li>Threaded view for the full interaction history with each client.</li>
            <li>Canned replies to speed up individual outreach and follow-up.</li>
        </ul>
        <div class="stacked-badges">
            <a class="btn secondary small" href="index.php?route=settings/profile">My Sending Profile</a>
            <a class="btn secondary small" href="index.php?route=settings/providerStatus">Provider Status</a>
        </div>
    </div>
</section>

<section class="grid conversation-grid">
    <div class="card">
        <div class="toolbar">
            <h2>Conversations</h2>
            <a class="btn secondary small" href="index.php?route=messages/exportCsv&channel=<?= e($inboxChannel ?? 'sms') ?>&<?= e(qs_without(['route', 'channel'])) ?>">Export CSV</a>
        </div>
        <form method="get" class="inline-form toolbar-right stacked-on-mobile">
            <input type="hidden" name="route" value="<?= e($inboxRoute ?? 'messages/inboxSms') ?>">
            <input name="q" placeholder="Search address, subject, body" value="<?= e($filters['q'] ?? '') ?>">
            <select name="direction">
                <option value="all">Any direction</option>
                <option value="inbound" <?= ($filters['direction'] ?? '') === 'inbound' ? 'selected' : '' ?>>Inbound</option>
                <option value="outbound" <?= ($filters['direction'] ?? '') === 'outbound' ? 'selected' : '' ?>>Outbound</option>
            </select>
            <select name="status">
                <option value="all">Any status</option>
                <?php foreach (['queued','sent','delivered','received','failed','undelivered','bounced'] as $status): ?>
                    <option value="<?= $status ?>" <?= ($filters['status'] ?? '') === $status ? 'selected' : '' ?>><?= ucfirst($status) ?></option>
                <?php endforeach; ?>
            </select>
            <select name="per_page">
                <?php foreach (($perPageOptions ?? [15, 25, 50]) as $option): ?>
                    <option value="<?= (int)$option ?>" <?= (int)($perPage ?? 15) === (int)$option ? 'selected' : '' ?>>View <?= (int)$option ?></option>
                <?php endforeach; ?>
            </select>
            <button class="btn secondary small">Filter</button>
        </form>
        <div class="small muted" style="margin-bottom:12px;">Showing <?= e(strtoupper($inboxChannel ?? 'sms')) ?> conversations only. Viewing <?= (int)($perPage ?? 15) ?> per page.</div>
        <div class="conversation-list" data-list-ignore="true">
            <?php foreach (($conversations ?? []) as $conversation): ?>
                <a class="conversation-item <?= ($selectedConversation ?? '') === $conversation['conversation_key'] ? 'active' : '' ?>" href="index.php?route=<?= e($inboxRoute ?? 'messages/inboxSms') ?>&<?= e(qs_without(['conversation', 'route'])) ?>&conversation=<?= urlencode($conversation['conversation_key']) ?>">
                    <div class="conversation-head"><strong><?= e($conversation['contact_name'] ?: $conversation['address']) ?></strong><span class="badge"><?= e(strtoupper($conversation['channel'])) ?></span></div>
                    <div class="small muted"><?= e($conversation['address']) ?></div>
                    <div class="conversation-preview"><?= e(mb_strimwidth($conversation['last_preview'], 0, 90, '...')) ?></div>
                    <div class="conversation-meta small muted"><?= e($conversation['last_message_at']) ?> · <?= (int)$conversation['message_count'] ?> msgs<?php if ($conversation['unread_like_count']): ?> · <?= (int)$conversation['unread_like_count'] ?> new<?php endif; ?></div>
                </a>
            <?php endforeach; ?>
            <?php if (empty($conversations)): ?>
                <div class="empty-state-cell muted">No conversations match this filter yet.</div>
            <?php endif; ?>
        </div>
        <?php if ($totalPages > 1): ?>
            <div class="page-slider">
                <a class="btn secondary small <?= $currentPage <= 1 ? 'is-disabled' : '' ?>" href="<?= $currentPage > 1 ? e($pageBase . max(1, $currentPage - 1)) : '#' ?>">Previous</a>
                <div class="page-slider-main">
                    <div class="page-slider-copy">
                        <strong>Jump to page <span data-slider-value><?= $currentPage ?></span></strong>
                        <span class="small muted">Slide through <?= $totalPages ?> pages without showing a long page-number list.</span>
                    </div>
                    <input type="range" class="js-page-slider" min="1" max="<?= $totalPages ?>" value="<?= $currentPage ?>" step="1" data-page-base="<?= e($pageBase) ?>" aria-label="Inbox page slider">
                </div>
                <a class="btn secondary small <?= $currentPage >= $totalPages ? 'is-disabled' : '' ?>" href="<?= $currentPage < $totalPages ? e($pageBase . min($totalPages, $currentPage + 1)) : '#' ?>">Next</a>
            </div>
        <?php endif; ?>
    </div>
    <div class="card">
        <div class="toolbar"><h2>Threaded View</h2><?php if (!empty($lastMessage)): ?><span class="badge"><?= e(strtoupper($lastMessage['channel'])) ?></span><?php endif; ?></div>
        <?php if (empty($thread)): ?>
            <p class="muted">Select a conversation to view its full history and reply inline.</p>
        <?php else: ?>
            <div class="thread">
                <?php foreach ($thread as $message): ?>
                    <article class="bubble <?= e($message['direction']) ?>">
                        <div class="bubble-meta small muted"><?= e(strtoupper($message['channel'])) ?> · <?= e($message['created_at']) ?> · <?= e($message['status']) ?></div>
                        <?php if (!empty($message['contact_id'])): ?><div class="small"><a href="index.php?route=contacts/show&id=<?= (int)$message['contact_id'] ?>">Open contact timeline</a></div><?php endif; ?>
                        <?php if (!empty($message['subject'])): ?><h3><?= e($message['subject']) ?></h3><?php endif; ?>
                        <div><?= nl2br(e(strip_tags((string)$message['body']))) ?></div>
                    </article>
                <?php endforeach; ?>
            </div>
            <hr>
            <form method="post" action="index.php?route=messages/reply">
                <?= csrf_input() ?>
                <input type="hidden" name="conversation_key" value="<?= e($selectedConversation ?? '') ?>">
                <input type="hidden" name="channel" value="<?= e($inboxChannel ?? 'sms') ?>">
                <?php if (($inboxChannel ?? 'sms') === 'email'): ?>
                    <input name="subject" value="<?= e((stripos((string)($lastMessage['subject'] ?? ''), 'Re:') === 0 ? $lastMessage['subject'] : 'Re: ' . ($lastMessage['subject'] ?? 'Conversation'))) ?>">
                <?php endif; ?>
                <textarea name="body" rows="6" placeholder="Reply in this thread"></textarea>
                <button class="btn primary">Send Reply</button>
            </form>
        <?php endif; ?>
    </div>
</section>

<section class="grid two">
    <div class="card">
        <div class="toolbar"><h2>Conversation Workflow</h2><span class="badge">Ownership + status</span></div>
        <?php if (!empty($selectedConversation)): ?>
            <form method="post" action="index.php?route=messages/saveConversationState">
                <?= csrf_input() ?>
                <input type="hidden" name="conversation_key" value="<?= e($selectedConversation) ?>">
                <input type="hidden" name="channel" value="<?= e($inboxChannel ?? 'sms') ?>">
                <div class="form-grid">
                    <select name="status">
                        <?php foreach (['open','pending','closed'] as $statusOpt): ?>
                            <option value="<?= $statusOpt ?>" <?= (($conversationState['status'] ?? 'open') === $statusOpt) ? 'selected' : '' ?>><?= ucfirst($statusOpt) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <select name="assigned_user_id">
                        <option value="">Unassigned</option>
                        <?php foreach (($users ?? []) as $user): ?>
                            <option value="<?= (int)$user['id'] ?>" <?= (int)($conversationState['assigned_user_id'] ?? 0) === (int)$user['id'] ? 'selected' : '' ?>><?= e($user['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <input name="internal_note" value="<?= e($conversationState['internal_note'] ?? '') ?>" placeholder="Internal note">
                </div>
                <button class="btn secondary">Save Workflow State</button>
            </form>
        <?php else: ?>
            <p class="muted">Select a conversation to manage assignment and status.</p>
        <?php endif; ?>
    </div>
    <div class="card">
        <div class="toolbar"><h2>Canned Replies</h2><span class="badge">Saved responses</span></div>
        <div class="small muted">Copy and paste these into replies for faster handling.</div>
        <?php foreach (($cannedReplies ?? []) as $reply): ?>
            <article class="bubble inbound" style="margin-top:12px;">
                <div class="bubble-meta small muted"><?= e($reply['title']) ?> · <?= e(strtoupper($reply['channel'])) ?></div>
                <?php if (!empty($reply['subject'])): ?><strong><?= e($reply['subject']) ?></strong><?php endif; ?>
                <div><?= nl2br(e($reply['body'])) ?></div>
            </article>
        <?php endforeach; ?>
        <?php if (empty($cannedReplies)): ?>
            <p class="muted" style="margin-top:12px;">No canned replies are saved for this channel yet.</p>
        <?php endif; ?>
    </div>
</section>
