<?php
/**
 * (c) ININOUT & PYXIS. All Rights Reserved.
 * Wszelkie modyfikacje tego pliku wymagaja zgloszenia oraz zgody autorow.
 * Any modifications to this file require notification and consent of the authors.
 */
/**
 * i-BOK 5 - Panel admina: Konfiguracja bramek SMS
 */

require_once __DIR__ . '/../inc/sms.php';

// Obsługa AJAX
if (isset($_GET['action'])) {
    header('Content-Type: application/json; charset=utf-8');
    $action = $_GET['action'];

    // GET config — zwraca config z wyczyszczonymi tokenami/hasłami
    if ($action === 'get_config') {
        $config = sms_load_config();

        // Maskuj tokeny/hasła
        if (!empty($config['smsapi']['token'])) {
            $config['smsapi']['token_set'] = true;
            $config['smsapi']['token'] = '';
        } else {
            $config['smsapi']['token_set'] = false;
        }

        if (!empty($config['serwersms']['password'])) {
            $config['serwersms']['password_set'] = true;
            $config['serwersms']['password'] = '';
        } else {
            $config['serwersms']['password_set'] = false;
        }

        if (!empty($config['smsplanet']['token'])) {
            $config['smsplanet']['token_set'] = true;
            $config['smsplanet']['token'] = '';
        } else {
            $config['smsplanet']['token_set'] = false;
        }

        echo json_encode(['success' => true, 'config' => $config]);
        exit;
    }

    // Blokada zapisu w trybie demo
    if (ibok_is_demo() && (strpos($action, 'save_') === 0)) {
        echo json_encode(['success' => false, 'error' => __('demo.save_blocked')]);
        exit;
    }

    // Zapisz ustawienia ogólne
    if ($action === 'save_general') {
        if (!csrf_validate()) {
            echo json_encode(['success' => false, 'error' => __('sms_admin.error_csrf')]);
            exit;
        }

        $config = sms_load_config();
        $config['active_gateway'] = $_POST['active_gateway'] ?? '';
        $config['test_mode'] = !empty($_POST['test_mode']);
        $config['default_prefix'] = trim($_POST['default_prefix'] ?? '48');

        if (sms_save_config($config)) {
            ibok_log("Konfiguracja SMS (ogólne) zapisana przez admina", 'info');
            echo json_encode(['success' => true, 'message' => __('sms_admin.saved_general')]);
        } else {
            echo json_encode(['success' => false, 'error' => __('sms_admin.error_save')]);
        }
        exit;
    }

    // Zapisz konfigurację bramki
    if (preg_match('/^save_(smsapi|serwersms|smsplanet)$/', $action, $m)) {
        if (!csrf_validate()) {
            echo json_encode(['success' => false, 'error' => __('sms_admin.error_csrf')]);
            exit;
        }

        $gw = $m[1];
        $config = sms_load_config();
        $oldGw = $config[$gw];

        if ($gw === 'smsapi') {
            $newToken = $_POST['token'] ?? '';
            $config['smsapi']['token'] = !empty($newToken) ? sms_encrypt($newToken) : $oldGw['token'];
            $config['smsapi']['sender'] = trim($_POST['sender'] ?? '');
        } elseif ($gw === 'serwersms') {
            $config['serwersms']['username'] = trim($_POST['username'] ?? '');
            $newPass = $_POST['password'] ?? '';
            $config['serwersms']['password'] = !empty($newPass) ? sms_encrypt($newPass) : $oldGw['password'];
            $config['serwersms']['sender'] = trim($_POST['sender'] ?? '');
        } elseif ($gw === 'smsplanet') {
            $newToken = $_POST['token'] ?? '';
            $config['smsplanet']['token'] = !empty($newToken) ? sms_encrypt($newToken) : $oldGw['token'];
            $config['smsplanet']['sender'] = trim($_POST['sender'] ?? '');
        }

        if (sms_save_config($config)) {
            ibok_log("Konfiguracja SMS ({$gw}) zapisana przez admina", 'info');
            echo json_encode(['success' => true, 'message' => __('sms_admin.saved')]);
        } else {
            echo json_encode(['success' => false, 'error' => __('sms_admin.error_save')]);
        }
        exit;
    }

    // Sprawdź saldo
    if ($action === 'check_balance') {
        if (!csrf_validate()) {
            echo json_encode(['success' => false, 'error' => __('sms_admin.error_csrf')]);
            exit;
        }

        $gateway = $_POST['gateway'] ?? '';
        if (!in_array($gateway, ['smsapi', 'serwersms', 'smsplanet'])) {
            echo json_encode(['success' => false, 'error' => 'Invalid gateway']);
            exit;
        }

        $result = sms_check_balance($gateway);
        echo json_encode($result);
        exit;
    }

    // Testowy SMS
    if ($action === 'test_send') {
        if (!csrf_validate()) {
            echo json_encode(['success' => false, 'error' => __('sms_admin.error_csrf')]);
            exit;
        }

        $phone = preg_replace('/[^0-9+]/', '', $_POST['phone'] ?? '');
        $message = trim($_POST['message'] ?? '');

        if (empty($phone)) {
            echo json_encode(['success' => false, 'error' => __('sms_admin.test_no_phone')]);
            exit;
        }
        if (empty($message)) {
            $message = __('sms_admin.test_message_default');
        }

        $result = sms_send($phone, $message);
        if ($result['success']) {
            $config = sms_load_config();
            if (!empty($config['test_mode'])) {
                $result['message'] = __('sms_admin.test_logged');
            }
            ibok_log("Testowy SMS wysłany na: {$phone}", 'info');
        }
        echo json_encode($result);
        exit;
    }

    echo json_encode(['success' => false, 'error' => 'Unknown action']);
    exit;
}
?>

