<?php
// ============================================================
//  admin/email.php — Email portal
// ============================================================
//
//  Layout:
//   - Account tabs at the top (one per mailbox the user has
//     access to). The active tab determines which inbox we show.
//   - "Sync now" button to trigger manual sync of the current
//     account (useful when testing, slow on first run).
//   - Inbox list — sender / subject / snippet / date.
//   - Click a row → admin/email-message.php?id=…
//
//  Permission: any admin user; their assigned accounts are
//  determined by email_account_users.
// ============================================================

require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/csrf.php';
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/email_sync.php';
auth_require_admin();

$me = auth_admin_user();

// ── POST: Sync now ──────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();
    $action = $_POST['action'] ?? '';

    if ($action === 'sync_now') {
        $account_id = (int)($_POST['account_id'] ?? 0);
        // Make sure the user has access
        $can_access = (bool)db_row(
            'SELECT 1 FROM email_account_users WHERE account_id=:a AND user_id=:u',
            ['a' => $account_id, 'u' => $me['id']]
        );
        if ($can_access) {
            @set_time_limit(0);
            $acct = db_row('SELECT * FROM email_accounts WHERE id=:id', ['id' => $account_id]);
            if ($acct) {
                $r = email_sync_account($acct);
                $msg = $r['ok']
                    ? "Sync complete: {$r['message']}"
                    : "Sync failed: {$r['message']}";
            } else {
                $msg = 'Account not found.';
            }
        } else {
            $msg = 'You don\'t have access to that account.';
        }
        header('Location: email.php?account=' . $account_id . '&msg=' . urlencode($msg));
        exit;
    }

    if ($action === 'mark_seen') {
        $message_id = (int)($_POST['message_id'] ?? 0);
        // Make sure the message belongs to an account the user can access
        $msg = db_row(
            "SELECT m.* FROM email_messages m
              JOIN email_account_users u ON u.account_id = m.account_id
              WHERE m.id=:id AND u.user_id=:uid",
            ['id' => $message_id, 'uid' => $me['id']]
        );
        if ($msg) {
            db_exec('UPDATE email_messages SET is_seen=1 WHERE id=:id', ['id' => $message_id]);
        }
        // No redirect — used for AJAX in future. For now, just bounce back.
        header('Location: email.php?account=' . (int)($msg['account_id'] ?? 0));
        exit;
    }
}

$page_title = 'Email';
require __DIR__ . '/_guard.php';

// Accounts this user has access to
$accounts = db_all(
    "SELECT a.*
       FROM email_accounts a
       JOIN email_account_users u ON u.account_id = a.id
      WHERE u.user_id = :uid
      ORDER BY a.display_name",
    ['uid' => $me['id']]
);

// Active account from URL ?account=, fallback to first
$active_id = (int)($_GET['account'] ?? 0);
if (!$active_id && !empty($accounts)) $active_id = (int)$accounts[0]['id'];
$active = null;
foreach ($accounts as $a) if ((int)$a['id'] === $active_id) { $active = $a; break; }

// Listing for active account
$active_folder = $_GET['folder'] ?? 'INBOX';
if (!in_array($active_folder, ['INBOX','SENT'], true)) $active_folder = 'INBOX';

// Resolve "SENT" → the account's configured sent folder name
$actual_folder = $active_folder === 'SENT'
    ? ($active['imap_sent_folder'] ?? 'Sent')
    : 'INBOX';

// ─── Search & filter parameters ───────────────────────────────
$search_q     = trim((string)($_GET['q']        ?? ''));
$filter_status= (string)($_GET['status']   ?? '');   // '', unread, flagged, answered, attach
$filter_after = trim((string)($_GET['after']    ?? ''));   // YYYY-MM-DD
$filter_before= trim((string)($_GET['before']   ?? ''));   // YYYY-MM-DD
$normal_limit = 100;
$search_limit = 200;
$search_error = '';

// Normalise date inputs — accept blank, validate ISO-ish format
$filter_after  = preg_match('/^\d{4}-\d{2}-\d{2}$/', $filter_after)  ? $filter_after  : '';
$filter_before = preg_match('/^\d{4}-\d{2}-\d{2}$/', $filter_before) ? $filter_before : '';

