<?php

require_once __DIR__ . "/../includes/db.php";
require_once __DIR__ . "/../includes/functions.php";
require_once __DIR__ . "/../includes/mailer.php";
require_once __DIR__ . "/../includes/session.php";

/**
 * =========================================
 * DEMOBANK OTP GENERATOR
 * =========================================
 * - Generates 6-digit OTP
 * - Stores in database
 * - Sends via email
 */

// Ensure user is logged in
$user_id = $_SESSION['user_id'] ?? null;

if (!$user_id) {
    die("Unauthorized access");
}

// Get user details
$conn = db();

$stmt = $conn->prepare("SELECT email, full_name FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();

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

$email = $user['email'];
$name  = $user['full_name'];

// Generate OTP (6 digits)
$otp = random_int(100000, 999999);

// OTP expiry (5 minutes)
$expires_at = date("Y-m-d H:i:s", strtotime("+5 minutes"));

/**
 * Save OTP to database
 * Table required: otp_codes
 */
$stmt = $conn->prepare("
    INSERT INTO otp_codes (user_id, otp_code, expires_at, created_at)
    VALUES (?, ?, ?, NOW())
");
$stmt->bind_param("iss", $user_id, $otp, $expires_at);
$stmt->execute();

/**
 * Send OTP email
 */
$subject = "Your DemoBank OTP Code";

$message = "
<html>
<body>
    <h2>DemoBank Security OTP</h2>

    <p>Hello <b>$name</b>,</p>

    <p>Your One-Time Password (OTP) is:</p>

    <h1 style='letter-spacing:5px;'>$otp</h1>

    <p>This code will expire in <b>5 minutes</b>.</p>

    <p>If you did not request this, please ignore this email.</p>

    <br>
    <p>DemoBank Security Team</p>
</body>
</html>
";

sendEmail($email, $subject, $message);

/**
 * Response
 */
echo json_encode([
    "status" => "success",
    "message" => "OTP sent to email"
]);