<?php
$totalContacts = (int)($contactCounts['total'] ?? count($contacts ?? []));
$emailReachable = (int)($contactCounts['email_reachable'] ?? 0);
$smsReachable = (int)($contactCounts['sms_reachable'] ?? 0);
$listCount = count($contactLists ?? []);
$currentPage = max(1, (int)($meta['page'] ?? 1));
$totalPages = max(1, (int)($meta['pages'] ?? 1));
$queryTail = qs_without(['page', 'route']);
$pageBase = 'index.php?route=contacts/index';
if ($queryTail !== '') {
    $pageBase .= '&' . $queryTail;
}
$pageBase .= '&page=';
$segmentName = 'All segments';
if (!empty($filters['segment_id'])) {
    foreach ($segments as $segment) {
        if ((int)$segment['id'] === (int)$filters['segment_id']) {
            $segmentName = $segment['name'];
            break;
        }
    }
}
?>

<section class="cards four compact-stats">
    <div class="card stat alt">
        <h3>Total Contacts</h3>
        <p><?= number_format($totalContacts) ?></p>
        <span>Directory size across all channels.</span>
    </div>
    <div class="card stat alt">
        <h3>Email Reachable</h3>
        <p><?= number_format($emailReachable) ?></p>
        <span>Active contacts with deliverable email targets.</span>
    </div>
    <div class="card stat alt">
        <h3>SMS Reachable</h3>
        <p><?= number_format($smsReachable) ?></p>
        <span>Active contacts with usable phone numbers.</span>
    </div>
    <div class="card stat alt">
        <h3>Saved Lists</h3>
        <p><?= number_format($listCount) ?></p>
        <span>Reusable audiences for imports and campaigns.</span>
    </div>
</section>

<section class="card spaced-card">
    <div class="section-header split-header">
        <div class="section-copy">
            <h2>Contacts</h2>
            <p>Browse clients, filter by channel or segment, and jump between pages without a crowded page-number strip.</p>
        </div>
        <form method="get" class="inline-form filters-row align-end">
            <input type="hidden" name="route" value="contacts/index">
            <input name="q" placeholder="Search contacts" value="<?= e($filters['q'] ?? '') ?>">
            <select name="channel">
                <option value="all">All channels</option>
                <option value="sms" <?= ($filters['channel'] ?? '') === 'sms' ? 'selected' : '' ?>>SMS</option>
                <option value="email" <?= ($filters['channel'] ?? '') === 'email' ? 'selected' : '' ?>>Email</option>
            </select>
            <select name="segment_id">
                <option value="">All segments</option>
                <?php foreach ($segments as $segment): ?>
                    <option value="<?= (int)$segment['id'] ?>" <?= (int)($filters['segment_id'] ?? 0) === (int)$segment['id'] ? 'selected' : '' ?>><?= e($segment['name']) ?></option>
                <?php endforeach; ?>
            </select>
            <select name="per_page">
                <?php foreach (($perPageOptions ?? [15, 25, 50]) as $option): ?>
                    <option value="<?= (int)$option ?>" <?= (int)($filters['per_page'] ?? ($perPage ?? 15)) === (int)$option ? 'selected' : '' ?>>View <?= (int)$option ?></option>
                <?php endforeach; ?>
            </select>
            <button class="btn secondary small">Apply Filters</button>
            <?php if (can_access('messages.export')): ?><a class="btn secondary small" href="index.php?route=contacts/exportCsv&<?= e(qs_without(['route'])) ?>">Export CSV</a><?php endif; ?>
        </form>
    </div>

    <div class="toolbar-meta muted small">
        <span><strong><?= number_format((int)($meta['total'] ?? 0)) ?></strong> matching contacts</span>
        <span>Channel: <strong><?= e(strtoupper($filters['channel'] ?? 'all')) ?></strong></span>
        <span>Segment: <strong><?= e($segmentName) ?></strong></span>
        <span>View <strong><?= (int)($filters['per_page'] ?? ($perPage ?? 15)) ?></strong> per page</span>
        <span>Page <strong><?= $currentPage ?></strong> of <strong><?= $totalPages ?></strong></span>
    </div>

    <div class="table-shell">
        <table class="data-table contact-table" data-list-ignore="true">
            <thead><tr><th>Name</th><th>Phone</th><th>Email</th><th>Company/Account</th><th>Pipeline</th><th>Stage</th><th>Score</th><th>Status</th><th></th></tr></thead>
            <tbody>
            <?php if ($contacts): ?>
                <?php foreach ($contacts as $contact): ?>
                    <tr>
                        <td>
                            <strong><?= e(trim($contact['first_name'] . ' ' . $contact['last_name'])) ?></strong>
                            <div class="small muted">Created <?= e(substr((string)($contact['created_at'] ?? ''), 0, 10)) ?></div>
                        </td>
                        <td><?= e($contact['phone'] ?: '—') ?></td>
                        <td><?= e($contact['email'] ?: '—') ?></td>
                        <td><?= e($contact['account_name'] ?: $contact['company'] ?: '—') ?></td>
                        <td><?= e($contact['pipeline_name'] ?? '—') ?></td>
                        <td><?= e(ucfirst($contact['lifecycle_stage'] ?? 'lead')) ?></td>
                        <td><?= (int)($contact['score'] ?? 0) ?></td>
                        <td>
                            <div class="stacked-badges">
                                <?php if (!(int)$contact['unsubscribed_sms']): ?><span class="badge">SMS OK</span><?php endif; ?>
                                <?php if (!(int)$contact['unsubscribed_email']): ?><span class="badge">Email OK</span><?php endif; ?>
                                <?php if ((int)$contact['unsubscribed_sms'] && (int)$contact['unsubscribed_email']): ?><span class="badge">Suppressed</span><?php endif; ?>
                            </div>
                        </td>
                        <td>
                            <div class="actions-cell">
                                <a class="btn secondary small" href="index.php?route=contacts/show&id=<?= (int)$contact['id'] ?>">View</a>
                                <?php if (can_access('contacts.delete')): ?>
                                    <a class="btn danger small" href="index.php?route=contacts/delete&id=<?= (int)$contact['id'] ?>" onclick="return confirm('Delete contact?')">Delete</a>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
            <?php else: ?>
                <tr>
                    <td colspan="9" class="empty-state-cell">
                        <strong>No contacts matched this view.</strong>
                        <div class="small muted">Adjust filters, import a CSV, or add a contact manually.</div>
                    </td>
                </tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>

    <?php if ($totalPages > 1): ?>
        <div class="page-slider">
            <a class="btn secondary small" href="<?= 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 across <?= $totalPages ?> pages without loading a long page 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="Contacts page slider"
                >
            </div>
            <a class="btn secondary small" href="<?= e($pageBase . min($totalPages, $currentPage + 1)) ?>">Next</a>
        </div>
    <?php endif; ?>
