<?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;
}

$data = json_decode(file_get_contents('php://input'), true);
$code = $data['code'] ?? '';

if (!$code || strlen($code) !== 6 || !ctype_digit($code)) {
    echo json_encode(['success' => false, 'error' => 'Invalid code']);
    exit;
}

try {
    $db = new Database();
    $twoFA = new TwoFactorAuth($db);
    
    $result = $twoFA->enableTwoFactor($_SESSION['user_id'], $code);
    
    if ($result['success']) {
        $backupCodes = $twoFA->getBackupCodes($_SESSION['user_id']);
        $result['backupCodes'] = $backupCodes;
    }
    
    echo json_encode($result);
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'error' => 'Verification failed'
    ]);
}