<?php
echo "<h1>Server Email Sending Limit Checker</h1>";
echo "<pre>";

echo "⚠️ Note: Exact hourly limit cannot be read from PHP on shared hosting.\n";
echo "This script will check logs for any rate limit messages.\n\n";

$user = get_current_user();
$possible_logs = [
    "/home/{$user}/.logs/exim.log",           // Most common in cPanel
    "/home/{$user}/.logs/maillog",
    "/var/log/exim_mainlog",
    "/var/log/maillog",
    "/var/log/mail.log"
];

$limit_found = false;
$log_checked = 0;

foreach ($possible_logs as $log) {
    if (file_exists($log)) {
        $log_checked++;
        echo "✅ Found log: " . basename($log) . "\n";
        
        // Read last 100 lines safely
        $lines = [];
        if (is_readable($log)) {
            $handle = fopen($log, "r");
            if ($handle) {
                fseek($handle, -4096, SEEK_END); // last ~4KB
                $content = fread($handle, 4096);
                fclose($handle);
                $lines = array_slice(explode("\n", $content), -80); // last 80 lines
            }
        }

        $recent_log = implode("\n", $lines);
        
        echo "Last ~80 lines preview:\n" . htmlspecialchars(substr($recent_log, -1500)) . "\n\n";

        // Check for limit related messages
        $keywords = ['RATE LIMIT', 'too many', '421', 'exceeded', 'deferred', 'max hourly', 'limit exceeded'];
        foreach ($keywords as $kw) {
            if (stripos($recent_log, $kw) !== false) {
                echo "⚠️ POSSIBLE RATE LIMIT DETECTED: '{$kw}' found in log!\n";
                $limit_found = true;
            }
        }
    }
}

if ($log_checked == 0) {
    echo "❌ No mail logs found that are readable from PHP.\n";
}

echo "\n<strong>Summary:</strong>\n";
if ($limit_found) {
    echo "❌ Your account has likely hit the sending limit recently.\n";
} else {
    echo "✅ No obvious rate limit error found in accessible logs.\n";
}

echo "\nTypical Shared Hosting Limits (approximate):\n";
echo "- 200 ~ 500 emails per hour (total from whole account)\n";
echo "- 2000 ~ 5000 emails per day\n";
echo "- Some hosts: 100-300 per hour\n\n";

echo "✅ Best & Most Accurate Methods:\n";
echo "1. cPanel → Metrics → Email Reports (or Track Delivery)\n";
echo "   → Here you can see how many emails sent in last hour/24h\n";
echo "2. cPanel → Email → Track Delivery\n";
echo "3. Contact your hosting support and ask: \"What is my current hourly email sending limit?\"\n\n";

echo "If you frequently need to send more emails, I strongly recommend using external SMTP services like:\n";
echo "• Brevo (Sendinblue) - Free 300/day\n";
echo "• SendGrid\n";
echo "• Mailgun\n";
echo "• Amazon SES\n";

echo "</pre>";
?>