<?php
/* ============================================================================
 *  test_email.php  —  ADMIN-ONLY SMTP diagnostic.
 *  Open:  /seven-credit-system/admin/test_email.php?to=you@example.com
 *  Shows the live SMTP conversation so we can see exactly where email fails.
 *  Delete this file once email is working.
 * ==========================================================================*/
session_start();
require_once '../config/database.php';
require_once '../config/password_reset.php';

if (!isset($_SESSION['user_id']) || ($_SESSION['role'] ?? '') !== 'admin') {
    http_response_code(403);
    die('Admin only. Log in as an administrator.');
}
header('Content-Type: text/plain; charset=utf-8');

$cfg = reset_cfg();
$to  = trim($_GET['to'] ?? $cfg['smtp_user']);

echo "=== Email (SMTP) diagnostic ===\n";
echo "Host: {$cfg['smtp_host']}:{$cfg['smtp_port']}  secure={$cfg['smtp_secure']}\n";
echo "User: {$cfg['smtp_user']}\n";
echo "From: {$cfg['mail_from']}   ->   To: {$to}\n";
echo "smtp_pass set? " . (($cfg['smtp_pass'] && strpos($cfg['smtp_pass'], 'PUT_THE_') !== 0) ? 'yes' : 'NO — still the placeholder!') . "\n\n";

$secure = strtolower((string) $cfg['smtp_secure']);
$remote = ($secure === 'ssl' ? 'ssl://' : '') . $cfg['smtp_host'] . ':' . (int) $cfg['smtp_port'];
$ctx = stream_context_create(['ssl' => ['verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true]]);
$fp = @stream_socket_client($remote, $errno, $errstr, 20, STREAM_CLIENT_CONNECT, $ctx);
if (!$fp) { echo "CONNECT FAILED: [$errno] $errstr\nTry smtp_host 'mail.7d-lao.com', or port 587 with secure 'tls'.\n"; exit; }
stream_set_timeout($fp, 20);

function rd($fp){ $d=''; while(($l=fgets($fp,515))!==false){ $d.=$l; if(strlen($l)>=4 && $l[3]===' ') break; } return rtrim($d); }
function cm($fp,$c,$hide=false){ fwrite($fp,$c."\r\n"); $r=rd($fp); echo ($hide?'> [hidden]':'> '.$c)."\n< ".$r."\n"; return $r; }

echo "< " . rd($fp) . "\n";
$h = $_SERVER['SERVER_NAME'] ?? 'localhost';
cm($fp, 'EHLO ' . $h);
if ($secure === 'tls') { cm($fp, 'STARTTLS'); @stream_socket_enable_crypto($fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT); cm($fp, 'EHLO ' . $h); }
cm($fp, 'AUTH LOGIN');
cm($fp, base64_encode($cfg['smtp_user']), true);
$auth = cm($fp, base64_encode($cfg['smtp_pass']), true);
if (strpos($auth, '235') !== 0) { echo "\n>>> AUTH FAILED. Check smtp_user and smtp_pass (the mailbox password).\n"; cm($fp, 'QUIT'); fclose($fp); exit; }

cm($fp, 'MAIL FROM:<' . $cfg['mail_from'] . '>');
cm($fp, 'RCPT TO:<' . $to . '>');
cm($fp, 'DATA');
$msg  = "Subject: Seven Digital SMTP test\r\n";
$msg .= "From: {$cfg['mail_from_name']} <{$cfg['mail_from']}>\r\n";
$msg .= "To: <{$to}>\r\n";
$msg .= "Content-Type: text/plain; charset=UTF-8\r\n\r\n";
$msg .= "This is a test email from the Seven Digital password-reset SMTP setup.\r\n.\r\n";
fwrite($fp, $msg);
echo "< " . rd($fp) . "\n";
cm($fp, 'QUIT');
fclose($fp);

echo "\n>>> If AUTH shows 235 and DATA shows 250, SMTP works. If the message still\n";
echo "    doesn't arrive in Gmail, it's a deliverability issue (SPF/DKIM/spam) —\n";
echo "    set up Email Deliverability in cPanel for 7d-lao.com.\n";
