<?php
include_once 'db.php';

// Fetch saved FBR config
$config = [
    'is_enabled' => 0,
    'api_url' => 'http://localhost:8524/api/IMSFiscal/GetInvoiceNumberByModel',
    'pos_id' => '',
    'usin' => ''
];

$result = $conn->query("SELECT * FROM fbr_config LIMIT 1");
if ($result && $result->num_rows > 0) {
    $row = $result->fetch_assoc();
    $config = [
        'is_enabled' => $row['is_enabled'],
        'api_url' => $row['api_url'],
        'pos_id' => $row['pos_id'],
        'usin' => $row['usin']
    ];
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>FBR Settings</title>
</head>
<body>

<h2>FBR Configuration</h2>

<label>
    <input type="checkbox" id="enableFbr" <?= $config['is_enabled'] ? 'checked' : '' ?>>
    Enable FBR
</label>

<div id="fbrSettings" style="display: <?= $config['is_enabled'] ? 'block' : 'none' ?>;">
    <label>API URL:
        <input type="text" id="apiUrl" value="<?= htmlspecialchars($config['api_url']) ?>">
    </label><br>
    <label>POS ID:
        <input type="text" id="posId" value="<?= htmlspecialchars($config['pos_id']) ?>">
    </label><br>
    <label>USIN:
        <input type="text" id="usin" value="<?= htmlspecialchars($config['usin']) ?>">
    </label><br>
    <button onclick="saveFbrSettings()">Save</button>
</div>

<script>
document.getElementById('enableFbr').addEventListener('change', function () {
    document.getElementById('fbrSettings').style.display = this.checked ? 'block' : 'none';
});

function saveFbrSettings() {
    const settings = {
        enabled: document.getElementById('enableFbr').checked,
        apiUrl: document.getElementById('apiUrl').value,
        posId: document.getElementById('posId').value,
        usin: document.getElementById('usin').value
    };

    fetch('save_fbr_config.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(settings)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('FBR settings saved successfully.');
        } else {
            alert('Error: ' + data.error);
        }
    })
    .catch(err => alert('AJAX error: ' + err));
}
</script>

</body>
</html>
