<?php
/**
 * Seed transactional-email config into sp_settings (encrypted api key).
 *
 * Brevo (https://app.brevo.com → SMTP & API → API keys). Verify your sender domain/
 * address in Brevo first, or delivery will be rejected.
 *
 * Run (from api/):
 *   BREVO_API_KEY='xkeysib-...' \
 *   EMAIL_FROM='noreply@medellin.co' EMAIL_FROM_NAME='Medellín' \
 *   php db/seed_email.php
 */
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../config.php';

$apiKey    = getenv('BREVO_API_KEY');
$fromEmail = getenv('EMAIL_FROM') ?: ('noreply@' . (parse_url(URL, PHP_URL_HOST) ?: 'localhost'));
$fromName  = getenv('EMAIL_FROM_NAME') ?: (defined('PROJECT_NAME') ? PROJECT_NAME : 'Website');

if ($apiKey === false || $apiKey === '') {
    fwrite(STDERR, "Set BREVO_API_KEY in the environment.\n");
    exit(1);
}

$meta = [
    'provider'   => 'brevo',
    'api_key'    => \Functions::Encrypt($apiKey),
    'from_email' => $fromEmail,
    'from_name'  => $fromName,
];

\Db::execute("DELETE FROM sp_settings WHERE keyval = ?", ['email']);
\Db::execute(
    "INSERT INTO sp_settings (keyval, `group`, metval, status, encrypted, createdate) VALUES ('email', 'email', ?, 1, 1, ?)",
    [json_encode($meta), date('Y-m-d H:i:s')]
);

echo "saved email (provider=brevo, from={$fromName} <{$fromEmail}>, encrypted=1)\n";
