<?php
// One-off fix: correct the mailbox_settings host/port values that were seeded with the
// wrong provider (Namecheap Private Email) instead of the real cPanel mail server for
// info@brcomputersmw.com. Run this once on the live server (php tmp_fix_mailbox_host.php),
// then delete it. Does not touch mailbox_password or mailbox_enabled.

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 currentMailboxRow(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 = ['mailbox_email', 'smtp_host', 'smtp_port', 'smtp_encryption', 'imap_host', 'imap_port', 'imap_encryption'];

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

$mailboxService = new MailboxService($conn);
$mailboxService->saveSettings([
    'mailbox_email' => 'info@brcomputersmw.com',
    'smtp_host' => 'mail.brcomputersmw.com',
    'smtp_port' => '465',
    'smtp_encryption' => 'ssl',
    'imap_host' => 'mail.brcomputersmw.com',
    'imap_port' => '993',
    'imap_encryption' => 'ssl',
], null);

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

echo "\nDone. mailbox_password and mailbox_enabled were left untouched - set the password and enable the mailbox from views/admin/mailbox_settings.php.\n";
