<?php
$fullName = trim((string)($contact['first_name'] ?? '') . ' ' . (string)($contact['last_name'] ?? '')) ?: 'Contact';
$activeTab = ($commTab ?? 'email') === 'sms' ? 'sms' : 'email';
$hasPhone = trim((string)($contact['phone'] ?? '')) !== '';
$hasEmail = trim((string)($contact['email'] ?? '')) !== '';
$smsReturnUrl = 'index.php?route=contacts/show&id=' . (int)$contact['id'] . '&comm_tab=sms';
if (!empty($selectedSmsThread['conversation_key'])) {
    $smsReturnUrl .= '&sms_conversation=' . urlencode((string)$selectedSmsThread['conversation_key']);
}
$emailReturnUrl = 'index.php?route=contacts/show&id=' . (int)$contact['id'] . '&comm_tab=email';
if (!empty($selectedEmailThread['conversation_key'])) {
    $emailReturnUrl .= '&email_conversation=' . urlencode((string)$selectedEmailThread['conversation_key']);
}
$commTabUrl = function (string $tab, ?string $conversationKey = null) use ($contact): string {
    $url = 'index.php?route=contacts/show&id=' . (int)$contact['id'] . '&comm_tab=' . urlencode($tab);
    if ($conversationKey) {
        $param = $tab === 'sms' ? 'sms_conversation' : 'email_conversation';
        $url .= '&' . $param . '=' . urlencode($conversationKey);
    }
    return $url;
};
$channelState = function (string $channel) use ($contact, $suppressed): array {
    $unsubscribedField = $channel === 'sms' ? 'unsubscribed_sms' : 'unsubscribed_email';
    if (!empty($suppressed[$channel])) {
        return ['label' => 'Suppressed', 'class' => 'danger'];
    }
    if (!empty($contact[$unsubscribedField])) {
        return ['label' => 'Unsubscribed', 'class' => 'warn'];
    }
    return ['label' => 'Active', 'class' => 'ok'];
};
$smsState = $channelState('sms');
$emailState = $channelState('email');
$renderThreadMessages = function (array $messages, string $channel): string {
    ob_start();
    foreach ($messages as $message):
        $isOutbound = ($message['direction'] ?? '') === 'outbound';
        $body = (string)($message['body'] ?? '');
        $safeBody = nl2br(e(strip_tags($body)));
        ?>
        <article class="bubble <?= $isOutbound ? 'outbound' : 'inbound' ?> crm-thread-bubble">
            <div class="conversation-head">
                <strong><?= $isOutbound ? 'You' : e(trim((string)($message['first_name'] ?? '') . ' ' . (string)($message['last_name'] ?? '')) ?: (($message['from_address'] ?? '') ?: 'Contact')) ?></strong>
                <span class="small muted"><?= e((string)($message['created_at'] ?? '')) ?> · <?= e(strtoupper((string)($message['status'] ?? ''))) ?></span>
            </div>
            <?php if ($channel === 'email' && !empty($message['subject'])): ?>
                <div class="preview-subject"><?= e((string)$message['subject']) ?></div>
            <?php endif; ?>
            <div class="crm-thread-body"><?= $safeBody ?></div>
            <?php if (!empty($message['attachment_path'])): ?>
                <div class="small muted">Attachment: <?= e((string)$message['attachment_path']) ?></div>
            <?php endif; ?>
            <?php if (!empty($message['media_url'])): ?>
                <div class="small muted">Media: <a href="<?= e((string)$message['media_url']) ?>" target="_blank" rel="noopener">Open media</a></div>
            <?php endif; ?>
        </article>
        <?php
    endforeach;
    return (string)ob_get_clean();
};
?>

