<?php
session_start();
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require '../phpmailer/src/Exception.php';
require '../phpmailer/src/PHPMailer.php';
require '../phpmailer/src/SMTP.php';

$config = include __DIR__ . '/../includes/email_config.php';

if(!isset($_SESSION['login_user_id'])){
    header("Location: ../login.php");
    exit;
}

// Fetch user email
$pdo = new PDO("mysql:host=localhost;dbname=proceessor_securebank", "proceessor_user", "Fakepassword2$.");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare("SELECT first_name, middle_name, last_name, email FROM users WHERE id = :id LIMIT 1");
$stmt->execute(['id'=>$_SESSION['login_user_id']]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if(!$user){
    die("User not found.");
}

// Generate new OTP
$otp = rand(100000,999999);
$_SESSION['otp'] = $otp;
$_SESSION['otp_expiry'] = time() + 300; // 5 mins

$full_name = trim($user['first_name'].' '.$user['middle_name'].' '.$user['last_name']);
$email = $user['email'];

// Send email
$mail = new PHPMailer(true);
try {
    $mail->isSMTP();
    $mail->Host = $config['host'];
    $mail->SMTPAuth = true;
    $mail->Username = $config['username'];
    $mail->Password = $config['password'];
    $mail->SMTPSecure = $config['secure'];
    $mail->Port = $config['port'];

    $mail->setFrom($config['username'], 'Your Website Name');
    $mail->addAddress($email);

    $mail->isHTML(true);
    $mail->Subject = 'Your OTP Code';
    $mail->Body = "<h2>Hello $full_name,</h2><p>Your new OTP is <b>$otp</b>. It expires in 5 minutes.</p>";
    $mail->AltBody = "Hello $full_name, Your OTP is: $otp (Expires in 5 minutes)";

    $mail->send();

    header("Location: otp.php?resent=1");
    exit;

} catch (Exception $e){
   