<?php
session_start();

header("Access-Control-Allow-Origin: https://enerliths.com");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Content-Type: application/json");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}
require "../config/db.php";
require "../vendor/autoload.php";

use PragmaRX\Google2FA\Google2FA;

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

$data = json_decode(file_get_contents("php://input"),true);

$secret = $data["secret"];
$code = $data["code"];

$user_id = $_SESSION["user_id"];

$google2fa = new Google2FA();

$valid = $google2fa->verifyKey($secret,$code);

if(!$valid){
    echo json_encode([
        "status"=>"error",
        "message"=>"Invalid authentication code"
    ]);
    exit;
}

/* SAVE 2FA */

$stmt = $conn->prepare("
INSERT INTO user_2fa (user_id,secret,enabled)
VALUES (?,?,1)
ON DUPLICATE KEY UPDATE secret=?,enabled=1
");

$stmt->bind_param("iss",$user_id,$secret,$secret);
$stmt->execute();

echo json_encode([
    "status"=>"success",
    "message"=>"Two-factor authentication enabled"
]);