<?php
require ('includes/PHPMailer.php');
require ('includes/SMTP.php');
require ('includes/Exception.php');    

// Defining namespaces
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;

require_once("scripts/functions.php");

// Initialize PHPMailer
$mail = new PHPMailer();
$mail->isSMTP();  // Uncomment if SMTP is required
$mail->Host = $smtp_host;
$mail->SMTPAuth = true;
$mail->CharSet = "UTF-8";
$mail->Username = $smtp_username; 
$mail->Password = $smtp_password;
$mail->SMTPSecure = $smtp_auth;
$mail->Port = $smtp_port;

// Gather user information
$ipa = $_SERVER['REMOTE_ADDR'];
$ua = getBrowser();
$browser = $ua['name'] . " on " . $ua['platform'];

// Generate authentication code and URL
$auth_code = randomNumber(4);  // Ensure this function returns a valid 4-digit number
$_SESSION['auth_code'] = $auth_code;
$url = $_SERVER['HTTP_HOST'];
$link = randomString(56);
$addr = "/account-authentication.php?source=$link";
$auth_url = "http://$url$addr"; // Ensure it is a proper URL

// Debugging: Output the generated authentication code
// echo "Generated Authentication Code: " . $auth_code; // Check output to ensure code is generated

// Set up email
$mail->setFrom($smtp_username, $display_name);
$mail->addReplyTo($smtp_username, $display_name);
$mail->addAddress($_SESSION['email']);  // Send email to user session email
$mail->Subject = "Device Authentication Required";
$mail->isHTML(true);

// Email body content with embedded authentication code
$mail->Body = '
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Device Authentication</title>
  <style>
    /* Add your custom styles here */
  </style>
</head>
<body>
  <table>
    <tr>
      <td>
        <h1>New Device Authentication</h1>
        <p>You are attempting to access your account from a new device or location. Please authenticate:</p>
        <p><strong>Location:</strong> ' . getLocation() . '</p>
        <p><strong>IP Address:</strong> ' . $ipa . '</p>
        <p><strong>Browser:</strong> ' . $browser . '</p>
        <h2>Your Authentication Code: ' . $auth_code . '</h2> <!-- Make sure this line displays the code -->
        <a href="' . $auth_url . '">Authorize this device</a>
        <p>If you did not request this, please ignore this email or contact support immediately.</p>
      </td>
    </tr>
  </table>
</body>
</html>';

// Send the email
if (!$mail->Send()) {  
  $_SESSION['verifiedTfa'] = hash('sha256', 'verified');
  echo "<script> window.location.href='personal-banking/dashboard?viewSource=".$_SESSION['loggedToken']."';</script>";
} else {
  echo "<script> window.location.href='secure/authenticator.php?viewSource=".$_SESSION['loggedToken']."';</script>";
}
?>