// Valid statuses
if (!in_array($filter_status, ['', 'unread', 'flagged', 'answered', 'attach', 'unanswered'], true)) {
    $filter_status = '';
}

// Have we got any filter applied at all?
$has_filters = $search_q !== ''
    || $filter_status !== ''
    || $filter_after !== ''
    || $filter_before !== '';

$messages = [];
if ($active) {
    // Build WHERE clauses incrementally so we can mix any number of filters
    $clauses = ['account_id = :a', 'folder = :f', 'is_deleted = 0'];
    $params  = ['a' => $active_id, 'f' => $actual_folder];

    // Text search across multiple columns
    if ($search_q !== '') {
        $needle = '%' . addcslashes($search_q, '%_\\') . '%';
        $clauses[] = '( subject    LIKE :q1
                     OR snippet    LIKE :q2
                     OR body_text  LIKE :q3
                     OR from_name  LIKE :q4
                     OR from_email LIKE :q5
                     OR to_list    LIKE :q6
                     OR cc_list    LIKE :q7 )';
        $params['q1'] = $needle; $params['q2'] = $needle; $params['q3'] = $needle;
        $params['q4'] = $needle; $params['q5'] = $needle; $params['q6'] = $needle;
        $params['q7'] = $needle;
    }

    // Status filter
    switch ($filter_status) {
        case 'unread':     $clauses[] = 'is_seen = 0';     break;
        case 'flagged':    $clauses[] = 'is_flagged = 1';  break;
        case 'answered':   $clauses[] = 'is_answered = 1'; break;
        case 'unanswered': $clauses[] = 'is_answered = 0'; break;
        case 'attach':     $clauses[] = 'has_attachments = 1'; break;
    }

    // From filter is intentionally absent — the main search box already
    // covers from_name and from_email, so a dedicated From field would be
    // redundant.

    // Date range
    if ($filter_after !== '') {
        $clauses[] = 'sent_at >= :after';
        $params['after'] = $filter_after . ' 00:00:00';
    }
    if ($filter_before !== '') {
        $clauses[] = 'sent_at <= :before';
        $params['before'] = $filter_before . ' 23:59:59';
    }

    $limit = $has_filters ? $search_limit : $normal_limit;
    $where = implode(' AND ', $clauses);
    $sql = "SELECT *
              FROM email_messages
             WHERE {$where}
             ORDER BY sent_at DESC, id DESC
             LIMIT " . (int)$limit;

    try {
        $messages = db_all($sql, $params);
    } catch (Throwable $e) {
        $search_error = $e->getMessage();
        if (function_exists('app_log')) app_log('email search failed: ' . $e->getMessage());
        $messages = [];
    }
}

// Helper used by the toolbar to keep one filter while changing others
function filter_url(string $base, array $current, array $changes): string {
    $merged = array_merge($current, $changes);
    // Strip empty values so URLs stay tidy
    $merged = array_filter($merged, fn($v) => $v !== '' && $v !== null);
    return $base . (empty($merged) ? '' : '?' . http_build_query($merged));
}

$current_filters = [
    'account' => $active_id,
    'folder'  => $active_folder,
    'q'       => $search_q,
    'status'  => $filter_status,
    'after'   => $filter_after,
    'before'  => $filter_before,
];

// Bulk-resolve sender (or recipient, for Sent folder) emails to member pills.
// One pass through the list collecting addresses, then one resolve call per
// unique address. Cheaper than doing it inside the render loop.
require_once __DIR__ . '/../includes/email_contacts.php';

