<?php
/**
 * smtp-set.php — admingrandfather.com: schimbă contul SMTP folosit pentru notificări (SMTP_HOST / PORT / USER / PASS / FROM).
 * Găsește singur fișierul unde sunt definite, face backup, scrie valorile noi, apoi poți trimite un email de test.
 * Parola o scrii tu în formular — nu e salvată nicăieri altundeva. Restore pune înapoi setările vechi. Șterge-l după folosire.
 */
const KEY = '49bb9d96cb5ffaa48db36c78ec8b1212';
if (!isset($_GET['key']) || !hash_equals(KEY, (string)$_GET['key'])) { http_response_code(404); exit('Not found'); }
$R = rtrim($_SERVER['DOCUMENT_ROOT'] ?: __DIR__, '/');
$BAK = '.bak-smtp';
$NAMES = ['SMTP_HOST', 'SMTP_PORT', 'SMTP_USER', 'SMTP_PASS', 'SMTP_FROM'];
function e($v) { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
function rx(string $n): string { return '/define\(\s*([\'"])' . $n . '\1\s*,\s*(?:\'(?:[^\'\\\\]|\\\\.)*\'|"(?:[^"\\\\]|\\\\.)*"|[^)]*?)\s*\)/'; }

/* fișierul care definește SMTP_HOST */
$file = null;
foreach (['config.php', 'core/smtp_mailer.php', 'api/_api_inc.php', 'inc.php', 'core/config.php', 'includes/config.php'] as $f)
    if (is_file("$R/$f") && preg_match(rx('SMTP_HOST'), (string)file_get_contents("$R/$f"))) { $file = "$R/$f"; break; }

$out = []; $err = []; $mode = $_POST['mode'] ?? '';
if ($file && $mode === 'save') {
    $new = [
        'SMTP_HOST' => trim((string)$_POST['host']), 'SMTP_PORT' => (int)$_POST['port'], 'SMTP_USER' => trim((string)$_POST['user']),
        'SMTP_PASS' => (string)$_POST['pass'], 'SMTP_FROM' => trim((string)$_POST['from']),
    ];
    if ($new['SMTP_HOST'] === '' || $new['SMTP_PORT'] <= 0 || !filter_var($new['SMTP_USER'], FILTER_VALIDATE_EMAIL) || !filter_var($new['SMTP_FROM'], FILTER_VALIDATE_EMAIL)) $err[] = 'Fill host, port, username and From with valid values.';
    elseif ($new['SMTP_PASS'] === '') $err[] = 'Type the password of the email account.';
    else {
        $c = (string)file_get_contents($file); $missing = [];
        foreach ($new as $n => $v) {
            $code = "define('$n', " . var_export($v, true) . ")";
            if (preg_match(rx($n), $c)) $c = preg_replace_callback(rx($n), fn() => $code, $c, 1);
            else $missing[] = $code . ';';
        }
        if ($missing) { $pos = strpos($c, '<?php'); $c = $pos === false ? $c : substr_replace($c, "<?php\n" . implode("\n", $missing) . "\n", $pos, 5); }
        try {
            token_get_all($c, TOKEN_PARSE);
            if (!is_file($file . $BAK)) copy($file, $file . $BAK);
            file_put_contents($file, $c); if (function_exists('opcache_invalidate')) @opcache_invalidate($file, true);
            header('Location: ?key=' . urlencode(KEY) . '&saved=1'); exit;
        } catch (Throwable $ex) { $err[] = 'Nothing changed — ' . $ex->getMessage(); }
    }
}
if ($file && $mode === 'restore' && is_file($file . $BAK)) { copy($file . $BAK, $file); @unlink($file . $BAK); if (function_exists('opcache_invalidate')) @opcache_invalidate($file, true); $out[] = 'Previous SMTP settings restored.'; }
if (isset($_GET['saved'])) $out[] = 'Saved. Now send a test email below.';

/* setările curente (citite proaspăt din fișier) + test */
$cur = [];
if ($file) { $src = (string)file_get_contents($file); foreach ($NAMES as $n) if (preg_match('/define\(\s*[\'"]' . $n . '[\'"]\s*,\s*(.+?)\s*\)\s*;/', $src, $m)) $cur[$n] = $n === 'SMTP_PASS' ? '•••• set' : trim($m[1], " '\""); }
$test = null; $testLog = '';
if ($file && $mode === 'test') {
    ob_start(); foreach (['config.php', 'api/_api_inc.php', 'core/smtp_mailer.php'] as $f) if (is_file("$R/$f")) { try { require_once "$R/$f"; } catch (Throwable $ex) {} } ob_end_clean();
    if (!headers_sent()) { header_remove('Content-Type'); header('Content-Type: text/html; charset=utf-8'); }
    $to = trim((string)$_POST['to']);
    $tmp = sys_get_temp_dir() . '/smtpset-' . bin2hex(random_bytes(4)) . '.log'; $old = ini_get('error_log'); ini_set('error_log', $tmp); ini_set('log_errors', '1');
    try {
        if (!filter_var($to, FILTER_VALIDATE_EMAIL)) throw new RuntimeException('Invalid address');
        if (!function_exists('smtp_send')) throw new RuntimeException('smtp_send() not found');
        $html = '<p>Test from ' . e($_SERVER['HTTP_HOST'] ?? '') . ' at ' . date('Y-m-d H:i:s') . ' via ' . e(defined('SMTP_USER') ? SMTP_USER : '') . '. Enquiry notifications to this address work.</p>';
        $test = (bool)smtp_send($to, 'Test — enquiry notifications', strip_tags($html), $to, 'Mail test', $html);
    } catch (Throwable $ex) { $test = false; $testLog .= $ex->getMessage() . "\n"; }
    ini_set('error_log', (string)$old); if (is_file($tmp)) { $testLog .= (string)file_get_contents($tmp); @unlink($tmp); }
}
if (!headers_sent()) header('Content-Type: text/html; charset=utf-8');
?><!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>SMTP</title>
<style>body{font:15px/1.55 system-ui,-apple-system,Segoe UI,sans-serif;background:#f4f6f9;color:#0f1b2d;margin:0}.w{max-width:640px;margin:28px auto;padding:0 16px}
.c{background:#fff;border:1px solid #dce2ea;border-radius:10px;padding:18px 20px;margin:0 0 14px}h2{font-size:17px;margin:0 0 10px}.ok{color:#15803d}.bad{color:#b42318}.m{color:#56657a;font-size:13.5px}
label{display:block;font-size:13px;font-weight:600;margin:10px 0 4px}input{width:100%;box-sizing:border-box;padding:9px 10px;border:1px solid #cbd3dd;border-radius:7px;font-size:15px}
.btn{background:#1d5fd1;color:#fff;border:0;border-radius:7px;padding:10px 16px;font-weight:700;cursor:pointer;margin-top:14px}td{padding:4px 10px 4px 0}</style></head><body><div class="w">
<h1 style="font-size:22px">SMTP for notifications</h1>
<?php foreach ($out as $m) echo '<p class="ok">&#10003; ' . e($m) . '</p>'; foreach ($err as $m) echo '<p class="bad">' . e($m) . '</p>'; ?>
<?php if (!$file): ?><div class="c bad">Could not find where SMTP_HOST is defined (config.php / core/smtp_mailer.php / api/_api_inc.php).</div><?php else: ?>
<div class="c"><h2>Current (<?= e(str_replace($R . '/', '', $file)) ?>)</h2><table><?php foreach ($NAMES as $n) echo '<tr><td><code>' . $n . '</code></td><td>' . e($cur[$n] ?? '—') . '</td></tr>'; ?></table></div>
<div class="c"><h2>New account</h2>
<form method="post" autocomplete="off"><input type="hidden" name="mode" value="save">
<label>Outgoing server</label><input name="host" value="mail.admingrandfather.com">
<label>SMTP port (SSL/TLS)</label><input name="port" value="465" inputmode="numeric">
<label>Username</label><input name="user" value="noreply@admingrandfather.com">
<label>Password (of this email account)</label><input name="pass" type="password" autocomplete="new-password">
<label>From address</label><input name="from" value="noreply@admingrandfather.com">
<button class="btn">Save</button></form></div>
<div class="c"><h2>Send a test</h2>
<?php if ($test !== null): ?><p><?= $test ? '<b class="ok">Accepted by the server.</b> Check Inbox and Spam.' : '<b class="bad">Not sent.</b>' ?></p><?php if (trim($testLog) !== ''): ?><pre style="background:#0f172a;color:#e2e8f0;padding:10px;border-radius:8px;font-size:12px;white-space:pre-wrap"><?= e(mb_substr($testLog, 0, 3000)) ?></pre><?php endif; endif; ?>
<form method="post"><input type="hidden" name="mode" value="test"><input name="to" value="office@auto-salesconsigment.com"><button class="btn">Send test</button></form></div>
<?php if (is_file($file . $BAK)): ?><form method="post" onsubmit="return confirm('Put back the previous SMTP settings?')"><input type="hidden" name="mode" value="restore"><button>Restore previous settings</button></form><?php endif; ?>
<?php endif; ?>
<p class="bad"><b>Delete smtp-set.php after use.</b></p></div></body></html>