<div class="fade-in">
    <h4 class="mb-4">
        <i class="bi bi-phone me-2"></i> <?= __('sms_admin.title') ?>
    </h4>

    <?= ibok_help_section('admin_sms', __('help.show_help'), __('help_admin.sms_section_content')) ?>

    <!-- Status -->
    <div id="smsStatus" class="mb-4"></div>

    <!-- Alerts -->
    <div id="smsAlert" class="d-none"></div>

    <div class="row g-4">
        <!-- Kolumna główna -->
        <div class="col-lg-8">
            <!-- Ustawienia ogólne -->
            <div class="card mb-4">
                <div class="card-header">
                    <i class="bi bi-sliders me-1"></i> <?= __('sms_admin.general_title') ?>
                </div>
                <div class="card-body">
                    <form id="generalForm">
                        <?= csrf_field() ?>

                        <div class="row mb-3">
                            <div class="col-md-5">
                                <label for="activeGateway" class="form-label"><?= __('sms_admin.active_gateway') ?></label>
                                <select class="form-select" id="activeGateway" name="active_gateway">
                                    <option value=""><?= __('sms_admin.active_gateway_none') ?></option>
                                    <option value="smsapi">SMSAPI.pl</option>
                                    <option value="serwersms">SerwerSMS.pl</option>
                                    <option value="smsplanet">SMSPlanet.pl</option>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label for="defaultPrefix" class="form-label"><?= __('sms_admin.default_prefix') ?></label>
                                <input type="text" class="form-control" id="defaultPrefix" name="default_prefix" value="48" maxlength="5">
                            </div>
                            <div class="col-md-4 d-flex align-items-end">
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" id="testMode" name="test_mode">
                                    <label class="form-check-label" for="testMode"><?= __('sms_admin.test_mode') ?></label>
                                </div>
                            </div>
                        </div>
                        <small class="text-muted d-block mb-3">
                            <i class="bi bi-info-circle me-1"></i> <?= __('sms_admin.test_mode_desc') ?>
                        </small>

                        <button type="submit" class="btn btn-primary" id="btnSaveGeneral">
                            <i class="bi bi-check-lg me-1"></i> <?= __('sms_admin.btn_save_general') ?>
                        </button>
                    </form>
                </div>
            </div>

            <!-- Zakładki bramek -->
            <div class="card">
                <div class="card-header p-0">
                    <ul class="nav nav-tabs card-header-tabs" id="gwTabs" role="tablist">
                        <li class="nav-item" role="presentation">
                            <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#tab-smsapi" type="button" role="tab">
                                <i class="bi bi-broadcast me-1"></i> <?= __('sms_admin.tab_smsapi') ?>
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-serwersms" type="button" role="tab">
                                <i class="bi bi-broadcast me-1"></i> <?= __('sms_admin.tab_serwersms') ?>
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-smsplanet" type="button" role="tab">
                                <i class="bi bi-broadcast me-1"></i> <?= __('sms_admin.tab_smsplanet') ?>
                            </button>
                        </li>
                    </ul>
                </div>
                <div class="card-body">
                    <div class="tab-content">
                        <!-- SMSAPI.pl -->
                        <div class="tab-pane fade show active" id="tab-smsapi" role="tabpanel">
                            <form id="form-smsapi" data-gateway="smsapi">
                                <?= csrf_field() ?>
                                <div class="mb-3">
                                    <label for="smsapi_token" class="form-label"><?= __('sms_admin.token') ?></label>
                                    <div class="input-group">
                                        <input type="password" class="form-control" id="smsapi_token" name="token"
                                               placeholder="&#8226;&#8226;&#8226;&#8226;&#8226;&#8226;&#8226;&#8226;" autocomplete="off">
                                        <button class="btn btn-outline-secondary btn-toggle-pass" type="button" data-target="smsapi_token">
                                            <i class="bi bi-eye"></i>
                                        </button>
                                    </div>
                                    <small class="text-muted sms-secret-hint" id="smsapi_token_hint" style="display:none;"></small>
                                </div>
                                <div class="mb-3">
                                    <label for="smsapi_sender" class="form-label"><?= __('sms_admin.sender') ?></label>
                                    <input type="text" class="form-control" id="smsapi_sender" name="sender" maxlength="11">
                                    <small class="text-muted"><?= __('sms_admin.sender_help') ?></small>
                                </div>
                                <div class="d-flex gap-2">
                                    <button type="submit" class="btn btn-primary btn-save-gw">
                                        <i class="bi bi-check-lg me-1"></i> <?= __('sms_admin.btn_save') ?>
                                    </button>
                                    <button type="button" class="btn btn-outline-info btn-balance" data-gateway="smsapi">
                                        <i class="bi bi-wallet2 me-1"></i> <?= __('sms_admin.btn_balance') ?>
                                    </button>
                                </div>
                                <div class="mt-2 sms-balance-result" id="balance-smsapi"></div>
                            </form>
                        </div>

                        <!-- SerwerSMS.pl -->
                        <div class="tab-pane fade" id="tab-serwersms" role="tabpanel">
                            <form id="form-serwersms" data-gateway="serwersms">
                                <?= csrf_field() ?>
                                <div class="row mb-3">
                                    <div class="col-md-6">
                                        <label for="serwersms_username" class="form-label"><?= __('sms_admin.username') ?></label>
                                        <input type="text" class="form-control" id="serwersms_username" name="username" autocomplete="off">
                                    </div>
                                    <div class="col-md-6">
                                        <label for="serwersms_password" class="form-label"><?= __('sms_admin.password') ?></label>
                                        <div class="input-group">
                                            <input type="password" class="form-control" id="serwersms_password" name="password"
                                                   placeholder="&#8226;&#8226;&#8226;&#8226;&#8226;&#8226;&#8226;&#8226;" autocomplete="new-password">
                                            <button class="btn btn-outline-secondary btn-toggle-pass" type="button" data-target="serwersms_password">
                                                <i class="bi bi-eye"></i>
                                            </button>
                                        </div>
                                        <small class="text-muted sms-secret-hint" id="serwersms_password_hint" style="display:none;"></small>
                                    </div>
                                </div>
                                <div class="mb-3">
                                    <label for="serwersms_sender" class="form-label"><?= __('sms_admin.sender') ?></label>
                                    <input type="text" class="form-control" id="serwersms_sender" name="sender" maxlength="11">
                                    <small class="text-muted"><?= __('sms_admin.sender_help') ?></small>
                                </div>
                                <div class="d-flex gap-2">
                                    <button type="submit" class="btn btn-primary btn-save-gw">
                                        <i class="bi bi-check-lg me-1"></i> <?= __('sms_admin.btn_save') ?>
                                    </button>
                                    <button type="button" class="btn btn-outline-info btn-balance" data-gateway="serwersms">
                                        <i class="bi bi-wallet2 me-1"></i> <?= __('sms_admin.btn_balance') ?>
                                    </button>
                                </div>
                                <div class="mt-2 sms-balance-result" id="balance-serwersms"></div>
                            </form>
                        </div>

                        <!-- SMSPlanet.pl -->
                        <div class="tab-pane fade" id="tab-smsplanet" role="tabpanel">
                            <form id="form-smsplanet" data-gateway="smsplanet">
                                <?= csrf_field() ?>
                                <div class="mb-3">
                                    <label for="smsplanet_token" class="form-label"><?= __('sms_admin.token') ?></label>
                                    <div class="input-group">
                                        <input type="password" class="form-control" id="smsplanet_token" name="token"
                                               placeholder="&#8226;&#8226;&#8226;&#8226;&#8226;&#8226;&#8226;&#8226;" autocomplete="off">
                                        <button class="btn btn-outline-secondary btn-toggle-pass" type="button" data-target="smsplanet_token">
                                            <i class="bi bi-eye"></i>
                                        </button>
                                    </div>
                                    <small class="text-muted sms-secret-hint" id="smsplanet_token_hint" style="display:none;"></small>
                                </div>
                                <div class="mb-3">
                                    <label for="smsplanet_sender" class="form-label"><?= __('sms_admin.sender') ?></label>
                                    <input type="text" class="form-control" id="smsplanet_sender" name="sender" maxlength="11">
                                    <small class="text-muted"><?= __('sms_admin.sender_help') ?></small>
                                </div>
                                <div class="d-flex gap-2">
                                    <button type="submit" class="btn btn-primary btn-save-gw">
                                        <i class="bi bi-check-lg me-1"></i> <?= __('sms_admin.btn_save') ?>
                                    </button>
                                    <button type="button" class="btn btn-outline-info btn-balance" data-gateway="smsplanet">
                                        <i class="bi bi-wallet2 me-1"></i> <?= __('sms_admin.btn_balance') ?>
                                    </button>
                                </div>
                                <div class="mt-2 sms-balance-result" id="balance-smsplanet"></div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Panel testowy -->
        <div class="col-lg-4">
            <div class="card">
                <div class="card-header">
                    <i class="bi bi-send-check me-1"></i> <?= __('sms_admin.test_title') ?>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label for="testPhone" class="form-label"><?= __('sms_admin.test_phone') ?></label>
                        <input type="text" class="form-control" id="testPhone"
                               placeholder="<?= __('sms_admin.test_phone_placeholder') ?>">
                    </div>
                    <div class="mb-3">
                        <label for="testMessage" class="form-label"><?= __('sms_admin.test_message') ?></label>
                        <textarea class="form-control" id="testMessage" rows="3"><?= __('sms_admin.test_message_default') ?></textarea>
                        <small class="text-muted" id="charCount">0 / 160</small>
                    </div>
                    <button type="button" class="btn btn-success w-100" id="btnTestSend">
                        <i class="bi bi-send me-1"></i> <?= __('sms_admin.btn_test') ?>
                    </button>
                    <div id="testResult" class="mt-3 d-none"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<script nonce="<?= csp_nonce() ?>">
