function loadEmailList($filename) {
$emails = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
return array_map('trim', $emails);
}

function getDomainFromEmail($email) {
$parts = explode('@', $email);
return $parts[1] ?? null;
}

function logError($message) {
file_put_contents('errors.log', "[" . date('Y-m-d H:i:s') . "] $message\n", FILE_APPEND);
}

function checkURLExistsWithFallback($url) {
$headers = @get_headers($url, 1);
if ($headers && isset($headers[0]) && preg_match('/200|301|302/', $headers[0])) {
return ['status' => 'Yes (HTTPS)', 'headers' => $headers];
}

$httpUrl = preg_replace('/^https:/', 'http:', $url);
$headers = @get_headers($httpUrl, 1);
if ($headers && isset($headers[0]) && preg_match('/200|301|302/', $headers[0])) {
return ['status' => 'Yes (HTTP)', 'headers' => $headers];
}

logError("URL not reachable: $url and $httpUrl");
return ['status' => 'No', 'headers' => []];
}

function checkMXRecords($domain) {
$mxhosts = [];
$cpanelDetected = false;

if (getmxrr($domain, $mxhosts)) {
foreach ($mxhosts as $mx) {
if (preg_match('/cpanel|mail|webmail/i', $mx)) {
$cpanelDetected = true;
break;
}
}
}

return [
'mx_records' => implode(', ', $mxhosts),
'cpanel_mx' => $cpanelDetected ? 'Yes' : 'No'
];
}

function analyzeHeadersForCpanel($headersArray) {
foreach ($headersArray as $key => $value) {
if (is_array($value)) $value = implode('; ', $value);
$key = strtolower($key);
$value = strtolower($value);
if (strpos($key, 'server') !== false && strpos($value, 'cpanel') !== false) return 'Yes';
if (strpos($key, 'x-powered-by') !== false && strpos($value, 'cpanel') !== false) return 'Yes';
if (strpos($value, 'whm') !== false || strpos($value, 'cpanel') !== false) return 'Yes';
}
return 'No';
}

function checkDomain($domain) {
$urls = [
"https://$domain/roundcube",
"https://$domain/webmail",
"https://webmail.$domain"
];

$results = [];
$headersCollected = [];

foreach ($urls as $url) {
$result = checkURLExistsWithFallback($url);
$results[$url] = $result['status'];
$headersCollected[] = $result['headers'];
}

$cpanelFromHeaders = 'No';
foreach ($headersCollected as $headers) {
if (analyzeHeadersForCpanel($headers) === 'Yes') {
$cpanelFromHeaders = 'Yes';
break;
}
}

$mxInfo = checkMXRecords($domain);

return [
'roundcube' => $results["https://$domain/roundcube"],
'webmail_path' => $results["https://$domain/webmail"],
'webmail_subdomain' => $results["https://webmail.$domain"],
'mx_records' => $mxInfo['mx_records'],
'cpanel_mx' => $mxInfo['cpanel_mx'],
'cpanel_headers' => $cpanelFromHeaders,
];
}

function analyzeEmails($emails) {
$results = [];

foreach ($emails as $email) {
$domain = getDomainFromEmail($email);
if (!$domain) {
logError("Invalid email format: $email");
continue;
}

$checkResults = checkDomain($domain);

$results[] = [
'Email' => $email,
'Domain' => $domain,
'domain.com/roundcube' => $checkResults['roundcube'],
'domain.com/webmail' => $checkResults['webmail_path'],
'webmail.domain.com' => $checkResults['webmail_subdomain'],
'MX Records' => $checkResults['mx_records'],
'cPanel via MX' => $checkResults['cpanel_mx'],
'cPanel via Headers' => $checkResults['cpanel_headers'],
];
}

return $results;
}

function saveResultsToCSV($results, $filename = 'results.csv') {
$fp = fopen($filename, 'w');

if (!empty($results)) {
fputcsv($fp, array_keys($results[0]));
foreach ($results as $row) {
fputcsv($fp, $row);
}
}

fclose($fp);
}

// ===== MAIN =====

$emailListFile = 'emails.txt';
$outputFile = 'results.csv';

$emails = loadEmailList($emailListFile);
$results = analyzeEmails($emails);
saveResultsToCSV($results, $outputFile);

echo "✅ Scan complete. Results saved to $outputFile\n";
echo "⚠️ Errors (if any) saved to errors.log\n";