<section class="workspace-hero crm-contact-hero">
    <div>
        <h2><?= e($fullName) ?></h2>
        <p><?= e((string)($contact['company'] ?: 'No company on file')) ?> · Contact CRM, communication threads, consent controls, and recent campaign activity in one view.</p>
        <div class="stacked-badges mt-12">
            <span class="badge"><?= e(ucfirst((string)($contact['lifecycle_stage'] ?? 'lead'))) ?></span>
            <span class="badge badge-<?= e($smsState['class']) ?>">SMS: <?= e($smsState['label']) ?></span>
            <span class="badge badge-<?= e($emailState['class']) ?>">Email: <?= e($emailState['label']) ?></span>
            <?php if (!empty($contact['owner_name'])): ?><span class="badge">Owner: <?= e((string)$contact['owner_name']) ?></span><?php endif; ?>
        </div>
    </div>
    <div class="workspace-actions">
        <a class="btn secondary" href="index.php?route=contacts/index">Back to Contacts</a>
        <?php if ($hasEmail): ?><a class="btn secondary" href="index.php?route=messages/mailCenter">Open Mail Center</a><?php endif; ?>
        <a class="btn secondary" href="index.php?route=messages/campaignReports">Campaign Reports</a>
    </div>
</section>

<section class="grid two crm-top-grid">
    <div class="card">
        <div class="toolbar"><h2>Contact Details</h2><span class="badge">CRM</span></div>
        <table class="compact">
            <tbody>
                <tr><th>Name</th><td><?= e($fullName) ?></td></tr>
                <tr><th>Phone</th><td><?= $hasPhone ? e((string)$contact['phone']) : '—' ?></td></tr>
                <tr><th>Email</th><td><?= $hasEmail ? e((string)$contact['email']) : '—' ?></td></tr>
                <tr><th>Company</th><td><?= e((string)($contact['company'] ?: '—')) ?></td></tr>
                <tr><th>Account</th><td><?= e((string)($contact['account_name'] ?? '—')) ?></td></tr>
                <tr><th>Pipeline</th><td><?= e((string)($contact['pipeline_name'] ?? '—')) ?></td></tr>
                <tr><th>Owner</th><td><?= e((string)($contact['owner_name'] ?? '—')) ?></td></tr>
                <tr><th>Timezone</th><td><?= e((string)($contact['timezone'] ?: '—')) ?></td></tr>
                <tr><th>Tags</th><td><?= e((string)($contact['tags'] ?: '—')) ?></td></tr>
                <tr><th>Score</th><td><?= (int)($contact['score'] ?? 0) ?></td></tr>
            </tbody>
        </table>
        <div class="metric-strip mt-12">
            <div class="metric-chip"><strong><?= (int)($summary['total_messages'] ?? 0) ?></strong><span class="small muted">messages</span></div>
            <div class="metric-chip"><strong><?= (int)($summary['open_total'] ?? 0) ?></strong><span class="small muted">opens</span></div>
            <div class="metric-chip"><strong><?= (int)($summary['click_total'] ?? 0) ?></strong><span class="small muted">clicks</span></div>
        </div>
    </div>

    <div class="card">
        <div class="toolbar"><h2>Lifecycle Profile</h2><span class="badge">Editable</span></div>
        <form method="post" action="index.php?route=contacts/updateProfile" class="stacked-panel">
            <?= csrf_input() ?>
            <input type="hidden" name="contact_id" value="<?= (int)$contact['id'] ?>">
            <input type="hidden" name="comm_tab" value="<?= e($activeTab) ?>">
            <div class="form-grid">
                <label>
                    <span class="small muted">Lifecycle stage</span>
                    <select name="lifecycle_stage">
                        <?php foreach (['lead','qualified','proposal','customer'] as $stage): ?>
                            <option value="<?= e($stage) ?>" <?= (($contact['lifecycle_stage'] ?? 'lead') === $stage) ? 'selected' : '' ?>><?= e(ucfirst($stage)) ?></option>
                        <?php endforeach; ?>
                    </select>
                </label>
                <label>
                    <span class="small muted">Score</span>
                    <input type="number" name="score" value="<?= (int)($contact['score'] ?? 0) ?>">
                </label>
                <label>
                    <span class="small muted">Owner</span>
                    <select name="owner_user_id">
                        <option value="">No owner</option>
                        <?php foreach ($users as $user): ?>
                            <option value="<?= (int)$user['id'] ?>" <?= (int)($contact['owner_user_id'] ?? 0) === (int)$user['id'] ? 'selected' : '' ?>><?= e((string)$user['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </label>
                <label>
                    <span class="small muted">Account</span>
                    <select name="account_id">
                        <option value="">No account</option>
                        <?php foreach ($accounts as $account): ?>
                            <option value="<?= (int)$account['id'] ?>" <?= (int)($contact['account_id'] ?? 0) === (int)$account['id'] ? 'selected' : '' ?>><?= e((string)$account['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </label>
                <label>
                    <span class="small muted">Pipeline</span>
                    <select name="pipeline_id">
                        <option value="">No pipeline</option>
                        <?php foreach ($pipelines as $pipeline): ?>
                            <option value="<?= (int)$pipeline['id'] ?>" <?= (int)($contact['pipeline_id'] ?? 0) === (int)$pipeline['id'] ? 'selected' : '' ?>><?= e((string)$pipeline['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </label>
            </div>
            <button class="btn primary">Save Profile</button>
        </form>

        <hr>
        <div class="crm-channel-status-grid">
            <div class="crm-channel-status">
                <div>
                    <strong>SMS/MMS</strong>
                    <div class="small muted"><?= $hasPhone ? e((string)$contact['phone']) : 'No phone on file' ?></div>
                </div>
                <span class="badge badge-<?= e($smsState['class']) ?>"><?= e($smsState['label']) ?></span>
            </div>
            <div class="stacked-badges">
                <?php if ($hasPhone): ?>
                    <form method="post" action="index.php?route=contacts/<?= !empty($suppressed['sms']) || !empty($contact['unsubscribed_sms']) ? 'resubscribe' : 'unsubscribe' ?>">
                        <?= csrf_input() ?>
                        <input type="hidden" name="contact_id" value="<?= (int)$contact['id'] ?>">
                        <input type="hidden" name="channel" value="sms">
                        <input type="hidden" name="comm_tab" value="sms">
                        <input type="hidden" name="reason" value="Manual preference change from contact profile">
                        <button class="btn <?= !empty($suppressed['sms']) || !empty($contact['unsubscribed_sms']) ? 'primary' : 'secondary' ?> small"><?= !empty($suppressed['sms']) || !empty($contact['unsubscribed_sms']) ? 'Resubscribe SMS' : 'Unsubscribe SMS' ?></button>
                    </form>
                <?php endif; ?>
            </div>
        </div>
        <div class="crm-channel-status-grid mt-12">
            <div class="crm-channel-status">
                <div>
                    <strong>Email</strong>
                    <div class="small muted"><?= $hasEmail ? e((string)$contact['email']) : 'No email on file' ?></div>
                </div>
                <span class="badge badge-<?= e($emailState['class']) ?>"><?= e($emailState['label']) ?></span>
            </div>
            <div class="stacked-badges">
                <?php if ($hasEmail): ?>
                    <form method="post" action="index.php?route=contacts/<?= !empty($suppressed['email']) || !empty($contact['unsubscribed_email']) ? 'resubscribe' : 'unsubscribe' ?>">
                        <?= csrf_input() ?>
                        <input type="hidden" name="contact_id" value="<?= (int)$contact['id'] ?>">
                        <input type="hidden" name="channel" value="email">
                        <input type="hidden" name="comm_tab" value="email">
                        <input type="hidden" name="reason" value="Manual preference change from contact profile">
                        <button class="btn <?= !empty($suppressed['email']) || !empty($contact['unsubscribed_email']) ? 'primary' : 'secondary' ?> small"><?= !empty($suppressed['email']) || !empty($contact['unsubscribed_email']) ? 'Resubscribe Email' : 'Unsubscribe Email' ?></button>
                    </form>
                <?php endif; ?>
            </div>
        </div>
    </div>
</section>

<section class="card crm-communication-card">
    <div class="toolbar"><h2>Communication Center</h2><span class="badge">Per-contact threads</span></div>
    <div class="tabs-inline crm-tab-row">
                <a class="btn <?= $activeTab === 'sms' ? 'primary' : 'secondary' ?> small" href="<?= e($commTabUrl('sms', $selectedSmsThread['conversation_key'] ?? null)) ?>">SMS/MMS</a>
        <a class="btn <?= $activeTab === 'email' ? 'primary' : 'secondary' ?> small" href="<?= e($commTabUrl('email', $selectedEmailThread['conversation_key'] ?? null)) ?>">Email</a>
    </div>

    <?php if ($activeTab === 'sms'): ?>
        <div class="grid two conversation-grid crm-contact-conversation-grid">
            <div>
                <div class="toolbar compact-toolbar"><h3>SMS/MMS Threads</h3><span class="badge"><?= count($smsConversations) ?> thread(s)</span></div>
                <div class="conversation-list crm-contact-thread-list">
                    <?php foreach ($smsConversations as $thread): ?>
                        <a class="conversation-item <?= !empty($selectedSmsThread['conversation_key']) && ($selectedSmsThread['conversation_key'] === $thread['conversation_key']) ? 'active' : '' ?>" href="<?= e($commTabUrl('sms', (string)$thread['conversation_key'])) ?>">
                            <div class="conversation-head"><strong><?= e((string)($thread['address'] ?: $fullName)) ?></strong><span class="small muted"><?= e((string)($thread['last_message_at'] ?? '')) ?></span></div>
                            <div class="conversation-preview"><?= e((string)($thread['last_preview'] ?? 'No message preview')) ?></div>
                            <div class="conversation-meta"><span class="small muted"><?= (int)($thread['message_count'] ?? 0) ?> messages</span><span class="small muted"><?= e(strtoupper((string)($thread['status'] ?? ''))) ?></span></div>
                        </a>
                    <?php endforeach; ?>
                    <?php if (!$smsConversations): ?>
                        <div class="crm-empty-state">No SMS/MMS thread exists for this contact yet.</div>
                    <?php endif; ?>
                </div>
            </div>
            <div>
                <div class="toolbar compact-toolbar"><h3><?= $selectedSmsThread ? 'SMS/MMS Thread' : 'Start SMS/MMS' ?></h3><span class="badge"><?= $hasPhone ? e((string)$contact['phone']) : 'No phone' ?></span></div>
                <div class="thread crm-thread-panel"><?= $renderThreadMessages($smsThreadMessages ?? [], 'sms') ?></div>
                <?php if ($hasPhone && can_access($selectedSmsThread ? 'messages.reply' : 'messages.send')): ?>
                    <div class="card mt-12">
                        <h3><?= $selectedSmsThread ? 'Reply in Thread' : 'Send SMS/MMS' ?></h3>
                        <form method="post" action="index.php?route=<?= $selectedSmsThread ? 'messages/reply' : 'messages/sendSms' ?>" class="stacked-panel">
                            <?= csrf_input() ?>
                            <?php if ($selectedSmsThread): ?>
                                <input type="hidden" name="channel" value="sms">
                                <input type="hidden" name="conversation_key" value="<?= e((string)$selectedSmsThread['conversation_key']) ?>">
                            <?php else: ?>
                                <input type="hidden" name="contact_id" value="<?= (int)$contact['id'] ?>">
                            <?php endif; ?>
                            <input type="hidden" name="return_url" value="<?= e($smsReturnUrl) ?>">
                            <textarea name="body" rows="5" placeholder="Type an SMS/MMS message" required></textarea>
                            <?php if (!$selectedSmsThread): ?><input type="url" name="media_url" placeholder="Optional media URL for MMS"><?php endif; ?>
                            <button class="btn primary"><?= $selectedSmsThread ? 'Send Reply' : 'Send SMS/MMS' ?></button>
                        </form>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    <?php else: ?>
        <div class="grid two conversation-grid crm-contact-conversation-grid">
            <div>
                <div class="toolbar compact-toolbar"><h3>Email Threads</h3><span class="badge"><?= count($emailConversations) ?> thread(s)</span></div>
                <div class="conversation-list crm-contact-thread-list">
                    <?php foreach ($emailConversations as $thread): ?>
                        <a class="conversation-item <?= !empty($selectedEmailThread['conversation_key']) && ($selectedEmailThread['conversation_key'] === $thread['conversation_key']) ? 'active' : '' ?>" href="<?= e($commTabUrl('email', (string)$thread['conversation_key'])) ?>">
                            <div class="conversation-head"><strong><?= e((string)($thread['subject'] ?: ($thread['address'] ?: $fullName))) ?></strong><span class="small muted"><?= e((string)($thread['last_message_at'] ?? '')) ?></span></div>
                            <div class="conversation-preview"><?= e((string)($thread['last_preview'] ?? 'No message preview')) ?></div>
                            <div class="conversation-meta"><span class="small muted"><?= (int)($thread['message_count'] ?? 0) ?> messages</span><span class="small muted"><?= e((string)($thread['address'] ?? '')) ?></span></div>
                        </a>
                    <?php endforeach; ?>
                    <?php if (!$emailConversations): ?>
                        <div class="crm-empty-state">No email thread exists for this contact yet.</div>
                    <?php endif; ?>
                </div>
            </div>
            <div>
                <div class="toolbar compact-toolbar"><h3><?= $selectedEmailThread ? 'Email Thread' : 'Compose Email' ?></h3><span class="badge"><?= $hasEmail ? e((string)$contact['email']) : 'No email' ?></span></div>
                <div class="thread crm-thread-panel"><?= $renderThreadMessages($emailThreadMessages ?? [], 'email') ?></div>
                <?php if ($hasEmail && can_access($selectedEmailThread ? 'messages.reply' : 'messages.send')): ?>
                    <div class="card mt-12">
                        <h3><?= $selectedEmailThread ? 'Reply in Thread' : 'Send Email' ?></h3>
                        <form method="post" enctype="multipart/form-data" action="index.php?route=<?= $selectedEmailThread ? 'messages/reply' : 'messages/sendEmail' ?>" class="stacked-panel">
                            <?= csrf_input() ?>
                            <?php if ($selectedEmailThread): ?>
                                <input type="hidden" name="channel" value="email">
                                <input type="hidden" name="conversation_key" value="<?= e((string)$selectedEmailThread['conversation_key']) ?>">
                            <?php else: ?>
                                <input type="hidden" name="contact_id" value="<?= (int)$contact['id'] ?>">
                            <?php endif; ?>
                            <input type="hidden" name="return_url" value="<?= e($emailReturnUrl) ?>">
                            <input name="subject" value="<?= e((string)($selectedEmailThread['subject'] ?? '')) ?>" placeholder="Subject" required>
                            <textarea name="body" rows="7" placeholder="Write an email" required></textarea>
                            <?php if (!$selectedEmailThread): ?><input type="file" name="attachment"><?php endif; ?>
                            <button class="btn primary"><?= $selectedEmailThread ? 'Send Reply' : 'Send Email' ?></button>
                        </form>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    <?php endif; ?>
</section>

<section class="grid two">
    <div class="card">
        <div class="toolbar"><h2>Recent Campaigns</h2><span class="badge">Linked to contact</span></div>
        <table>
            <thead><tr><th>Campaign</th><th>Channel</th><th>Status</th><th>Scheduled</th></tr></thead>
            <tbody>
            <?php foreach ($recentCampaigns as $campaign): ?>
                <tr>
                    <td><a href="index.php?route=messages/report&id=<?= (int)$campaign['id'] ?>"><?= e((string)$campaign['name']) ?></a></td>
                    <td><?= e(strtoupper((string)$campaign['channel'])) ?></td>
                    <td><?= e((string)$campaign['status']) ?></td>
                    <td><?= e((string)($campaign['scheduled_at'] ?? 'Immediate')) ?></td>
                </tr>
            <?php endforeach; ?>
            <?php if (!$recentCampaigns): ?><tr><td colspan="4" class="muted">No campaigns linked to this contact yet.</td></tr><?php endif; ?>
            </tbody>
        </table>
    </div>
    <div class="card">
        <div class="toolbar"><h2>Consent + Suppression</h2><span class="badge">Editable</span></div>
        <div class="grid two" style="margin-bottom:16px;">
            <form method="post" action="index.php?route=contacts/addConsent" class="stacked-panel">
                <?= csrf_input() ?>
                <input type="hidden" name="contact_id" value="<?= (int)$contact['id'] ?>">
                <input type="hidden" name="comm_tab" value="<?= e($activeTab) ?>">
                <select name="channel"><option value="email">Email</option><option value="sms">SMS</option></select>
                <select name="status"><option value="opt_in">Opt in</option><option value="opt_out">Opt out</option></select>
                <input name="source" value="manual" placeholder="Source">
                <textarea name="proof_note" rows="3" placeholder="Optional note or proof"></textarea>
                <button class="btn secondary">Add Consent Record</button>
            </form>
            <div>
                <h3>Suppression Entries</h3>
                <div class="crm-mini-list">
                    <?php foreach ($suppressionEntries as $entry): ?>
                        <article>
                            <strong><?= e(strtoupper((string)$entry['channel'])) ?></strong>
                            <div class="small muted"><?= e((string)$entry['address']) ?> · <?= e((string)($entry['reason'] ?? 'manual')) ?></div>
                            <div class="small muted"><?= e((string)$entry['updated_at']) ?></div>
                        </article>
                    <?php endforeach; ?>
                    <?php if (!$suppressionEntries): ?><div class="muted small">No active suppression rows attached to this contact.</div><?php endif; ?>
                </div>
            </div>
        </div>
        <div class="crm-mini-list">
            <?php foreach (array_slice($consentLogs, 0, 8) as $log): ?>
                <article>
                    <strong><?= e(strtoupper((string)$log['channel'])) ?> · <?= e((string)$log['status']) ?></strong>
                    <div class="small muted"><?= e((string)($log['source'] ?? 'manual')) ?> · <?= e((string)$log['created_at']) ?></div>
                    <?php if (!empty($log['proof_note'])): ?><div class="small muted"><?= e((string)$log['proof_note']) ?></div><?php endif; ?>
                </article>
            <?php endforeach; ?>
            <?php if (!$consentLogs): ?><div class="muted small">No consent history yet.</div><?php endif; ?>
        </div>
    </div>
</section>

<section class="grid two">
    <div class="card">
        <div class="toolbar"><h2>Tasks + Reminders</h2><span class="badge">Follow-up</span></div>
        <div class="grid two" style="margin-bottom:16px;">
            <form method="post" action="index.php?route=contacts/addTask" class="stacked-panel">
                <?= csrf_input() ?>
                <input type="hidden" name="contact_id" value="<?= (int)$contact['id'] ?>">
                <input type="hidden" name="comm_tab" value="<?= e($activeTab) ?>">
                <input name="title" placeholder="Task title" required>
                <input type="datetime-local" name="due_at">
                <select name="assigned_user_id">
                    <option value="">Assign later</option>
                    <?php foreach ($users as $user): ?><option value="<?= (int)$user['id'] ?>"><?= e((string)$user['name']) ?></option><?php endforeach; ?>
                </select>
                <button class="btn secondary">Add Task</button>
            </form>
            <form method="post" action="index.php?route=contacts/addReminder" class="stacked-panel">
                <?= csrf_input() ?>
                <input type="hidden" name="contact_id" value="<?= (int)$contact['id'] ?>">
                <input type="hidden" name="comm_tab" value="<?= e($activeTab) ?>">
                <input name="title" placeholder="Reminder title" required>
                <input type="datetime-local" name="remind_at">
                <select name="assigned_user_id">
                    <option value="">Assign later</option>
                    <?php foreach ($users as $user): ?><option value="<?= (int)$user['id'] ?>"><?= e((string)$user['name']) ?></option><?php endforeach; ?>
                </select>
                <button class="btn secondary">Add Reminder</button>
            </form>
        </div>
        <table class="compact">
            <thead><tr><th>Type</th><th>Title</th><th>Status</th><th>When</th><th></th></tr></thead>
            <tbody>
                <?php foreach ($tasks as $task): ?>
                    <tr>
                        <td>Task</td>
                        <td><?= e((string)$task['title']) ?></td>
                        <td><?= e((string)$task['status']) ?></td>
                        <td><?= e((string)($task['due_at'] ?? '—')) ?></td>
                        <td><?php if (($task['status'] ?? 'open') !== 'done'): ?><a class="btn secondary small" href="index.php?route=contacts/completeTask&contact_id=<?= (int)$contact['id'] ?>&task_id=<?= (int)$task['id'] ?>&comm_tab=<?= e($activeTab) ?>">Complete</a><?php endif; ?></td>
                    </tr>
                <?php endforeach; ?>
                <?php foreach ($reminders as $reminder): ?>
                    <tr>
                        <td>Reminder</td>
                        <td><?= e((string)$reminder['title']) ?></td>
                        <td><?= e((string)$reminder['status']) ?></td>
                        <td><?= e((string)($reminder['remind_at'] ?? '—')) ?></td>
                        <td><?php if (($reminder['status'] ?? 'open') !== 'done'): ?><a class="btn secondary small" href="index.php?route=contacts/completeReminder&contact_id=<?= (int)$contact['id'] ?>&reminder_id=<?= (int)$reminder['id'] ?>&comm_tab=<?= e($activeTab) ?>">Complete</a><?php endif; ?></td>
                    </tr>
                <?php endforeach; ?>
                <?php if (!$tasks && !$reminders): ?><tr><td colspan="5" class="muted">No open tasks or reminders.</td></tr><?php endif; ?>
            </tbody>
        </table>
    </div>
    <div class="card">
        <div class="toolbar"><h2>Notes + Custom Fields</h2><span class="badge">CRM detail</span></div>
        <form method="post" action="index.php?route=contacts/addNote" class="stacked-panel" style="margin-bottom:16px;">
            <?= csrf_input() ?>
            <input type="hidden" name="contact_id" value="<?= (int)$contact['id'] ?>">
            <input type="hidden" name="comm_tab" value="<?= e($activeTab) ?>">
            <textarea name="note_body" rows="4" placeholder="Internal note" required></textarea>
            <select name="visibility"><option value="internal">Internal</option><option value="shared">Shared</option></select>
            <button class="btn secondary">Add Note</button>
        </form>
        <div class="crm-mini-list" style="margin-bottom:16px;">
            <?php foreach (array_slice($notes, 0, 6) as $note): ?>
                <article>
                    <strong><?= e((string)($note['created_by_name'] ?? 'User')) ?></strong>
                    <div class="small muted"><?= e((string)$note['created_at']) ?> · <?= e((string)$note['visibility']) ?></div>
                    <div><?= nl2br(e((string)$note['note_body'])) ?></div>
                </article>
            <?php endforeach; ?>
            <?php if (!$notes): ?><div class="muted small">No notes yet.</div><?php endif; ?>
        </div>
        <form method="post" action="index.php?route=contacts/saveCustomValues" class="stacked-panel">
            <?= csrf_input() ?>
            <input type="hidden" name="contact_id" value="<?= (int)$contact['id'] ?>">
            <input type="hidden" name="comm_tab" value="<?= e($activeTab) ?>">
            <?php foreach ($customFields as $field): ?>
                <label>
                    <span class="small muted"><?= e((string)$field['name']) ?></span>
                    <input name="custom[<?= e((string)$field['field_key']) ?>]" value="<?= e((string)($customValues[$field['field_key']] ?? '')) ?>" placeholder="<?= e((string)$field['name']) ?>">
                </label>
            <?php endforeach; ?>
            <?php if (!$customFields): ?><div class="muted small">No custom fields configured yet.</div><?php endif; ?>
            <?php if ($customFields): ?><button class="btn secondary">Save Custom Fields</button><?php endif; ?>
        </form>
    </div>
</section>

<section class="card">
    <div class="toolbar"><h2>Activity Timeline</h2><span class="badge">Messages + Events</span></div>
    <div class="timeline-list">
        <?php foreach ($timeline as $item): ?>
            <article class="timeline-item">
                <div class="conversation-head"><strong><?= e(strtoupper((string)$item['item_type'])) ?> · <?= e(strtoupper((string)($item['channel'] ?? ''))) ?></strong><span class="small muted"><?= e((string)($item['created_at'] ?? '')) ?></span></div>
                <div class="small muted"><?= e((string)($item['status'] ?? '')) ?><?= !empty($item['event_type']) ? ' · ' . e((string)$item['event_type']) : '' ?></div>
                <?php if (!empty($item['subject'])): ?><div class="preview-subject"><?= e((string)$item['subject']) ?></div><?php endif; ?>
                <?php if (!empty($item['event_value'])): ?><div class="small muted"><?= e((string)$item['event_value']) ?></div><?php endif; ?>
                <?php if (!empty($item['body'])): ?><div><?= nl2br(e(substr(strip_tags((string)$item['body']), 0, 240))) ?></div><?php endif; ?>
            </article>
        <?php endforeach; ?>
        <?php if (!$timeline): ?><div class="muted">No activity yet.</div><?php endif; ?>
    </div>
</section>
