<?php
define('TONSUI_LOADED', true);
if (!defined('TONSUI_ALLOW_GUEST')) { define('TONSUI_ALLOW_GUEST', true); }
require_once __DIR__ . '/session_init.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/includes/Mailer.php';
require_once __DIR__ . '/includes/Env.php';
require_once __DIR__ . '/email_helper.php';
header('Content-Type: application/json');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }
function out($ok, $msg = '', $data = []) { $r = ['success'=>$ok]; if ($msg!=='') $r['message']=$msg; foreach($data as $k=>$v){$r[$k]=$v;} echo json_encode($r); exit; }
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); header('Allow: POST'); out(false, 'Method not allowed'); }
$pending = $_SESSION['pending_login'] ?? null;
if (!$pending || !is_array($pending) || empty($pending['email'])) { http_response_code(400); out(false, 'No pending login found'); }
$now = time();
$last = isset($_SESSION['pending_login_last_sent']) ? (int)$_SESSION['pending_login_last_sent'] : 0;
$cooldown = 45;
$wait = $cooldown - ($now - $last);
if ($wait > 0) { http_response_code(429); out(false, 'Please wait before resending', ['retry_after' => $wait]); }
try { $otp = (string)random_int(100000, 999999); } catch (Exception $e) { $otp = (string)mt_rand(100000, 999999); }
$_SESSION['pending_login']['otp'] = $otp;
$_SESSION['pending_login']['expires'] = $now + 3600;
$_SESSION['pending_login_last_sent'] = $now;
$sent = false;
// Try centralized templated email first for branding consistency
try {
  $res = @sendEmail($pdo, $_SESSION['pending_login']['email'], 'loginOtp', [
    'user_name' => ($_SESSION['pending_login']['username'] ?? (explode('@', $_SESSION['pending_login']['email'])[0] ?? 'Customer')),
    'otp_code' => $otp
  ]);
  if (is_array($res) && !empty($res['success'])) { $sent = true; }
} catch (Exception $e) { $sent = false; }
// Prepare fallback content (used only if helper fails)
$subject = 'Your login verification code';
$html = '<p>Your one-time login code is:</p><h2 style="letter-spacing:2px;">' . htmlspecialchars($otp) . '</h2><p>This code expires in 60 minutes.</p>';
// Fallback to direct PHPMailer using env if helper didn't send
if (!$sent) {
  try {
    $envHost = TonEnv::get('MAILER_HOST', '');
    $envUser = TonEnv::get('MAILER_USERNAME', '');
    $envPass = TonEnv::get('MAILER_PASSWORD', '');
    $envPort = (int)TonEnv::get('MAILER_PORT', '587');
    $envFrom = TonEnv::get('MAILER_FROM', $envUser);
    $envFromName = TonEnv::get('MAILER_FROM_NAME', 'First De France Bank');
    $envEnc = strtolower((string)TonEnv::get('MAILER_ENCRYPTION', ''));
    if ($envHost && $envUser && $envPass) {
      $m = new PHPMailer\PHPMailer\PHPMailer(true);
      $m->isSMTP();
      $m->Host = $envHost;
      $m->SMTPAuth = true;
      $m->Username = $envUser;
      $m->Password = $envPass;
      if ($envEnc === 'ssl' || $envPort === 465) {
        $m->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS;
      } else {
        $m->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;
      }
      $m->Port = $envPort ?: 587;
      $m->setFrom($envFrom ?: $envUser, $envFromName);
      $m->addAddress($_SESSION['pending_login']['email']);
      $m->isHTML(true);
      $m->Subject = $subject;
      $m->Body = $html;
      $m->AltBody = strip_tags($html);
      $m->send();
      $sent = true;
    }
  } catch (Exception $e) { $sent = false; }
}
if (!$sent) {
  $cfg = getEmailConfig($pdo);
  if ($cfg && !empty($cfg['smtp']) && !empty($cfg['smtp']['enabled'])) {
    try {
      $smtp = $cfg['smtp'];
      $m = new PHPMailer\PHPMailer\PHPMailer(true);
      $m->isSMTP();
      $m->Host = $smtp['host'];
      $m->SMTPAuth = true;
      $m->Username = $smtp['username'];
      $m->Password = $smtp['password'];
      $m->SMTPSecure = $smtp['encryption'] === 'ssl' ? PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS : PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;
      $m->Port = $smtp['port'];
      $m->setFrom($smtp['fromEmail'], $smtp['fromName']);
      $m->addAddress($_SESSION['pending_login']['email']);
      $m->isHTML(true);
      $m->Subject = $subject;
      $m->Body = $html;
      $m->AltBody = strip_tags($html);
      $m->send();
      $sent = true;
    } catch (Exception $e) { $sent = false; }
  }
}
if (!$sent) { $fallback = new Mailer(); @$fallback->sendEmail($_SESSION['pending_login']['email'], $subject, $html, strip_tags($html)); }
out(true, 'Verification code resent', ['cooldown' => $cooldown]);