const SMS_LANG = {
    saved: '<?= __('sms_admin.saved') ?>',
    savedGeneral: '<?= __('sms_admin.saved_general') ?>',
    errorSave: '<?= __('sms_admin.error_save') ?>',
    testSuccess: '<?= __('sms_admin.test_success') ?>',
    testError: '<?= __('sms_admin.test_error') ?>',
    testNoPhone: '<?= __('sms_admin.test_no_phone') ?>',
    testLogged: '<?= __('sms_admin.test_logged') ?>',
    balanceLabel: '<?= __('sms_admin.balance_label') ?>',
    balanceError: '<?= __('sms_admin.balance_error') ?>',
    balanceUnitSmsapi: '<?= __('sms_admin.balance_unit_smsapi') ?>',
    balanceUnitSerwersms: '<?= __('sms_admin.balance_unit_serwersms') ?>',
    balanceUnitSmsplanet: '<?= __('sms_admin.balance_unit_smsplanet') ?>',
    noGateway: '<?= __('sms_admin.no_gateway') ?>',
    statusActive: '<?= __('sms_admin.status_active') ?>',
    statusInactive: '<?= __('sms_admin.status_inactive') ?>',
    tokenSet: '<?= __('sms_admin.token_set') ?>',
    passwordSet: '<?= __('sms_admin.password_set') ?>',
    tokenHelp: '<?= __('sms_admin.token_help') ?>',
    passwordHelp: '<?= __('sms_admin.password_help') ?>',
    btnSave: '<?= __('sms_admin.btn_save') ?>',
    btnSaveGeneral: '<?= __('sms_admin.btn_save_general') ?>',
    btnBalance: '<?= __('sms_admin.btn_balance') ?>',
    btnTest: '<?= __('sms_admin.btn_test') ?>'
};

