<section class="card">
    <div class="toolbar">
        <h2>Contacts</h2>
        <form method="get" class="inline-form toolbar-right">
            <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>
            <button class="btn secondary small">Filter</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>
    <table>
        <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 foreach ($contacts as $contact): ?>
            <tr>
                <td><?= e(trim($contact['first_name'] . ' ' . $contact['last_name'])) ?></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; ?>
                    </div>
                </td>
                <td>
                    <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; ?>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    <?php if (($meta['pages'] ?? 1) > 1): ?>
        <div class="pagination">
            <?php for ($i = 1; $i <= $meta['pages']; $i++): ?>
                <a class="page-link <?= $i === (int)$meta['page'] ? 'active' : '' ?>" href="index.php?route=contacts/index&<?= e(qs_without(['page', 'route'])) ?>&page=<?= $i ?>"><?= $i ?></a>
            <?php endfor; ?>
        </div>
    <?php endif; ?>
</section>

<?php if (can_access('contacts.manage')): ?>
<section class="grid two">
    <div class="card">
        <h2>Add Contact</h2>
        <form method="post" action="index.php?route=contacts/save">
            <?= csrf_input() ?>
            <div class="form-grid">
                <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">Choose <strong>Add to List</strong> to place this new client directly into an existing imported list without a separate CSV upload.</p>
            <button class="btn primary">Save Contact</button>
        </form>
    </div>
    <div class="card">
        <h2>Import CSV</h2>
        <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">
    <div class="card">
        <h2>Saved Segments</h2>
        <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 class="card">
        <h2>Create Dynamic Segment</h2>
        <form method="post" action="index.php?route=contacts/saveSegment">
            <?= csrf_input() ?>
            <div class="form-grid">
                <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">
    <div class="card">
        <h2>Saved Contact Lists</h2>
        <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 class="card">
        <h2>Create / Import Contact List</h2>
        <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; ?>
