<?php
session_start();
include 'db.php';

if (!isset($_SESSION['user_id']) || !isset($_POST['secret'])) {
    $_SESSION['flash_message'] = "❌ Invalid request.";
    header("Location: scan_qr.php");
    exit();
}

$user_id = $_SESSION['user_id'];
$secret_raw = trim($_POST['secret']);
$app_name = trim($_POST['app_name']);

// Example scanned QR content:
//$otpAuthUri = "otpauth://totp/MyAuthenticatorApp?secret=ZEOQ3OPTWEJEOJ4T&issuer=MyCompany";

$otpAuthUri = $secret_raw;

// Extract the secret
preg_match('/secret=([A-Z2-7]+)&?/', $otpAuthUri, $matches);
$secret = $matches[1] ?? null;

if (!$secret) {
    die("❌ Error: Unable to extract secret from QR code.");
}

// Store only the secret
$stmt = $conn->prepare("INSERT INTO scanned_auths (user_id, app_name, secret) VALUES (?, ?, ?)");
$stmt->execute([$user_id, $app_name, $secret]);

/*
$stmt = $conn->prepare("INSERT INTO scanned_auths (user_id, app_name, secret) VALUES (?, ?, ?)");
$stmt->bind_param("iss", $user_id, $app_name, $secret);
$stmt->execute();
*/



//$stmt = $conn->prepare("INSERT INTO scanned_auths (user_id, secret) VALUES (?, ?)");
//$stmt->bind_param("is", $user_id, $secret);
$stmt->execute();
$stmt->close();
$conn->close();

$_SESSION['flash_message'] = "✅ QR Code scanned and saved!";
header("Location: dashboard.php");
exit();