const CSRF_TOKEN = '<?= csrf_token() ?>';

document.addEventListener('DOMContentLoaded', function() {
    loadConfig();

    // Toggle password visibility
    $('.btn-toggle-pass').on('click', function() {
        var targetId = $(this).data('target');
        var inp = $('#' + targetId);
        var icon = $(this).find('i');
        if (inp.attr('type') === 'password') {
            inp.attr('type', 'text');
            icon.removeClass('bi-eye').addClass('bi-eye-slash');
        } else {
            inp.attr('type', 'password');
            icon.removeClass('bi-eye-slash').addClass('bi-eye');
        }
    });

    // Save general
    $('#generalForm').on('submit', function(e) {
        e.preventDefault();
        saveGeneral();
    });

    // Save gateway forms
    $('form[data-gateway]').on('submit', function(e) {
        e.preventDefault();
        saveGateway($(this).data('gateway'));
    });

    // Check balance
    $('.btn-balance').on('click', function() {
        checkBalance($(this).data('gateway'));
    });

    // Test send
    $('#btnTestSend').on('click', function() {
        testSend();
    });

    // Character counter
    $('#testMessage').on('input', function() {
        var len = $(this).val().length;
        var smsCount = Math.ceil(len / 160) || 1;
        $('#charCount').text(len + ' / ' + (smsCount * 160) + ' (' + smsCount + ' SMS)');
    }).trigger('input');
});