$is_sent_folder = ($active_folder === 'SENT');
$emails_to_resolve = [];
foreach ($messages as $m) {
    if ($is_sent_folder) {
        // For Sent, show the first recipient instead of the sender (which is us)
        $to = (string)($m['to_list'] ?? '');
        if (preg_match('/<([^>]+)>/', $to, $mm)) {
            $emails_to_resolve[strtolower(trim($mm[1]))] = true;
        } elseif ($to !== '') {
            $first = trim(explode(',', $to)[0]);
            if (filter_var($first, FILTER_VALIDATE_EMAIL)) {
                $emails_to_resolve[strtolower($first)] = true;
            }
        }
    } else {
        if (!empty($m['from_email'])) {
            $emails_to_resolve[strtolower($m['from_email'])] = true;
        }
    }
}
$contact_lookup = [];
try {
    $contact_lookup = email_resolve_contacts(array_keys($emails_to_resolve));
} catch (Throwable $e) {
    if (function_exists('app_log')) app_log('email contact lookup failed: ' . $e->getMessage());
    // Fall back to empty lookup — rows will display raw emails
}

// Unread count badges for each account
$unread_by_acct = [];
if (!empty($accounts)) {
    $rows = db_all(
        "SELECT account_id, COUNT(*) AS c
           FROM email_messages
          WHERE folder='INBOX' AND is_seen=0 AND is_deleted=0
          GROUP BY account_id"
    );
    foreach ($rows as $r) $unread_by_acct[(int)$r['account_id']] = (int)$r['c'];
}

// Status filter counts for the current account/folder
$filter_counts = ['all'=>0, 'unread'=>0, 'flagged'=>0, 'unanswered'=>0, 'attach'=>0];
if ($active) {
    try {
        $row = db_row(
            "SELECT COUNT(*) AS all_c,
                    SUM(CASE WHEN is_seen=0      THEN 1 ELSE 0 END) AS unread_c,
                    SUM(CASE WHEN is_flagged=1   THEN 1 ELSE 0 END) AS flagged_c,
                    SUM(CASE WHEN is_answered=0  THEN 1 ELSE 0 END) AS unanswered_c,
                    SUM(CASE WHEN has_attachments=1 THEN 1 ELSE 0 END) AS attach_c
               FROM email_messages
              WHERE account_id=:a AND folder=:f AND is_deleted=0",
            ['a' => $active_id, 'f' => $actual_folder]
        );
        $filter_counts = [
            'all'        => (int)($row['all_c']        ?? 0),
            'unread'     => (int)($row['unread_c']     ?? 0),
            'flagged'    => (int)($row['flagged_c']    ?? 0),
            'unanswered' => (int)($row['unanswered_c'] ?? 0),
            'attach'     => (int)($row['attach_c']     ?? 0),
        ];
    } catch (Throwable $_) { /* keep zeros */ }
}
?>

<style>
.eml-page{padding:0;margin:0 0 2rem;}
.eml-tabs{
    display:flex;gap:.4rem;flex-wrap:wrap;margin-bottom:1rem;
    border-bottom:1px solid var(--line);padding-bottom:.75rem;
}
.eml-tab{
    display:inline-flex;align-items:center;gap:.5rem;
    padding:.5rem .9rem;border-radius:8px 8px 0 0;
    border:1px solid var(--line);border-bottom:none;
    background:#fff;color:var(--ink);text-decoration:none;font-size:.88rem;
    position:relative;top:1px;
}
.eml-tab.on{background:var(--surface-alt);font-weight:700;}
.eml-tab .acct-dot{
    width:10px;height:10px;border-radius:50%;flex-shrink:0;
}
.eml-tab .unread-pill{
    background:#dc2626;color:#fff;font-size:.68rem;padding:.05em .45em;border-radius:999px;
    font-weight:700;
}

.eml-actions{display:flex;justify-content:space-between;align-items:center;gap:.75rem;margin-bottom:.85rem;flex-wrap:wrap;}
.eml-actions .left{display:flex;gap:.5rem;align-items:center;flex-wrap:wrap;}
.eml-actions .right{font-size:.82rem;color:var(--ink-muted);}

