<?php
/**
 * CLI: notify archival-enabled mailboxes of their Bichon archive login username.
 *
 * The 2026.06.59 backfill renamed Bichon login usernames from the raw email
 * address to a bounded scheme (emailmgmt::deriveBichonUsername). This tells the
 * affected customers their new archive sign-in username (password unchanged).
 *
 * DRY-RUN by default — prints who would be notified. Pass --send to deliver.
 * Run per server (each has its own mailboxes):
 *   php /root/whp/scripts/notify-bichon-username-change.php          # preview
 *   php /root/whp/scripts/notify-bichon-username-change.php --send   # deliver
 */

if (php_sapi_name() !== 'cli') { http_response_code(403); exit("CLI only\n"); }

require_once('/docker/whp/web/configs/config.php');
require_once('/docker/whp/web/libs/smtp_mailer.php');
require_once('/docker/whp/web/libs/BichonClient.php');
require_once('/docker/whp/web/libs/mysqlmgmt.php');

$send = in_array('--send', $argv ?? [], true);

if (!BichonClient::isConfigured()) { fwrite(STDERR, "Bichon not configured on this host; nothing to notify.\n"); exit(0); }
$smtp = SmtpMailer::loadConfig();
if (!$smtp) { fwrite(STDERR, "SMTP not configured on this host; cannot send.\n"); exit(1); }

$bcfg = BichonClient::loadConfig();
$url  = rtrim((string)($bcfg['url'] ?? ''), '/') . '/';

$db = (new mysqlmgmt())->getMySQLConnection();
$rows = $db->query(
    "SELECT email_address, bichon_username
     FROM whp.email_accounts
     WHERE archival_enabled = 1 AND bichon_username IS NOT NULL AND bichon_username <> ''
     ORDER BY email_address"
)->fetchAll(PDO::FETCH_ASSOC);

echo ($send ? "[SEND]" : "[DRY-RUN]") . " " . count($rows) . " mailbox(es); archive = $url\n";

$mailer = $send ? new SmtpMailer($smtp) : null;
$sent = 0; $failed = 0;
foreach ($rows as $r) {
    $to = $r['email_address'];
    $u  = $r['bichon_username'];
    if (!$send) { echo "  would notify: $to  ->  $u\n"; continue; }

    $subject = 'Your email archive sign-in username has changed';
    $html = '<html><body style="font-family:Arial,sans-serif;color:#333;line-height:1.5">'
          . '<h2 style="color:#2a6">Email archive sign-in update</h2>'
          . '<p>The username you use to sign in to your email <strong>archive</strong> has changed. '
          . 'This affects only viewing your archived mail &mdash; your mailbox, its address, and email '
          . 'delivery are unchanged.</p>'
          . '<table cellpadding="6" style="border-collapse:collapse;margin:12px 0">'
          . '<tr><td style="color:#666">Archive</td><td><a href="' . htmlspecialchars($url) . '">' . htmlspecialchars($url) . '</a></td></tr>'
          . '<tr><td style="color:#666">New username</td><td><code style="font-size:15px">' . htmlspecialchars($u) . '</code></td></tr>'
          . '<tr><td style="color:#666">Password</td><td>unchanged &mdash; the same password as your mailbox (' . htmlspecialchars($to) . ')</td></tr>'
          . '</table>'
          . '<p style="color:#999;font-size:12px">If you don\'t use the email archive, no action is needed.</p>'
          . '</body></html>';
    $text = "Email archive sign-in update\n\n"
          . "The username for signing in to your email ARCHIVE has changed. This affects only\n"
          . "viewing archived mail; your mailbox, address, and email delivery are unchanged.\n\n"
          . "Archive:      $url\n"
          . "New username: $u\n"
          . "Password:     unchanged (same as your mailbox $to)\n\n"
          . "If you don't use the email archive, no action is needed.\n";

    $res = $mailer->send($to, $subject, $html, $text);
    if (!empty($res['success'])) { echo "  sent: $to  ->  $u\n"; $sent++; }
    else { fwrite(STDERR, "  FAIL: $to: " . ($res['error'] ?? 'unknown') . "\n"); $failed++; }
}

echo $send ? "done: $sent sent, $failed failed.\n"
           : "(dry-run; re-run with --send to deliver)\n";
