<?php
// One-off fix: mail.brcomputersmw.com resolves to a shared cPanel server whose SSL
// certificate covers *.web-hosting.com, not the customer's domain, causing a
// "Certificate failure: Hostname mismatch" error. Reverse DNS on the mail server's IP
// (162.0.232.75) resolves to business75-2.web-hosting.com, which IS covered by the
// cert's Subject Alternative Name (confirmed via `openssl s_client ... Verify return
// code: 0 (ok)`). Using that hostname instead lets TLS validate properly with no
// security tradeoff, so this also re-enables verify_cert.
// Run once on the live server (php tmp_fix_mailbox_hostname_cert.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' => 'business75-2.web-hosting.com',
    'imap_host' => 'business75-2.web-hosting.com',
    'verify_cert' => 'true',
], null);

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

echo "\nDone. Reload the Mailbox Settings page - the certificate error should be gone and verification is back on securely.\n";
