<?php
ini_set('display_errors', 0);

require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/mailer.php';
require_once __DIR__ . '/../includes/functions.php';

if (session_status() === PHP_SESSION_NONE) session_start();

$user_id = $_SESSION['user_id'] ?? null;
if (!$user_id) {
    header("Location: /auth/login.php");
    exit;
}

$conn = db();

// ==========================
// GET TRANSFER
// ==========================
$transfer_id = intval($_GET['transfer_id'] ?? 0);

$stmt = $conn->prepare("
    SELECT t.*, u.email, u.first_name, a.currency
    FROM transfers t
    JOIN users u ON t.user_id = u.id
    LEFT JOIN accounts a ON a.user_id = u.id
    WHERE t.id = ? AND t.user_id = ?
    LIMIT 1
");

$stmt->bind_param("ii", $transfer_id, $user_id);
$stmt->execute();
$transfer = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$transfer) {
    header("Location: /user/dashboard.php");
    exit;
}

// ==========================
// CURRENCY SYMBOL
// ==========================
$symbols = [
    'USD'=>'$','EUR'=>'€','GBP'=>'£','JPY'=>'¥','CNY'=>'¥',
    'NGN'=>'₦','GHS'=>'₵','INR'=>'₹','CAD'=>'C$','AUD'=>'A$'
];

$symbol = $symbols[$transfer['currency']] ?? '$';

// ==========================
// GENERATE OTP (ON FIRST LOAD)
// ==========================
if (!isset($_SESSION['otp_'.$transfer_id])) {

    $otp = rand(100000, 999999);
    $_SESSION['otp_'.$transfer_id] = $otp;

    // EMAIL
    $amountFormatted = $symbol . number_format($transfer['total'], 2);

    $subject = "DemoBank OTP Verification";

    $body = "
Hello {$transfer['first_name']},

Your OTP for transfer verification is:

{$otp}

Transfer Amount: {$amountFormatted}

Do not share this code with anyone.
";

    try {
        sendMail($transfer['email'], $subject, $body);
    } catch (Exception $e) {}
}

// ==========================
// HANDLE OTP SUBMISSION
// ==========================
$error = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $entered_otp = trim($_POST['otp'] ?? '');
    $session_otp = $_SESSION['otp_'.$transfer_id] ?? '';

    if ($entered_otp == $session_otp) {

        // ✅ Mark as OTP verified
        $stmt = $conn->prepare("
            UPDATE transfers 
            SET otp_verified = 1 
            WHERE id = ? AND user_id = ?
        ");
        $stmt->bind_param("ii", $transfer_id, $user_id);
        $stmt->execute();
        $stmt->close();

        // Remove OTP
        unset($_SESSION['otp_'.$transfer_id]);

        // 👉 NEXT STEP (token engine)
        header("Location: /transfer/token.php?transfer_id=".$transfer_id);
        exit;

    } else {
        $error = "Invalid OTP. Try again.";
    }
}

// ==========================
// UI
// ==========================
ob_start();
?>

<h2>🔐 OTP Verification</h2>

<p>We sent a verification code to your email.</p>

<p><strong>Amount:</strong> <?= $symbol . number_format($transfer['total'],2) ?></p>

<?php if ($error): ?>
    <div style="color:red;"><?= htmlspecialchars($error) ?></div>
<?php endif; ?>

<form method="POST">
    <label>Enter OTP</label>
    <input type="text" name="otp" required maxlength="6" style="padding:10px;font-size:18px;letter-spacing:5px;">

    <br><br>

    <button type="submit" style="padding:10px 20px;background:#1a73e8;color:#fff;border:none;border-radius:5px;">
        Verify OTP
    </button>
</form>

<?php
$content = ob_get_clean();
renderLayout("OTP Verification", $content, $conn);