/* Single-row search bar: text search + After/Before all inline */
.eml-search{
    display:inline-flex;align-items:center;gap:.4rem;
    background:#fff;border:1px solid var(--line);border-radius:6px;
    padding:.35rem .65rem;
    flex:0 1 auto;max-width:100%;
    transition:.15s;flex-wrap:wrap;
}
.eml-search:focus-within{border-color:var(--brand-primary);box-shadow:0 0 0 3px rgba(99,102,241,.12);}
.eml-search-icon{font-size:.85rem;opacity:.5;}
.eml-search-input{
    border:none;outline:none;background:transparent;
    flex:0 1 220px;font-family:inherit;font-size:.9rem;padding:.25rem 0;
    min-width:140px;width:220px;
}

/* Visual divider between text search and the filter inputs */
.eml-divider{
    width:1px;height:22px;background:var(--line);margin:0 .2rem;flex-shrink:0;
}

/* Date filter inputs — bigger and more readable */
.eml-filter-input{
    border:1px solid transparent;outline:none;background:transparent;
    font-family:inherit;font-size:.85rem;padding:.3rem .5rem;
    color:var(--ink);border-radius:5px;
    flex:0 0 auto;
}
.eml-filter-input:hover{background:var(--surface-alt);}
.eml-filter-input:focus{background:var(--surface-alt);border-color:var(--brand-primary);}
.eml-filter-date{
    width:140px;color:var(--ink-muted);
    font-variant-numeric:tabular-nums;
}
.eml-filter-date:valid{color:var(--ink);}

.eml-apply-btn{
    background:var(--brand-primary);color:#fff;border:none;
    border-radius:5px;padding:.45rem 1rem;font-size:.85rem;font-weight:600;
    cursor:pointer;font-family:inherit;line-height:1;flex-shrink:0;
}
.eml-apply-btn:hover{filter:brightness(0.9);}

