<?php
// Admin-only: Send Test Email using SMTP settings from settings table
if (!defined('TONSUI_LOADED')) { define('TONSUI_LOADED', true); }
require_once __DIR__ . '/session_init.php';
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/auth.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$autoload = __DIR__ . '/vendor/autoload.php';
if (file_exists($autoload)) { require $autoload; }

header('Content-Type: application/json');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if (!empty($origin)) { header('Access-Control-Allow-Origin: ' . $origin); }
else if (!empty($_SERVER['HTTP_HOST'])) { $scheme = $_SERVER['REQUEST_SCHEME'] ?? 'https'; header('Access-Control-Allow-Origin: ' . $scheme . '://' . $_SERVER['HTTP_HOST']); }
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }

requireAdmin(true);

try {
  if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    exit;
  }
  $input = json_decode(file_get_contents('php://input'), true) ?: [];
  $to = trim($input['to'] ?? '');

  // Load SMTP settings from settings table
  $settings = [];
  $st = $pdo->query("SELECT setting_key, setting_value FROM settings");
  while ($row = $st->fetch(PDO::FETCH_ASSOC)) { $settings[$row['setting_key']] = $row['setting_value']; }
  $enabled = ($settings['smtp_enabled'] ?? '0') === '1';
  if (!$enabled) { echo json_encode(['success'=>false,'error'=>'SMTP is disabled in settings']); exit; }

  $host = (string)($settings['smtp_host'] ?? '');
  $port = (int)($settings['smtp_port'] ?? 587);
  $user = (string)($settings['smtp_username'] ?? '');
  $pass = (string)($settings['smtp_password'] ?? '');
  $enc  = (string)($settings['smtp_encryption'] ?? 'tls');
  $from = (string)($settings['smtp_from_email'] ?? 'noreply@localhost');
  $fromName = (string)($settings['smtp_from_name'] ?? 'First De France Bank');
  if ($to === '') { $to = (string)($settings['contact_email'] ?? $from); }

  if (empty($host)) { echo json_encode(['success'=>false,'error'=>'SMTP host not configured']); exit; }
  if (!filter_var($to, FILTER_VALIDATE_EMAIL)) { echo json_encode(['success'=>false,'error'=>'Invalid recipient email']); exit; }

  $mail = new PHPMailer(true);
  try {
    $mail->isSMTP();
    $mail->Host = $host;
    $mail->SMTPAuth = true;
    $mail->Username = $user;
    $mail->Password = $pass;
    if (in_array(strtolower($enc), ['tls','ssl'])) { $mail->SMTPSecure = $enc; }
    $mail->Port = $port;
    $mail->CharSet = 'UTF-8';
    $mail->setFrom($from, $fromName);
    $mail->addAddress($to);
    $mail->isHTML(true);
    $mail->Subject = 'Test Email from First De France Admin';
    $mail->Body = '<p>This is a test email confirming your SMTP configuration is working.</p>';
    $mail->AltBody = 'This is a test email confirming your SMTP configuration is working.';
    $mail->send();
    echo json_encode(['success'=>true,'message'=>'Test email sent to ' . $to]);
  } catch (Exception $e) {
    echo json_encode(['success'=>false,'error'=>'Mailer error: ' . $mail->ErrorInfo]);
  }
} catch (Throwable $e) {
  http_response_code(500);
  echo json_encode(['success'=>false,'error'=>$e->getMessage()]);
}
