<?php
session_start();
require_once 'db.php';
require_once 'TwoFactorAuth.php';

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

try {
    $db = new Database();
    $conn = $db->connect();
    
    $stmt = $conn->prepare("SELECT email FROM utilisateurs WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $email = $stmt->fetchColumn();
    
    if (!$email) {
        echo json_encode(['success' => false, 'error' => 'User not found']);
        exit;
    }

    $twoFA = new TwoFactorAuth($db);
    $result = $twoFA->setupTwoFactor($_SESSION['user_id'], $email);
    
    echo json_encode($result);
} catch (Exception $e) {
    error_log("2FA Setup Error: " . $e->getMessage());
    echo json_encode(['success' => false, 'error' => 'Setup failed']);
}