<?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 && strlen($code) !== 8)) {
    echo json_encode(['success' => false, 'error' => 'Invalid code']);
    exit;
}

try {
    $db = new Database();
    $twoFA = new TwoFactorAuth($db);
    
    $verifyResult = $twoFA->verifyCode($_SESSION['user_id'], $code);
    if (!$verifyResult['success']) {
        echo json_encode($verifyResult);
        exit;
    }

    $stmt = $db->connect()->prepare("
        UPDATE two_factor_auth 
        SET is_enabled = FALSE, 
            attempt_count = 0, 
            last_attempt = NULL 
        WHERE user_id = ?
    ");
    $stmt->execute([$_SESSION['user_id']]);
    
    echo json_encode(['success' => true]);
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'error' => 'Disable failed'
    ]);
}