</section>

<?php if (can_access('contacts.manage')): ?>
<section class="grid two roomy-grid">
    <div class="card spaced-card">
        <div class="section-copy section-gap-sm">
            <h2>Add Contact</h2>
            <p>Create a client once and optionally attach them to an existing saved list in the same step.</p>
        </div>
        <form method="post" action="index.php?route=contacts/save">
            <?= csrf_input() ?>
            <div class="form-grid form-grid-three-balanced">
                <input name="first_name" placeholder="First Name" required>
                <input name="last_name" placeholder="Last Name">
                <input name="phone" placeholder="Phone Number">
                <input name="email" type="email" placeholder="Email Address">
                <input name="company" placeholder="Company">
                <input name="tags" placeholder="Tags, comma separated">
                <input name="timezone" placeholder="Timezone e.g. America/Chicago" value="<?= e(config('app.timezone','America/Chicago')) ?>">
                <select name="lifecycle_stage"><option value="lead">Lead</option><option value="qualified">Qualified</option><option value="proposal">Proposal</option><option value="customer">Customer</option></select>
                <input name="score" type="number" value="0" placeholder="Score">
                <select name="add_to_list_id">
                    <option value="">Add to List (optional)</option>
                    <?php foreach (($contactLists ?? []) as $list): ?>
                        <option value="<?= (int)$list['id'] ?>"><?= e($list['name']) ?> (<?= e(strtoupper($list['channel'])) ?>)</option>
                    <?php endforeach; ?>
                </select>
            </div>
            <p class="small muted form-help">Duplicate protection is on. If the email or phone already exists, the app refreshes the existing client and avoids creating a second record.</p>
            <button class="btn primary">Save Contact</button>
        </form>
    </div>
    <div class="card spaced-card">
        <div class="section-copy section-gap-sm">
            <h2>Import CSV</h2>
            <p>Bring in new clients from a spreadsheet without generating duplicate records for matching email addresses or phone numbers.</p>
        </div>
        <form method="post" action="index.php?route=contacts/import" enctype="multipart/form-data">
            <?= csrf_input() ?>
            <p class="muted">Expected columns: first_name, last_name, phone, email, company, tags, timezone, lifecycle_stage, score</p>
            <input type="file" name="csv_file" accept=".csv" required>
            <button class="btn secondary">Import Contacts</button>
        </form>
    </div>
</section>
<?php endif; ?>

