<?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'] ?? '';
$token      = $data['token'] ?? '';
$mode       = $data['mode'] ?? 'sandbox';

// Check existence
$result = $conn->query("SELECT id FROM fbr_digital LIMIT 1");

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

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

$stmt->close();