function loadConfig() {
    $.get('admin.php?page=sms&action=get_config', function(data) {
        if (!data.success) return;
        var c = data.config;

        // General
        $('#activeGateway').val(c.active_gateway || '');
        $('#testMode').prop('checked', c.test_mode);
        $('#defaultPrefix').val(c.default_prefix || '48');

        // SMSAPI
        $('#smsapi_sender').val(c.smsapi.sender || '');
        if (c.smsapi.token_set) {
            $('#smsapi_token_hint').text(SMS_LANG.tokenSet + ' — ' + SMS_LANG.tokenHelp).show();
        }

        // SerwerSMS
        $('#serwersms_username').val(c.serwersms.username || '');
        $('#serwersms_sender').val(c.serwersms.sender || '');
        if (c.serwersms.password_set) {
            $('#serwersms_password_hint').text(SMS_LANG.passwordSet + ' — ' + SMS_LANG.passwordHelp).show();
        }

        // SMSPlanet
        $('#smsplanet_sender').val(c.smsplanet.sender || '');
        if (c.smsplanet.token_set) {
            $('#smsplanet_token_hint').text(SMS_LANG.tokenSet + ' — ' + SMS_LANG.tokenHelp).show();
        }

        updateStatus(c.active_gateway);
    });
}

function saveGeneral() {
    var btn = $('#btnSaveGeneral');
    btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-1"></span>...');

    $.post('admin.php?page=sms&action=save_general', $('#generalForm').serialize(), function(data) {
        if (data.success) {
            showAlert('success', data.message || SMS_LANG.savedGeneral);
            updateStatus($('#activeGateway').val());
        } else {
            showAlert('danger', data.error || SMS_LANG.errorSave);
        }
    }).fail(function() {
        showAlert('danger', SMS_LANG.errorSave);
    }).always(function() {
        btn.prop('disabled', false).html('<i class="bi bi-check-lg me-1"></i> ' + SMS_LANG.btnSaveGeneral);
    });
}

function saveGateway(gw) {
    var form = $('#form-' + gw);
    var btn = form.find('.btn-save-gw');
    btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-1"></span>...');

    $.post('admin.php?page=sms&action=save_' + gw, form.serialize(), function(data) {
        if (data.success) {
            showAlert('success', data.message || SMS_LANG.saved);
            // Clear secret fields and show hint
            if (gw === 'smsapi') {
                if ($('#smsapi_token').val()) {
                    $('#smsapi_token').val('');
                    $('#smsapi_token_hint').text(SMS_LANG.tokenSet + ' — ' + SMS_LANG.tokenHelp).show();
                }
            } else if (gw === 'serwersms') {
                if ($('#serwersms_password').val()) {
                    $('#serwersms_password').val('');
                    $('#serwersms_password_hint').text(SMS_LANG.passwordSet + ' — ' + SMS_LANG.passwordHelp).show();
                }
            } else if (gw === 'smsplanet') {
                if ($('#smsplanet_token').val()) {
                    $('#smsplanet_token').val('');
                    $('#smsplanet_token_hint').text(SMS_LANG.tokenSet + ' — ' + SMS_LANG.tokenHelp).show();
                }
            }
        } else {
            showAlert('danger', data.error || SMS_LANG.errorSave);
        }
    }).fail(function() {
        showAlert('danger', SMS_LANG.errorSave);
    }).always(function() {
        btn.prop('disabled', false).html('<i class="bi bi-check-lg me-1"></i> ' + SMS_LANG.btnSave);
    });
}

