<?php
// One-off fix: sending via business75-2.web-hosting.com (the internal shared-server
// hostname used to satisfy the TLS certificate check) gets rejected by cPanel/Exim's
// mail-domain policy: "Your domain brcomputersmw.com is not allowed in header From".
// That policy is tied to the domain's mail routing on the account, which cPanel only
// recognizes via the officially documented hostname (mail.brcomputersmw.com), not the
// internal server alias. Revert to mail.brcomputersmw.com and disable cert verification
// (its certificate is issued for *.web-hosting.com, not this hostname, so strict
// verification would fail the TLS handshake) to get a working, if unverified, connection.
// Run once on the live server (php tmp_fix_mailbox_smtp_domain.php), then delete it.

require_once __DIR__ . '/classes/Database.php';
require_once __DIR__ . '/classes/MailboxService.php';

$database = new Database();
$conn = $database->getConnection();
if (!$conn) {
    fwrite(STDERR, "Database connection failed. Check config/database.php and make sure MySQL is running.\n");
    exit(1);
}

function currentMailboxSetting(PDO $conn, string $key) {
    $stmt = $conn->prepare('SELECT setting_value FROM mailbox_settings WHERE setting_key = :key');
    $stmt->execute([':key' => $key]);
    return $stmt->fetchColumn();
}

$keysToShow = ['smtp_host', 'imap_host', 'verify_cert'];

echo "Before:\n";
foreach ($keysToShow as $key) {
    echo " - {$key}: " . (currentMailboxSetting($conn, $key) ?: '(empty)') . "\n";
}

$mailboxService = new MailboxService($conn);
$mailboxService->saveSettings([
    'smtp_host' => 'mail.brcomputersmw.com',
    'imap_host' => 'mail.brcomputersmw.com',
    'verify_cert' => 'false',
], null);

echo "\nAfter:\n";
foreach ($keysToShow as $key) {
    echo " - {$key}: " . (currentMailboxSetting($conn, $key) ?: '(empty)') . "\n";
}

echo "\nDone. Try Send Test again. If it still fails with the same 'not allowed in header From' error,\n";
echo "the restriction is enforced server-side (cPanel/WHM SMTP Restrictions) and needs your hosting\n";
echo "provider's support to confirm the account's mail routing for brcomputersmw.com is set to 'Local Mail Exchanger'.\n";
