<?php
// ============================================================
//  admin/email-search-contacts.php — JSON search for compose
// ============================================================
//
//  Called by email-compose.php via fetch() as the user types in
//  To/Cc/Bcc fields. Returns up to 8 matching members.
//
//  Matches on: email, first_name, last_name, business_name.
//  Email-domain match also flagged so the UI can show
//  "anyone@<domain>" suggestions.
//
//  Response shape:
//    [
//      {
//        "type": "member",
//        "email": "mary@elegant.co.za",
//        "name": "Mary Smith",
//        "business": "Elegant Work",
//        "label": "Mary Smith · Elegant Work",
//        "member_id": 42,
//        "match": "email"|"name"|"business"|"domain"
//      },
//      ...
//    ]
// ============================================================

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

header('Content-Type: application/json; charset=utf-8');
header('X-Content-Type-Options: nosniff');

$q = trim((string)($_GET['q'] ?? ''));
if (mb_strlen($q) < 2) { echo json_encode([]); exit; }

$results = [];

// 1. Exact email or partial-email match
$by_email = db_all(
    "SELECT id, first_name, last_name, business_name, email
       FROM members
      WHERE email LIKE :q
      ORDER BY (email = :exact) DESC, business_name, last_name
      LIMIT 6",
    ['q' => '%' . $q . '%', 'exact' => $q]
);
foreach ($by_email as $m) {
    $name = trim(($m['first_name'] ?? '') . ' ' . ($m['last_name'] ?? ''));
    $biz  = (string)($m['business_name'] ?? '');
    $label = $name && $biz ? "{$name} · {$biz}"
           : ($name ?: ($biz ?: $m['email']));
    $results[] = [
        'type'      => 'member',
        'email'     => $m['email'],
        'name'      => $name,
        'business'  => $biz,
        'label'     => $label,
        'member_id' => (int)$m['id'],
        'match'     => 'email',
    ];
}

// 2. Name / business-name match (only if we don't already have results)
if (mb_strlen($q) >= 2) {
    $by_name = db_all(
        "SELECT id, first_name, last_name, business_name, email
           FROM members
          WHERE (first_name LIKE :q OR last_name LIKE :q OR business_name LIKE :q)
            AND email NOT LIKE :qe
          ORDER BY
            CASE WHEN business_name LIKE :qstart THEN 0 ELSE 1 END,
            business_name, last_name
          LIMIT 6",
        ['q' => '%' . $q . '%', 'qstart' => $q . '%', 'qe' => '%' . $q . '%']
    );
    foreach ($by_name as $m) {
        $name = trim(($m['first_name'] ?? '') . ' ' . ($m['last_name'] ?? ''));
        $biz  = (string)($m['business_name'] ?? '');
        $label = $name && $biz ? "{$name} · {$biz}"
               : ($name ?: ($biz ?: $m['email']));
        $match = stripos($biz, $q) !== false ? 'business' : 'name';
        $results[] = [
            'type'      => 'member',
            'email'     => $m['email'],
            'name'      => $name,
            'business'  => $biz,
            'label'     => $label,
            'member_id' => (int)$m['id'],
            'match'     => $match,
        ];
    }
}

// Dedupe by email
$seen = [];
$unique = [];
foreach ($results as $r) {
    $key = strtolower($r['email']);
    if (isset($seen[$key])) continue;
    $seen[$key] = true;
    $unique[] = $r;
    if (count($unique) >= 8) break;
}

echo json_encode($unique, JSON_UNESCAPED_UNICODE);