<?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';

try {
    $pdo = new PDO("mysql:host=localhost;dbname=proceessor_securebank", "proceessor_user", "Fakepassword2$.");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Throwable $e) {
    die("Database connection failed: " . $e->getMessage());
}

// Check POST input
if(!isset($_POST['account_number'], $_POST['password'])){
    die("Account number and password are required.");
}

$account_number = trim($_POST['account_number']);
$password = trim($_POST['password']);

// Look up user
$stmt = $pdo->prepare("SELECT id, first_name, middle_name, last_name, email, password_hash FROM users WHERE account_number = :account_number LIMIT 1");
$stmt->execute(['account_number' => $account_number]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if(!$user || !password_verify($password, $user['password_hash'])){
    die("Invalid account number or password.");
}

// Generate OTP
$otp = rand(100000, 999999);
$_SESSION['otp'] = $otp;
$_SESSION['otp_expiry'] = time() + 300; // 5 minutes
$_SESSION['login_user_id'] = $user['id'];

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

// Send OTP via PHPMailer
$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'], 'Chase Bank');
    $mail->addAddress($email);

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

    $mail->send();

    // Redirect to OTP page
    header("Location: ../auth/otp.php");
    exit;

} catch (Exception $e) {
    die("Mailer Error: " . $mail->ErrorInfo);
}