<?php
// ============================================================
//  Email contact resolution
// ============================================================
//
//  Looks up a member by:
//    1. Exact email match (highest confidence)
//    2. Email domain match (e.g. anyone@elegant.co.za → that business)
//
//  Returns a "pill" descriptor used by the compose UI:
//    ['email'=>..., 'name'=>..., 'business'=>..., 'member_id'=>?int,
//     'label'=>..., 'match'=>'exact'|'domain'|'none']
//
//  Domains we ignore for matching (too generic):
//    gmail.com, yahoo.com, outlook.com, hotmail.com, icloud.com, etc.
//  Matching by these would falsely tag every random Gmail address as
//  some member who happens to have a Gmail address.
// ============================================================

const EMAIL_GENERIC_DOMAINS = [
    'gmail.com', 'googlemail.com', 'yahoo.com', 'yahoo.co.za',
    'outlook.com', 'hotmail.com', 'live.com', 'msn.com',
    'icloud.com', 'me.com', 'aol.com', 'protonmail.com',
    'mail.com', 'mweb.co.za', 'webmail.co.za', 'telkomsa.net',
    'vodamail.co.za', 'mtnloaded.co.za',
];

/**
 * Resolve a single email address to a member pill descriptor.
 *
 * @param string $email
 * @return array{email:string, name:string, business:string, member_id:?int, label:string, match:string}
 */
function email_resolve_contact(string $email): array {
    $email = strtolower(trim($email));
    if ($email === '') {
        return ['email'=>'', 'name'=>'', 'business'=>'', 'member_id'=>null, 'label'=>'', 'match'=>'none'];
    }

    // 1. Exact email match
    $member = db_row(
        "SELECT id, first_name, last_name, business_name, email
           FROM members
          WHERE email = :e
          LIMIT 1",
        ['e' => $email]
    );
    if ($member) {
        return email_format_member_pill($email, $member, 'exact');
    }

    // 2. Domain match (skip generic providers)
    $parts = explode('@', $email);
    if (count($parts) !== 2) {
        return ['email'=>$email, 'name'=>'', 'business'=>'', 'member_id'=>null, 'label'=>$email, 'match'=>'none'];
    }
    $domain = $parts[1];
    if (in_array($domain, EMAIL_GENERIC_DOMAINS, true)) {
        return ['email'=>$email, 'name'=>'', 'business'=>'', 'member_id'=>null, 'label'=>$email, 'match'=>'none'];
    }

    // Match by any member email ending in the same domain
    $member = db_row(
        "SELECT id, first_name, last_name, business_name, email
           FROM members
          WHERE email LIKE :pat
          ORDER BY (email = :e) DESC, business_name
          LIMIT 1",
        ['pat' => '%@' . $domain, 'e' => $email]
    );
    if ($member) {
        return email_format_member_pill($email, $member, 'domain');
    }

    // No match
    return ['email'=>$email, 'name'=>'', 'business'=>'', 'member_id'=>null, 'label'=>$email, 'match'=>'none'];
}

/**
 * Bulk version — resolves multiple emails at once with one query per group.
 * Returns map of email → pill descriptor.
 */
function email_resolve_contacts(array $emails): array {
    $out = [];
    foreach ($emails as $e) {
        if (!isset($out[strtolower($e)])) {
            $out[strtolower($e)] = email_resolve_contact($e);
        }
    }
    return $out;
}

function email_format_member_pill(string $email, array $member, string $match): array {
    $name = trim(($member['first_name'] ?? '') . ' ' . ($member['last_name'] ?? ''));
    $biz  = (string)($member['business_name'] ?? '');

    if ($match === 'domain' && strcasecmp($email, $member['email']) !== 0) {
        // Anyone @business-domain — show just the business, not the person's name
        // (because we don't know who at that company this email belongs to)
        $label = $biz ?: $name;
    } else {
        $label = $name && $biz ? "{$name} · {$biz}"
               : ($name ?: ($biz ?: $email));
    }

    return [
        'email'     => $email,
        'name'      => $name,
        'business'  => $biz,
        'member_id' => (int)$member['id'],
        'label'     => $label,
        'match'     => $match,
    ];
}