function checkBalance(gw) {
    var btn = $('.btn-balance[data-gateway="' + gw + '"]');
    var resultEl = $('#balance-' + gw);
    btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-1"></span>...');

    $.post('admin.php?page=sms&action=check_balance', { csrf_token: CSRF_TOKEN, gateway: gw }, function(data) {
        if (data.success) {
            var unitKey = 'balanceUnit' + gw.charAt(0).toUpperCase() + gw.slice(1);
            var unit = SMS_LANG[unitKey] || '';
            resultEl.html('<span class="badge bg-success"><i class="bi bi-wallet2 me-1"></i>' + SMS_LANG.balanceLabel + ': ' + escHtml(data.balance) + ' ' + unit + '</span>');
        } else {
            var msg = SMS_LANG.balanceError.replace(':error', escHtml(data.error || 'Unknown error'));
            resultEl.html('<span class="badge bg-danger">' + msg + '</span>');
        }
    }).fail(function() {
        resultEl.html('<span class="badge bg-danger">Network error</span>');
    }).always(function() {
        btn.prop('disabled', false).html('<i class="bi bi-wallet2 me-1"></i> ' + SMS_LANG.btnBalance);
    });
}

function testSend() {
    var phone = $('#testPhone').val().trim();
    if (!phone) {
        $('#testResult').removeClass('d-none alert-success alert-danger').addClass('alert alert-warning').text(SMS_LANG.testNoPhone);
        return;
    }

    var btn = $('#btnTestSend');
    btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-1"></span>...');

    $.post('admin.php?page=sms&action=test_send', {
        csrf_token: CSRF_TOKEN,
        phone: phone,
        message: $('#testMessage').val()
    }, function(data) {
        if (data.success) {
            var msg = data.message || SMS_LANG.testSuccess;
            $('#testResult').removeClass('d-none alert-danger alert-warning').addClass('alert alert-success').text(msg);
        } else {
            var msg = SMS_LANG.testError.replace(':error', escHtml(data.error || 'Unknown error'));
            $('#testResult').removeClass('d-none alert-success alert-warning').addClass('alert alert-danger').text(msg);
        }
    }).fail(function() {
        $('#testResult').removeClass('d-none alert-success alert-warning').addClass('alert alert-danger').text('Network error');
    }).always(function() {
        btn.prop('disabled', false).html('<i class="bi bi-send me-1"></i> ' + SMS_LANG.btnTest);
    });
}

function showAlert(type, msg) {
    $('#smsAlert').removeClass('d-none alert-success alert-danger alert-warning alert-info')
        .addClass('alert alert-' + type + ' alert-dismissible fade show')
        .html(msg + '<button type="button" class="btn-close" data-bs-dismiss="alert"></button>');
}

function updateStatus(gateway) {
    if (gateway) {
        var gwName = {smsapi: 'SMSAPI.pl', serwersms: 'SerwerSMS.pl', smsplanet: 'SMSPlanet.pl'}[gateway] || gateway;
        var msg = SMS_LANG.statusActive.replace(':gateway', gwName);
        $('#smsStatus').html('<div class="alert alert-success mb-0"><i class="bi bi-check-circle me-1"></i> <strong>' + escHtml(msg) + '</strong></div>');
    } else {
        $('#smsStatus').html('<div class="alert alert-secondary mb-0"><i class="bi bi-info-circle me-1"></i> ' + SMS_LANG.statusInactive + '</div>');
    }
}

function escHtml(str) {
    var div = document.createElement('div');
    div.appendChild(document.createTextNode(str));
    return div.innerHTML;
}
</script>
