<?php
include 'db.php';

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

$is_enabled = isset($data['enabled']) && $data['enabled'] ? 1 : 0;
$api_url = $data['apiUrl'] ?? '';
$pos_id  = $data['posId'] ?? '';
$usin    = $data['usin'] ?? '';

// Check if config already exists
$result = $conn->query("SELECT id FROM fbr_config LIMIT 1");

if ($result && $result->num_rows > 0) {
    $stmt = $conn->prepare("UPDATE fbr_config SET is_enabled = ?, api_url = ?, pos_id = ?, usin = ? WHERE id = 1");
    $stmt->bind_param("isis", $is_enabled, $api_url, $pos_id, $usin);
} else {
    $stmt = $conn->prepare("INSERT INTO fbr_config (is_enabled, api_url, pos_id, usin) VALUES (?, ?, ?, ?)");
    $stmt->bind_param("isis", $is_enabled, $api_url, $pos_id, $usin);
}

if ($stmt->execute()) {
    echo json_encode(['success' => true]);
} else {
    echo json_encode(['success' => false, 'error' => $stmt->error]);
}

$stmt->close();
