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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_qr'])) {
    $user_id = $_SESSION['user_id'];

    // Fetch QR code path
    $stmt = $conn->prepare("SELECT qr_code_path FROM authentications WHERE user_id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();
    $qrCodePath = $row['qr_code_path'] ?? null;
    $stmt->close();

    // Delete the file if it exists
    if ($qrCodePath && file_exists($qrCodePath)) {
        unlink($qrCodePath);
    }

    // Remove QR code path from the database
    $stmt = $conn->prepare("UPDATE authentications SET qr_code_path = NULL WHERE user_id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $stmt->close();
    $conn->close();

    $_SESSION['flash_message'] = "✅ QR Code deleted successfully!";
    header("Location: dashboard.php");
    exit;
} else {
    $_SESSION['flash_message'] = "❌ Invalid request.";
    header("Location: dashboard.php");
    exit;
}