<?php if (can_access('segments.manage')): ?>
<section class="grid two roomy-grid">
    <div class="card spaced-card">
        <div class="section-copy section-gap-sm">
            <h2>Saved Segments</h2>
            <p>Reusable audience rules for campaigns and filtered contact views.</p>
        </div>
        <div class="table-shell compact-table-shell">
            <table class="data-table">
                <thead><tr><th>Name</th><th>Channel</th><th>Filters</th><th>Members</th><th></th></tr></thead>
                <tbody>
                <?php foreach ($segments as $segment): $rules = json_decode((string)($segment['rule_json'] ?? '{}'), true) ?: []; ?>
                    <tr>
                        <td><?= e($segment['name']) ?></td>
                        <td><?= e(strtoupper($segment['channel'])) ?></td>
                        <td><?= e(trim(($segment['tag_filter'] ? 'tag:' . $segment['tag_filter'] . ' ' : '') . ($segment['company_filter'] ? 'company:' . $segment['company_filter'] . ' ' : '') . (!empty($rules['lifecycle_stage']) ? 'stage:' . $rules['lifecycle_stage'] . ' ' : '') . (!empty($rules['minimum_score']) ? 'score>=' . $rules['minimum_score'] : ''))) ?></td>
                        <td><?= (int)($segment['member_count'] ?? 0) ?></td>
                        <td><a class="btn danger small" href="index.php?route=contacts/deleteSegment&id=<?= (int)$segment['id'] ?>" onclick="return confirm('Delete segment?')">Delete</a></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    <div class="card spaced-card">
        <div class="section-copy section-gap-sm">
            <h2>Create Dynamic Segment</h2>
            <p>Build segments with score, lifecycle, company, and tag rules.</p>
        </div>
        <form method="post" action="index.php?route=contacts/saveSegment">
            <?= csrf_input() ?>
            <div class="form-grid form-grid-three-balanced">
                <input name="name" placeholder="Segment name" required>
                <select name="channel"><option value="all">All channels</option><option value="sms">SMS</option><option value="email">Email</option></select>
                <input name="tag_filter" placeholder="Tag contains">
                <input name="company_filter" placeholder="Company contains">
                <select name="lifecycle_stage"><option value="">Any stage</option><option value="lead">Lead</option><option value="qualified">Qualified</option><option value="proposal">Proposal</option><option value="customer">Customer</option></select>
                <input name="minimum_score" type="number" min="0" value="0" placeholder="Minimum score">
            </div>
            <button class="btn primary">Save Segment</button>
        </form>
    </div>
</section>
<?php endif; ?>

<?php if (can_access('contacts.manage')): ?>
<section class="grid two roomy-grid">
    <div class="card spaced-card">
        <div class="section-copy section-gap-sm">
            <h2>Saved Contact Lists</h2>
            <p>Audience pools you can import into, reuse, and target from campaigns.</p>
        </div>
        <div class="table-shell compact-table-shell">
            <table class="data-table">
                <thead><tr><th>Name</th><th>Channel</th><th>Members</th><th>Description</th><th></th></tr></thead>
                <tbody>
                <?php foreach (($contactLists ?? []) as $list): ?>
                    <tr>
                        <td><?= e($list['name']) ?></td>
                        <td><?= e(strtoupper($list['channel'])) ?></td>
                        <td><?= (int)($list['member_count'] ?? 0) ?></td>
                        <td><?= e($list['description'] ?? '') ?></td>
                        <td><a class="btn danger small" href="index.php?route=contacts/deleteContactList&id=<?= (int)$list['id'] ?>" onclick="return confirm('Delete contact list?')">Delete</a></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    <div class="card spaced-card">
        <div class="section-copy section-gap-sm">
            <h2>Create / Import Contact List</h2>
            <p>Save an empty list first, then feed it from CSV with duplicate-safe contact reuse.</p>
        </div>
        <form method="post" action="index.php?route=contacts/saveContactList">
            <?= csrf_input() ?>
            <div class="form-grid">
                <input name="name" placeholder="List name" required>
                <select name="channel"><option value="both">Both</option><option value="email">Email</option><option value="sms">SMS</option></select>
                <input name="description" placeholder="Optional description">
            </div>
            <button class="btn primary">Save Empty List</button>
        </form>
        <hr>
        <form method="post" action="index.php?route=contacts/importContactList" enctype="multipart/form-data">
            <?= csrf_input() ?>
            <p class="muted">Import a CSV into a saved list for later campaign use.</p>
            <select name="list_id" required>
                <option value="">Choose saved list</option>
                <?php foreach (($contactLists ?? []) as $list): ?>
                    <option value="<?= (int)$list['id'] ?>"><?= e($list['name']) ?> (<?= e(strtoupper($list['channel'])) ?>)</option>
                <?php endforeach; ?>
            </select>
            <input type="file" name="csv_file" accept=".csv" required>
            <button class="btn secondary">Import Into List</button>
        </form>
    </div>
</section>
<?php endif; ?>
