<?php
include 'config.php';

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode([
        "account" => false
    ]);
    exit;
}

$telegram_id = trim($_POST['telegram_id'] ?? '');
$extract_json = trim($_POST['extract_json'] ?? '');

if (empty($telegram_id) || empty($extract_json)) {
    echo json_encode([
        "account" => false
    ]);
    exit;
}

$result = $conn->query("SELECT id, extra_json FROM users");

while ($row = $result->fetch_assoc()) {

    $json = json_decode($row['extra_json'], true);

    if (
        isset($json['telegram_id']) &&
        $json['telegram_id'] == $telegram_id
    ) {

        $id = (int)$row['id'];

        $stmt = $conn->prepare(
            "UPDATE users SET extra_json=? WHERE id=?"
        );
        $stmt->bind_param("si", $extract_json, $id);
        $stmt->execute();

        echo json_encode([
            "account" => true
        ]);
        exit;
    }
}

echo json_encode([
    "account" => false
]);
?>