.eml-search-clear{
    color:var(--ink-muted);text-decoration:none;font-size:1.2rem;line-height:1;
    padding:.2rem .45rem;border-radius:5px;flex-shrink:0;
}
.eml-search-clear:hover{background:#fee2e2;color:#991b1b;}

.eml-search-status{
    font-size:.78rem;color:var(--ink-muted);margin-bottom:.75rem;
}
.eml-search-status a{color:var(--ink-muted);text-decoration:underline dotted;}
.eml-search-status a:hover{color:var(--ink);}

/* Status filter chips */
.eml-chips{
    display:flex;flex-wrap:wrap;gap:.4rem;margin-bottom:.85rem;
}
.eml-chip{
    display:inline-flex;align-items:center;gap:.4rem;
    padding:.35rem .85rem;border-radius:999px;
    background:#fff;color:var(--ink);text-decoration:none;
    border:1px solid var(--line);font-size:.82rem;font-weight:500;
    transition:.15s;
}
.eml-chip:hover{background:var(--surface-alt);}
.eml-chip.on{
    background:var(--brand-primary);color:#fff;border-color:var(--brand-primary);
}
.eml-chip .ct{
    font-size:.7rem;background:rgba(0,0,0,.1);padding:.05em .45em;border-radius:999px;
    font-weight:600;
}
.eml-chip.on .ct{background:rgba(255,255,255,.25);}

.eml-list{background:#fff;border:1px solid var(--line);border-radius:8px;overflow:hidden;}
.eml-row{
    display:grid;grid-template-columns:200px 1fr 120px;
    padding:.7rem 1rem;border-bottom:1px solid var(--line);
    cursor:pointer;align-items:start;gap:.75rem;
}
.eml-row:last-child{border-bottom:none;}
.eml-row:hover{background:#fafaf8;}
.eml-row.is-unread{background:#fffbeb;}
.eml-row.is-unread:hover{background:#fef9e7;}
.eml-row .from{
    font-weight:600;font-size:.88rem;color:var(--ink);
    overflow:hidden;text-overflow:ellipsis;white-space:nowrap;
}
.eml-row.is-unread .from{color:#000;}

/* Member-match pills shown inline in the inbox list */
.row-pill{
    display:inline-flex;align-items:center;gap:.35rem;
    padding:.15rem .55rem;border-radius:999px;
    font-size:.78rem;font-weight:500;line-height:1.4;
    max-width:100%;overflow:hidden;
}
.row-pill .row-pill-prefix{
    font-size:.68rem;text-transform:uppercase;letter-spacing:.05em;
    opacity:.7;font-weight:600;
}
.row-pill .row-pill-label{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}

.row-pill.match-exact{background:#e0e7ff;color:#3730a3;}
.row-pill.match-domain{background:#fef3c7;color:#92400e;}
.row-pill.match-none{background:transparent;color:var(--ink);padding-left:0;padding-right:0;}
.eml-row.is-unread .row-pill.match-none{color:#000;}
.eml-row .subj{font-size:.88rem;color:var(--ink);overflow:hidden;}
.eml-row.is-unread .subj{font-weight:600;}
.eml-row .snip{font-size:.78rem;color:var(--ink-muted);margin-top:.2rem;display:-webkit-box;-webkit-line-clamp:1;-webkit-box-orient:vertical;overflow:hidden;}
.eml-row .when{font-size:.78rem;color:var(--ink-muted);text-align:right;white-space:nowrap;}
.eml-row .icons{font-size:.72rem;color:var(--ink-muted);}
.eml-row .ic{margin-right:.3rem;}

.eml-empty{padding:3rem 1rem;text-align:center;color:var(--ink-muted);}
.eml-empty .ic{font-size:2rem;opacity:.4;display:block;margin-bottom:.5rem;}

.no-accts{
    background:#fff;border:1px solid var(--line);border-radius:8px;
    padding:2.5rem 1.5rem;text-align:center;color:var(--ink-muted);
}

.flash{
    padding:.7rem 1rem;border-radius:6px;margin-bottom:1rem;font-size:.88rem;
    background:#dbeafe;color:#1e40af;border:1px solid #93c5fd;
}
.flash.bad{background:#fef2f2;color:#991b1b;border-color:#fca5a5;}
</style>

<section class="section"><div class="container">

<div style="display:flex;justify-content:space-between;align-items:center;gap:1rem;flex-wrap:wrap;margin-bottom:1rem;">
    <h1 style="margin:0;">Email</h1>
    <div style="display:flex;gap:.5rem;">
        <a href="email-signature.php" class="btn btn-outline" style="font-size:.82rem;padding:.4rem .85rem;">✎ My signature</a>
        <a href="email-whitelist.php" class="btn btn-outline" style="font-size:.82rem;padding:.4rem .85rem;">🛡 Whitelist</a>
        <?php if ($me['role'] === 'super_admin'): ?>
            <a href="email-accounts.php" class="btn btn-outline" style="font-size:.82rem;padding:.4rem .85rem;">⚙ Manage mailboxes</a>
        <?php endif; ?>
    </div>
</div>

<?php if (!empty($_GET['msg'])): ?>
    <?php $msg_text = (string)$_GET['msg']; $is_err = stripos($msg_text, 'fail') !== false; ?>
    <div class="flash <?= $is_err ? 'bad' : '' ?>"><?= htmlspecialchars($msg_text) ?></div>
<?php endif; ?>

<?php if (empty($accounts)): ?>
    <div class="no-accts">
        <p style="margin:0 0 .5rem;">You don't have access to any mailboxes yet.</p>
        <p style="margin:0;font-size:.85rem;">
            <?php if ($me['role'] === 'super_admin'): ?>
                <a href="email-accounts.php">Add a mailbox →</a>
            <?php else: ?>
                Ask a super admin to grant you access in Settings → Email Mailboxes.
            <?php endif; ?>
        </p>
    </div>
<?php else: ?>

    <!-- Account tabs -->
    <div class="eml-tabs">
        <?php foreach ($accounts as $a):
            $unread = $unread_by_acct[(int)$a['id']] ?? 0;
        ?>
            <a href="?account=<?= (int)$a['id'] ?>"
               class="eml-tab <?= (int)$a['id'] === $active_id ? 'on' : '' ?>"
               style="<?= (int)$a['id'] === $active_id ? '--accent:' . htmlspecialchars($a['colour']) . ';border-bottom:3px solid ' . htmlspecialchars($a['colour']) . ';' : '' ?>">
                <span class="acct-dot" style="background:<?= htmlspecialchars($a['colour']) ?>;"></span>
                <span><?= htmlspecialchars($a['display_name']) ?></span>
                <?php if ($unread > 0): ?>
                    <span class="unread-pill"><?= $unread ?></span>
                <?php endif; ?>
            </a>
        <?php endforeach; ?>
    </div>

    <?php if ($active): ?>

        <!-- Folder pills (INBOX / Sent) -->
        <div style="display:flex;gap:.4rem;margin-bottom:.85rem;font-size:.82rem;">
            <a href="?account=<?= (int)$active['id'] ?>&folder=INBOX"
               style="padding:.35rem .9rem;border-radius:999px;text-decoration:none;
                      background:<?= $active_folder==='INBOX' ? 'var(--brand-primary)' : '#fff' ?>;
                      color:<?= $active_folder==='INBOX' ? '#fff' : 'var(--ink)' ?>;
                      border:1px solid <?= $active_folder==='INBOX' ? 'var(--brand-primary)' : 'var(--line)' ?>;">
                📥 Inbox
            </a>
            <a href="?account=<?= (int)$active['id'] ?>&folder=SENT"
               style="padding:.35rem .9rem;border-radius:999px;text-decoration:none;
                      background:<?= $active_folder==='SENT' ? 'var(--brand-primary)' : '#fff' ?>;
                      color:<?= $active_folder==='SENT' ? '#fff' : 'var(--ink)' ?>;
                      border:1px solid <?= $active_folder==='SENT' ? 'var(--brand-primary)' : 'var(--line)' ?>;">
                📤 Sent
            </a>
        </div>

        <div class="eml-actions">
            <div class="left">
                <a href="email-compose.php?mode=new&account=<?= (int)$active['id'] ?>" class="btn"
                   style="padding:.45rem 1rem;font-size:.88rem;">✏ New message</a>
                <form method="post" style="display:inline;">
                    <?= csrf_field() ?>
                    <input type="hidden" name="action" value="sync_now">
                    <input type="hidden" name="account_id" value="<?= (int)$active['id'] ?>">
                    <button type="submit" class="btn btn-outline" style="padding:.4rem .85rem;font-size:.82rem;"
                            onclick="this.disabled=true;this.innerHTML='Syncing… (may take a minute)';this.form.submit();">
                        ↻ Sync now
                    </button>
                </form>
                <span class="right" style="margin-left:.5rem;">
                    <?php if (!empty($active['last_synced_at'])): ?>
                        Last sync <?= htmlspecialchars(date('j M H:i', strtotime($active['last_synced_at']))) ?>
                    <?php else: ?>
                        Never synced
                    <?php endif; ?>
                </span>
            </div>
            <form method="get" class="eml-search" id="eml-search-form">
                <input type="hidden" name="account" value="<?= (int)$active['id'] ?>">
                <input type="hidden" name="folder"  value="<?= htmlspecialchars($active_folder) ?>">
                <?php if ($filter_status !== ''): ?>
                    <input type="hidden" name="status" value="<?= htmlspecialchars($filter_status) ?>">
                <?php endif; ?>

                <span class="eml-search-icon">🔍</span>
                <input type="search" name="q" value="<?= htmlspecialchars($search_q) ?>"
                       placeholder="Search subject, sender, body…"
                       autocomplete="off"
                       class="eml-search-input">

                <span class="eml-divider"></span>

                <input type="date" name="after" value="<?= htmlspecialchars($filter_after) ?>"
                       class="eml-filter-input eml-filter-date"
                       title="On or after this date">

                <input type="date" name="before" value="<?= htmlspecialchars($filter_before) ?>"
                       class="eml-filter-input eml-filter-date"
                       title="On or before this date">

                <button type="submit" class="eml-apply-btn" title="Search">Search</button>

                <?php if ($has_filters): ?>
                    <a href="email.php?account=<?= (int)$active['id'] ?>&folder=<?= htmlspecialchars($active_folder) ?>"
                       class="eml-search-clear" title="Clear all filters">×</a>
                <?php endif; ?>
            </form>
        </div>

        <!-- Status filter chips -->
        <div class="eml-chips">
            <?php
            $chips = [
                ['key'=>'',           'label'=>'All',          'count'=>$filter_counts['all']],
                ['key'=>'unread',     'label'=>'Unread',       'count'=>$filter_counts['unread']],
                ['key'=>'flagged',    'label'=>'Flagged',      'count'=>$filter_counts['flagged']],
                ['key'=>'unanswered', 'label'=>'Needs reply',  'count'=>$filter_counts['unanswered']],
                ['key'=>'attach',     'label'=>'Attachments',  'count'=>$filter_counts['attach']],
            ];
            foreach ($chips as $c):
                $is_on = ($filter_status === $c['key']);
                $url = filter_url('email.php', $current_filters, ['status' => $c['key']]);
            ?>
                <a href="<?= htmlspecialchars($url) ?>" class="eml-chip <?= $is_on ? 'on' : '' ?>">
                    <?= htmlspecialchars($c['label']) ?>
                    <?php if ($c['count'] > 0): ?>
                        <span class="ct"><?= (int)$c['count'] ?></span>
                    <?php endif; ?>
                </a>
            <?php endforeach; ?>
        </div>

        <!-- Status line -->
        <?php if ($has_filters): ?>
            <div class="eml-search-status">
                <?= count($messages) ?> result<?= count($messages) === 1 ? '' : 's' ?>
                <?php
                $bits = [];
                if ($search_q !== '')      $bits[] = 'matching "' . htmlspecialchars($search_q) . '"';
                if ($filter_status !== '') $bits[] = 'status: <strong>' . htmlspecialchars(['unread'=>'unread','flagged'=>'flagged','answered'=>'replied','unanswered'=>'needs reply','attach'=>'with attachments'][$filter_status] ?? $filter_status) . '</strong>';
                if ($filter_after !== '')  $bits[] = 'after ' . htmlspecialchars($filter_after);
                if ($filter_before !== '') $bits[] = 'before ' . htmlspecialchars($filter_before);
                if (!empty($bits)) echo ' · ' . implode(' · ', $bits);
                ?>
                <?php if (count($messages) >= $search_limit): ?>
                    · showing first <?= $search_limit ?>, refine to narrow
                <?php endif; ?>
                · <a href="email.php?account=<?= (int)$active['id'] ?>&folder=<?= htmlspecialchars($active_folder) ?>">clear all filters</a>
            </div>
        <?php else: ?>
            <div class="eml-search-status">
                <?= count($messages) ?> shown · most recent <?= $normal_limit ?>
            </div>
        <?php endif; ?>

        <?php if (!empty($active['last_error'])): ?>
            <div class="flash bad" style="margin-bottom:1rem;">
                ⚠ Last sync error: <?= htmlspecialchars(mb_substr((string)$active['last_error'], 0, 300)) ?>
            </div>
        <?php endif; ?>

        <?php if ($search_error !== ''): ?>
            <div class="flash bad" style="margin-bottom:1rem;">
                ⚠ Search failed: <?= htmlspecialchars(mb_substr($search_error, 0, 400)) ?>
            </div>
        <?php endif; ?>

        <?php if (empty($messages)): ?>
            <div class="eml-list">
                <div class="eml-empty">
                    <span class="ic"><?= $has_filters ? '🔍' : '📭' ?></span>
                    <?php if ($has_filters): ?>
                        <p style="margin:0 0 .25rem;">No messages match your filters.</p>
                        <p style="margin:0;font-size:.82rem;">
                            Try removing some, or
                            <a href="email.php?account=<?= (int)$active['id'] ?>&folder=<?= htmlspecialchars($active_folder) ?>">clear all filters</a>.
                        </p>
                    <?php else: ?>
                        <p style="margin:0 0 .25rem;">No messages yet.</p>
                        <p style="margin:0;font-size:.82rem;">Click "Sync now" to pull mail from this mailbox.</p>
                    <?php endif; ?>
                </div>
            </div>
        <?php else: ?>
            <div class="eml-list">
                <?php foreach ($messages as $m):
                    $unread_cls = $m['is_seen'] ? '' : 'is-unread';

                    // Resolve the relevant email (sender for inbox, first recipient for Sent)
                    if ($is_sent_folder) {
                        $to_str = (string)($m['to_list'] ?? '');
                        if (preg_match('/<([^>]+)>/', $to_str, $mm)) {
                            $relevant_email = strtolower(trim($mm[1]));
                        } else {
                            $first = trim(explode(',', $to_str)[0]);
                            $relevant_email = filter_var($first, FILTER_VALIDATE_EMAIL)
                                ? strtolower($first) : '';
                        }
                        $relevant_name = '';
                    } else {
                        $relevant_email = strtolower((string)($m['from_email'] ?? ''));
                        $relevant_name  = $m['from_name'] ?? '';
                    }

                    $contact = $contact_lookup[$relevant_email] ?? null;

                    // Display label and pill class
                    if ($contact && $contact['match'] === 'exact') {
                        $disp_label = $contact['label'];
                        $pill_cls   = 'match-exact';
                        $tooltip    = $contact['label'] . ' — ' . $relevant_email;
                    } elseif ($contact && $contact['match'] === 'domain') {
                        $disp_label = $contact['label'] ?: $relevant_email;
                        $pill_cls   = 'match-domain';
                        $tooltip    = $contact['label'] . ' — ' . $relevant_email;
                    } else {
                        // Unknown — show the name from email headers if present, else email
                        $disp_label = $relevant_name ?: $relevant_email ?: 'Unknown';
                        $pill_cls   = 'match-none';
                        $tooltip    = $relevant_email;
                    }

                    $when_ts    = $m['sent_at'] ? strtotime($m['sent_at']) : null;
                    $when_str   = $when_ts ? date('j M', $when_ts) : '—';
                    if ($when_ts && date('Y-m-d', $when_ts) === date('Y-m-d')) {
                        $when_str = date('H:i', $when_ts);
                    } elseif ($when_ts && date('Y', $when_ts) !== date('Y')) {
                        $when_str = date('j M y', $when_ts);
                    }
                ?>
                    <a class="eml-row <?= $unread_cls ?>"
                       href="email-message.php?id=<?= (int)$m['id'] ?>"
                       style="text-decoration:none;color:inherit;">
                        <div class="from">
                            <span class="row-pill <?= $pill_cls ?>" title="<?= htmlspecialchars($tooltip) ?>">
                                <?php if ($is_sent_folder): ?>
                                    <span class="row-pill-prefix">to</span>
                                <?php endif; ?>
                                <span class="row-pill-label"><?= htmlspecialchars($disp_label) ?></span>
                            </span>
                        </div>
                        <div>
                            <div class="subj">
                                <span class="icons">
                                    <?= $m['is_answered'] ? '<span class="ic" title="Replied">↩</span>' : '' ?>
                                    <?= $m['is_flagged']  ? '<span class="ic" title="Flagged">⚑</span>' : '' ?>
                                    <?= $m['has_attachments'] ? '<span class="ic" title="Attachment">📎</span>' : '' ?>
                                </span>
                                <?= htmlspecialchars($m['subject'] ?: '(no subject)') ?>
                            </div>
                            <div class="snip"><?= htmlspecialchars((string)$m['snippet']) ?></div>
                        </div>
                        <div class="when"><?= htmlspecialchars($when_str) ?></div>
                    </a>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    <?php endif; ?>

<?php endif; ?>

</div></section>

<script>
(function () {
    // Strip empty filter params before form submit, so URLs stay tidy.
    const form = document.getElementById('eml-search-form');
    if (form) {
        form.addEventListener('submit', () => {
            ['q', 'after', 'before', 'status'].forEach(name => {
                const inputs = form.querySelectorAll(`[name="${name}"]`);
                inputs.forEach(input => {
                    if (input.value === '' || input.value === null) {
                        input.disabled = true; // disabled fields aren't submitted
                    }
                });
            });
        });
    }
})();
</script>

<?php require __DIR__ . '/_footer.php'; ?>