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

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

error_log("Starting verification process"); // Debug log

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

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

error_log("Received code: " . $code); // Debug log
error_log("User ID: " . $_SESSION['user_id']); // Debug log

$db = new Database();
$twoFA = new TwoFactorAuth($db);

try {
    // Get the secret key first
    $conn = $db->connect();
    $stmt = $conn->prepare("SELECT secret_key FROM two_factor_auth WHERE user_id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $secret = $stmt->fetchColumn();
    
    error_log("Secret key from DB: " . $secret); // Debug log

    $result = $twoFA->enableTwoFactor($_SESSION['user_id'], $code);
    error_log("Enable result: " . json_encode($result)); // Debug log
    
    if ($result['success']) {
        $backupCodes = $twoFA->generateBackupCodes();
        $result['backupCodes'] = $backupCodes;
    }
    
    echo json_encode($result);
} catch (Exception $e) {
    error_log("Error during verification: " . $e->getMessage()); // Debug log
    echo json_encode(['success' => false, 'error' => 'Verification error']);
}