<?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 - Wysyłka SMS do klientów (admin)
 */

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

$sms_history_file = IBOK_CFG_DIR . '/sms_send_history.json';

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

    // Pobierz listę klientów z telefonami
    if ($action === 'get_clients') {
        $pdo = db_get_pdo();
        if (!$pdo) {
            echo json_encode(['success' => false, 'error' => 'Database connection error']);
            exit;
        }

        try {
            $stmt = $pdo->query(
                'SELECT U_NRKLIENTA, U_NAZWISKO, U_IMIE, U_LOGIN, U_TEL1, U_TEL2, U_SALDOZALEGLE
                 FROM vUserdb
                 WHERE (U_DATADEAKTYWACJI IS NULL OR U_DATADEAKTYWACJI = \'0000-00-00\')
                 ORDER BY U_NAZWISKO'
            );
            $rows = $stmt->fetchAll();
            $clients = [];

            foreach ($rows as $row) {
                $saldoZalegle = (float)($row['U_SALDOZALEGLE'] ?? 0);
                $clients[] = [
                    'id'    => (string)$row['U_NRKLIENTA'],
                    'name'  => trim(db_str($row['U_NAZWISKO']) . ' ' . db_str($row['U_IMIE'])),
                    'login' => db_str($row['U_LOGIN']),
                    'tel1'  => db_str($row['U_TEL1']),
                    'tel2'  => db_str($row['U_TEL2']),
                    'debt'      => $saldoZalegle > 0 ? number_format($saldoZalegle, 2, ',', '') : '',
                    'debt_raw'  => $saldoZalegle > 0 ? round($saldoZalegle, 2) : 0,
                ];
            }

            echo json_encode(['success' => true, 'clients' => $clients]);
        } catch (PDOException $e) {
            ibok_log("wyslij_sms get_clients error: " . $e->getMessage(), 'error');
            echo json_encode(['success' => false, 'error' => 'Query error']);
        }
        exit;
    }

    // Wyślij SMS
    if ($action === 'send_sms') {
        if (ibok_is_demo()) {
            echo json_encode(['success' => false, 'error' => __('demo.feature_blocked')]);
            exit;
        }
        if (!csrf_validate()) {
            echo json_encode(['success' => false, 'error' => __('wyslij_sms.error_csrf')]);
            exit;
        }

        $phones = $_POST['phones'] ?? [];
        $recipients = $_POST['recipients'] ?? []; // client info for history
        $message = trim($_POST['message'] ?? '');

        if (!is_array($phones) || empty($phones)) {
            echo json_encode(['success' => false, 'error' => __('wyslij_sms.no_recipients')]);
            exit;
        }
        if (empty($message)) {
            echo json_encode(['success' => false, 'error' => __('wyslij_sms.no_message')]);
            exit;
        }

        // Sprawdź czy bramka skonfigurowana
        $config = sms_load_config();
        if (empty($config['active_gateway'])) {
            echo json_encode(['success' => false, 'error' => __('wyslij_sms.no_gateway_configured')]);
            exit;
        }

        $gwName = $config['active_gateway'];
        $results = [];
        $sent = 0;
        $failed = 0;

        // Prefix kraju z konfiguracji
        $defaultPrefix = $config['default_prefix'] ?? '48';

        // Wyślij SMS-y po jednym
        foreach ($phones as $i => $phone) {
            $phone = sms_normalize_phone($phone, $defaultPrefix);
            if (empty($phone)) {
                $failed++;
                $results[] = ['phone' => $phone, 'status' => 'invalid'];
                continue;
            }

            $result = sms_send($phone, $message);

            $status = $result['success'] ? 'sent' : 'failed';
            if ($result['success']) {
                $sent++;
            } else {
                $failed++;
            }

            $results[] = [
                'phone'  => $phone,
                'status' => $status,
                'error'  => $result['error'] ?? '',
            ];

            // Zapisz do historii
            $recipientLabel = isset($recipients[$i]) ? $recipients[$i] : $phone;
            sms_history_add($sms_history_file, [
                'date'      => date('Y-m-d H:i:s'),
                'recipient' => $recipientLabel,
                'phone'     => $phone,
                'message'   => mb_substr($message, 0, 160),
                'status'    => $status,
                'gateway'   => $gwName,
                'error'     => $result['error'] ?? '',
            ]);
        }

        ibok_log("Wysyłka SMS: {$sent} wysłano, {$failed} błędów (bramka: {$gwName})", 'info');

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

    // Pobierz historię
    if ($action === 'get_history') {
        $history = sms_history_load($sms_history_file);
        echo json_encode(['success' => true, 'history' => $history]);
        exit;
    }

    // Wyczyść historię
    if ($action === 'clear_history') {
        if (!csrf_validate()) {
            echo json_encode(['success' => false, 'error' => __('wyslij_sms.error_csrf')]);
            exit;
        }
        @file_put_contents($sms_history_file, '[]', LOCK_EX);
        ibok_log("Historia wysyłek SMS wyczyszczona", 'info');
        echo json_encode(['success' => true, 'message' => __('wyslij_sms.history_cleared')]);
        exit;
    }

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

// =============================================
// Normalizacja numeru telefonu
// =============================================

/**
 * Normalizuj numer telefonu z bazy do formatu bramki SMS.
 *
 * Obsługiwane formaty wejściowe:
 *   123-456-789, 123 456 789, +48 123-456-789, 48123456789,
 *   0048123456789, (48) 500-600-700, tel. 123-456-789
 *
 * @param string $phone Surowy numer z bazy
 * @param string $prefix Domyślny prefix kraju (np. '48')
 * @return string Znormalizowany numer (np. '48123456789') lub '' jeśli nieprawidłowy
 */
function sms_normalize_phone($phone, $prefix = '48') {
    // Usuń wszystko oprócz cyfr i +
    $phone = preg_replace('/[^0-9+]/', '', $phone);
    // Usuń wiodący +
    $phone = ltrim($phone, '+');
    if (empty($phone)) return '';

    // 00XX... → XX... (podwójne zero jako prefix międzynarodowy)
    if (substr($phone, 0, 2) === '00' && strlen($phone) > 10) {
        $phone = substr($phone, 2);
    }

    // 9 cyfr → dodaj prefix krajowy
    if (strlen($phone) === 9) {
        $phone = $prefix . $phone;
    }

    // Walidacja: 11 cyfr dla polskiego numeru (48 + 9 cyfr)
    if (strlen($phone) < 10 || strlen($phone) > 15) {
        return '';
    }

    return $phone;
}

// =============================================
// Funkcje historii
// =============================================

function sms_history_load($file) {
    if (!file_exists($file)) return [];
    $data = json_decode(file_get_contents($file), true);
    return is_array($data) ? $data : [];
}

function sms_history_add($file, $entry) {
    $history = sms_history_load($file);
    array_unshift($history, $entry);
    // Limit do 500 wpisów
    if (count($history) > 500) {
        $history = array_slice($history, 0, 500);
    }
    @file_put_contents($file, json_encode($history, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE), LOCK_EX);
}

// Sprawdź bramkę
$config = sms_load_config();
$gatewayConfigured = !empty($config['active_gateway']);
$gatewayName = $config['active_gateway'] ?? '';
?>

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

    <?= ibok_help_section('admin_wyslij_sms', __('help.show_help'), __('help_admin.wyslij_sms_section_content')) ?>

    <?php if (!$gatewayConfigured): ?>
    <div class="alert alert-warning">
        <i class="bi bi-exclamation-triangle me-1"></i>
        <?= __('wyslij_sms.no_gateway_configured') ?>
    </div>
    <?php endif; ?>

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

    <!-- Zakładki -->
    <ul class="nav nav-tabs mb-3" role="tablist">
        <li class="nav-item">
            <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#tab-send" type="button">
                <i class="bi bi-send me-1"></i> <?= __('wyslij_sms.tab_send') ?>
            </button>
        </li>
        <li class="nav-item">
            <button class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-history" type="button" id="historyTabBtn">
                <i class="bi bi-clock-history me-1"></i> <?= __('wyslij_sms.tab_history') ?>
            </button>
        </li>
    </ul>

    <div class="tab-content">
        <!-- TAB: Wyślij SMS -->
        <div class="tab-pane fade show active" id="tab-send">
            <div class="row g-4">
                <!-- Lista klientów -->
                <div class="col-lg-8">
                    <div class="card">
                        <div class="card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
                            <span><i class="bi bi-people me-1"></i> <?= __('wyslij_sms.select_clients') ?></span>
                            <div class="d-flex gap-2 flex-wrap">
                                <div class="form-check form-switch mb-0">
                                    <input class="form-check-input" type="checkbox" id="filterWithPhone">
                                    <label class="form-check-label small" for="filterWithPhone"><?= __('wyslij_sms.filter_with_phone') ?></label>
                                </div>
                                <div class="form-check form-switch mb-0">
                                    <input class="form-check-input" type="checkbox" id="filterDebt">
                                    <label class="form-check-label small" for="filterDebt"><?= __('wyslij_sms.filter_debt') ?></label>
                                </div>
                                <button class="btn btn-outline-primary btn-sm" id="btnSelectWithPhone" type="button">
                                    <i class="bi bi-check-all me-1"></i><?= __('wyslij_sms.btn_select_with_phone') ?>
                                </button>
                                <button class="btn btn-outline-secondary btn-sm" id="btnDeselectAll" type="button">
                                    <i class="bi bi-x-lg me-1"></i><?= __('wyslij_sms.btn_deselect_all') ?>
                                </button>
                            </div>
                        </div>
                        <div class="card-body p-0">
                            <div class="table-responsive">
                                <table class="table table-hover table-sm mb-0" id="clientsTable">
                                    <thead class="table-light">
                                        <tr>
                                            <th style="width:30px;"><?= __('wyslij_sms.col_select') ?></th>
                                            <th><?= __('wyslij_sms.col_client_id') ?></th>
                                            <th><?= __('wyslij_sms.col_name') ?></th>
                                            <th><?= __('wyslij_sms.col_login') ?></th>
                                            <th><?= __('wyslij_sms.col_tel1') ?></th>
                                            <th><?= __('wyslij_sms.col_tel2') ?></th>
                                            <th><?= __('wyslij_sms.col_debt') ?></th>
                                        </tr>
                                    </thead>
                                    <tbody id="clientsBody">
                                        <tr><td colspan="7" class="text-center text-muted py-3">
                                            <span class="spinner-border spinner-border-sm me-1"></span> ...
                                        </td></tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        <div class="card-footer text-muted small" id="selectionInfo">
                            <?= __('wyslij_sms.selected_count', ['count' => '0']) ?>
                        </div>
                    </div>
                </div>

                <!-- Formularz wysyłki -->
                <div class="col-lg-4">
                    <div class="card">
                        <div class="card-header">
                            <i class="bi bi-chat-left-text me-1"></i> <?= __('wyslij_sms.message') ?>
                        </div>
                        <div class="card-body">
                            <div class="mb-3">
                                <label for="manualPhone" class="form-label small"><?= __('wyslij_sms.manual_number') ?></label>
                                <input type="text" class="form-control form-control-sm" id="manualPhone"
                                       placeholder="np. 500600700">
                                <small class="text-muted"><?= __('wyslij_sms.manual_number_help') ?></small>
                            </div>

                            <div class="mb-3">
                                <label for="smsMessage" class="form-label small"><?= __('wyslij_sms.message') ?></label>
                                <textarea class="form-control" id="smsMessage" rows="5" maxlength="480"></textarea>
                                <small class="text-muted" id="charCounter">0 zn. / 1 SMS</small>
                            </div>

                            <button type="button" class="btn btn-success w-100" id="btnSendSms" <?= !$gatewayConfigured ? 'disabled' : '' ?>>
                                <i class="bi bi-send me-1"></i> <?= __('wyslij_sms.btn_send') ?>
                            </button>

                            <div id="sendProgress" class="mt-3 d-none">
                                <div class="progress mb-2">
                                    <div class="progress-bar progress-bar-striped progress-bar-animated" id="sendProgressBar" style="width: 0%"></div>
                                </div>
                                <small class="text-muted" id="sendProgressText"></small>
                            </div>

                            <div id="sendResult" class="mt-3 d-none"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- TAB: Historia -->
        <div class="tab-pane fade" id="tab-history">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <span><i class="bi bi-clock-history me-1"></i> <?= __('wyslij_sms.history_title') ?></span>
                    <button class="btn btn-outline-danger btn-sm" id="btnClearHistory" type="button">
                        <i class="bi bi-trash me-1"></i><?= __('wyslij_sms.btn_clear_history') ?>
                    </button>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover table-sm mb-0" id="historyTable">
                            <thead class="table-light">
                                <tr>
                                    <th><?= __('wyslij_sms.col_date') ?></th>
                                    <th><?= __('wyslij_sms.col_recipient') ?></th>
                                    <th><?= __('wyslij_sms.col_message') ?></th>
                                    <th><?= __('wyslij_sms.col_status') ?></th>
                                    <th><?= __('wyslij_sms.col_gateway') ?></th>
                                </tr>
                            </thead>
                            <tbody id="historyBody">
                                <tr><td colspan="5" class="text-center text-muted py-3"><?= __('wyslij_sms.history_empty') ?></td></tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script nonce="<?= csp_nonce() ?>">
const SMS_SEND_LANG = {
    selectedCount:  '<?= __('wyslij_sms.selected_count', ['count' => '__COUNT__']) ?>',
    confirmSend:    '<?= __('wyslij_sms.confirm_send', ['count' => '__COUNT__']) ?>',
    noRecipients:   '<?= __('wyslij_sms.no_recipients') ?>',
    noMessage:      '<?= __('wyslij_sms.no_message') ?>',
    sending:        '<?= __('wyslij_sms.sending') ?>',
    sendProgress:   '<?= __('wyslij_sms.send_progress', ['sent' => '__SENT__', 'total' => '__TOTAL__']) ?>',
    sendComplete:   '<?= __('wyslij_sms.send_complete', ['sent' => '__SENT__', 'failed' => '__FAILED__']) ?>',
    sentOk:         '<?= __('wyslij_sms.sent_ok') ?>',
    sentError:      '<?= __('wyslij_sms.sent_error') ?>',
    historyEmpty:   '<?= __('wyslij_sms.history_empty') ?>',
    confirmClear:   '<?= __('wyslij_sms.confirm_clear') ?>',
    historyCleared: '<?= __('wyslij_sms.history_cleared') ?>',
    charCount:      '<?= __('wyslij_sms.char_count', ['chars' => '__CHARS__', 'sms' => '__SMS__']) ?>',
    noGateway:      '<?= __('wyslij_sms.no_gateway_configured') ?>',
    btnSend:        '<?= __('wyslij_sms.btn_send') ?>'
};

const CSRF_TOKEN = '<?= csrf_token() ?>';
let allClients = [];
let clientsDT = null;

// DataTables language
const DT_LANG = (document.documentElement.lang || 'pl') === 'en' ? {
    "emptyTable": "No data available", "info": "Showing _START_ to _END_ of _TOTAL_ entries",
    "infoEmpty": "Showing 0 to 0 of 0 entries", "infoFiltered": "(filtered from _MAX_ total entries)",
    "lengthMenu": "Show _MENU_ entries", "search": "Search:", "zeroRecords": "No matching records found",
    "paginate": {"first":"First","last":"Last","next":"Next","previous":"Previous"}
} : {
    "emptyTable": "Brak danych", "info": "Pozycje od _START_ do _END_ z _TOTAL_ łącznie",
    "infoEmpty": "Pozycji 0 z 0", "infoFiltered": "(filtrowane z _MAX_ pozycji)",
    "lengthMenu": "Pokaż _MENU_ pozycji", "search": "Szukaj:", "zeroRecords": "Nie znaleziono pasujących pozycji",
    "paginate": {"first":"Pierwsza","last":"Ostatnia","next":"Następna","previous":"Poprzednia"}
};

document.addEventListener('DOMContentLoaded', function() {
    // Custom DataTables filter for phone/debt toggles
    $.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {
        if (settings.nTable.id !== 'clientsTable') return true;
        var row = clientsDT ? clientsDT.row(dataIndex).data() : null;
        if (!row) return true;
        var match = row[0].match(/data-idx="(\d+)"/);
        if (!match) return true;
        var idx = parseInt(match[1]);
        var c = allClients[idx];
        if (!c) return true;

        if ($('#filterWithPhone').is(':checked') && !c.tel1 && !c.tel2) return false;
        if ($('#filterDebt').is(':checked') && !c.debt) return false;
        return true;
    });

    loadClients();

    // Character counter
    $('#smsMessage').on('input', function() {
        var len = $(this).val().length;
        var smsCount = Math.ceil(len / 160) || 1;
        var txt = SMS_SEND_LANG.charCount.replace('__CHARS__', len).replace('__SMS__', smsCount);
        $('#charCounter').text(txt);
    });

    // Filter toggles — redraw DataTable (custom search plugin handles filtering)
    $('#filterWithPhone, #filterDebt').on('change', function() {
        if (clientsDT) clientsDT.draw();
    });

    // Select all with phone (across ALL pages)
    $('#btnSelectWithPhone').on('click', function() {
        if (!clientsDT) return;
        // Iterate all rows (not just visible page)
        clientsDT.rows({search: 'applied'}).every(function() {
            var rowData = this.data();
            var match = rowData[0].match(/data-idx="(\d+)"/);
            if (!match) return;
            var c = allClients[parseInt(match[1])];
            if (c && (c.tel1 || c.tel2)) {
                $(this.node()).find('.client-check').prop('checked', true);
            }
        });
        updateSelectionCount();
    });

    // Deselect all (across ALL pages)
    $('#btnDeselectAll').on('click', function() {
        if (!clientsDT) return;
        clientsDT.rows().every(function() {
            $(this.node()).find('.client-check').prop('checked', false);
        });
        updateSelectionCount();
    });

    // Selection count — delegate on tbody (works across pages)
    $('#clientsTable tbody').on('change', '.client-check', function() {
        updateSelectionCount();
    });

    // Send SMS
    $('#btnSendSms').on('click', function() {
        sendSms();
    });

    // Clear history
    $('#btnClearHistory').on('click', function() {
        if (confirm(SMS_SEND_LANG.confirmClear)) {
            clearHistory();
        }
    });

    // Load history on tab switch
    $('#historyTabBtn').on('shown.bs.tab', function() {
        loadHistory();
    });
});

function loadClients() {
    $.get('admin.php?page=wyslij_sms&action=get_clients', function(data) {
        if (data.success) {
            allClients = data.clients;
            initClientsTable();
        } else {
            $('#clientsBody').html('<tr><td colspan="7" class="text-center text-danger">' + escHtml(data.error || 'Error') + '</td></tr>');
        }
    }).fail(function() {
        $('#clientsBody').html('<tr><td colspan="7" class="text-center text-danger">Network error</td></tr>');
    });
}

function initClientsTable() {
    // Build rows data
    var rows = [];
    for (var i = 0; i < allClients.length; i++) {
        var c = allClients[i];
        rows.push([
            '<input type="checkbox" class="form-check-input client-check" data-idx="' + i + '">',
            '<a href="admin.php?page=klient_info&id=' + encodeURIComponent(c.id) + '">' + escHtml(c.id) + '</a>',
            escHtml(c.name),
            escHtml(c.login),
            escHtml(c.tel1),
            escHtml(c.tel2),
            c.debt_raw || 0
        ]);
    }

    // Destroy previous instance if exists
    if (clientsDT) {
        clientsDT.destroy();
        clientsDT = null;
    }
    // Clear spinner/placeholder rows before DataTables init
    $('#clientsTable tbody').empty();

    clientsDT = $('#clientsTable').DataTable({
        data: rows,
        destroy: true,
        paging: true,
        pageLength: 25,
        order: [[2, 'asc']],
        columnDefs: [
            { orderable: false, targets: 0, className: 'text-center' },
            {
                targets: 6,
                type: 'num',
                render: function(data, type) {
                    if (type === 'sort' || type === 'type') {
                        return parseFloat(data) || 0;
                    }
                    if (!data || data <= 0) return '';
                    var formatted = parseFloat(data).toFixed(2).replace('.', ',');
                    return '<span class="badge bg-danger">' + formatted + ' zł</span>';
                }
            }
        ],
        language: DT_LANG
    });

    updateSelectionCount();
}

function updateSelectionCount() {
    var count = 0;
    if (clientsDT) {
        clientsDT.rows().every(function() {
            if ($(this.node()).find('.client-check').is(':checked')) count++;
        });
    }
    var manual = $('#manualPhone').val().trim();
    if (manual) count++;
    var txt = SMS_SEND_LANG.selectedCount.replace('__COUNT__', count);
    $('#selectionInfo').text(txt);
}

function getSelectedPhones() {
    var phones = [];
    var recipients = [];

    if (clientsDT) {
        clientsDT.rows().every(function() {
            var cb = $(this.node()).find('.client-check');
            if (!cb.is(':checked')) return;
            var idx = cb.data('idx');
            var c = allClients[idx];
            if (!c) return;

            var phone = c.tel1 || c.tel2;
            if (phone) {
                phones.push(phone);
                recipients.push(c.name + ' (' + c.id + ') ' + phone);
            }
        });
    }

    // Dodatkowy numer ręczny
    var manual = $('#manualPhone').val().trim();
    if (manual) {
        phones.push(manual);
        recipients.push(manual);
    }

    return { phones: phones, recipients: recipients };
}

function sendSms() {
    var sel = getSelectedPhones();
    var message = $('#smsMessage').val().trim();

    if (sel.phones.length === 0) {
        showAlert('warning', SMS_SEND_LANG.noRecipients);
        return;
    }
    if (!message) {
        showAlert('warning', SMS_SEND_LANG.noMessage);
        return;
    }

    var confirmMsg = SMS_SEND_LANG.confirmSend.replace('__COUNT__', sel.phones.length);
    if (!confirm(confirmMsg)) return;

    var btn = $('#btnSendSms');
    btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-1"></span> ' + SMS_SEND_LANG.sending);
    $('#sendProgress').removeClass('d-none');
    $('#sendResult').addClass('d-none');

    $.post('admin.php?page=wyslij_sms&action=send_sms', {
        csrf_token: CSRF_TOKEN,
        phones: sel.phones,
        recipients: sel.recipients,
        message: message
    }, function(data) {
        if (data.success !== undefined) {
            var sent = data.sent || 0;
            var failed = data.failed || 0;
            var total = sent + failed;
            var pct = total > 0 ? Math.round((sent / total) * 100) : 0;

            $('#sendProgressBar').css('width', '100%');

            var completeTxt = SMS_SEND_LANG.sendComplete.replace('__SENT__', sent).replace('__FAILED__', failed);
            $('#sendProgressText').text(completeTxt);

            var alertType = failed === 0 ? 'success' : (sent > 0 ? 'warning' : 'danger');
            showAlert(alertType, completeTxt);
        } else {
            showAlert('danger', data.error || 'Error');
        }
    }).fail(function() {
        showAlert('danger', 'Network error');
    }).always(function() {
        btn.prop('disabled', false).html('<i class="bi bi-send me-1"></i> ' + SMS_SEND_LANG.btnSend);
    });
}

function loadHistory() {
    $.get('admin.php?page=wyslij_sms&action=get_history', function(data) {
        if (data.success && data.history && data.history.length > 0) {
            var html = '';
            for (var i = 0; i < data.history.length; i++) {
                var h = data.history[i];
                var statusBadge = h.status === 'sent'
                    ? '<span class="badge bg-success">' + SMS_SEND_LANG.sentOk + '</span>'
                    : '<span class="badge bg-danger" title="' + escAttr(h.error || '') + '">' + SMS_SEND_LANG.sentError + '</span>';

                html += '<tr>' +
                    '<td class="text-nowrap">' + escHtml(h.date || '') + '</td>' +
                    '<td>' + escHtml(h.recipient || h.phone || '') + '</td>' +
                    '<td class="small">' + escHtml(h.message || '') + '</td>' +
                    '<td>' + statusBadge + '</td>' +
                    '<td>' + escHtml(h.gateway || '') + '</td>' +
                    '</tr>';
            }
            $('#historyBody').html(html);
        } else {
            $('#historyBody').html('<tr><td colspan="5" class="text-center text-muted py-3">' + SMS_SEND_LANG.historyEmpty + '</td></tr>');
        }
    });
}

function clearHistory() {
    $.post('admin.php?page=wyslij_sms&action=clear_history', {
        csrf_token: CSRF_TOKEN
    }, function(data) {
        if (data.success) {
            showAlert('success', data.message || SMS_SEND_LANG.historyCleared);
            loadHistory();
        } else {
            showAlert('danger', data.error || 'Error');
        }
    });
}

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(escHtml(msg) + '<button type="button" class="btn-close" data-bs-dismiss="alert"></button>');
}

function escHtml(str) {
    if (!str) return '';
    var div = document.createElement('div');
    div.appendChild(document.createTextNode(str));
    return div.innerHTML;
}

function escAttr(str) {
    return escHtml(str).replace(/"/g, '&quot;');
}
</script>
