$(function () {
    loadData();
    $('#searchBox, #alertStatusFilter').on('change', loadData);
    $('#searchBox').on('input', debounce(loadData, 300));
    $('#btnRefresh').on('click', loadData);
});

function loadData() {
    loadAlertSettings();
    loadAlertDeliveries();
}

function loadAlertSettings() {
    $.get('api/alerts.php?action=settings', function (res) {
        if (res.status !== 'success') return;
        var d = res.data || {};
        $('#alertSettings').html(
            '<div class="row g-3 small">'
            + '<div class="col-md-2"><strong>Email</strong><br>' + (d.email_enabled ? '<span class="text-success">Enabled</span>' : '<span class="text-secondary">Disabled</span>') + '</div>'
            + '<div class="col-md-2"><strong>SMS</strong><br>' + (d.sms_enabled ? '<span class="text-success">Enabled</span>' : '<span class="text-secondary">Disabled</span>') + '</div>'
            + '<div class="col-md-2"><strong>Provider</strong><br>' + esc(d.sms_provider || '') + '</div>'
            + '<div class="col-md-2"><strong>Sender</strong><br>' + esc(d.sms_sender || '') + '</div>'
            + '<div class="col-md-2"><strong>SMS Webhook</strong><br>' + (d.sms_webhook_url ? '<code>' + esc(d.sms_webhook_url) + '</code>' : '<span class="text-danger">Missing</span>') + '</div>'
            + '<div class="col-md-2"><strong>App URL</strong><br>' + (d.app_url ? esc(d.app_url) : '<span class="text-muted">Not set</span>') + '</div>'
            + '</div>'
        );
    });
}

function loadAlertDeliveries() {
    $.get('api/alerts.php', {
        action: 'list',
        search: $('#searchBox').val(),
        status: $('#alertStatusFilter').val()
    }, function (res) {
        if (res.status !== 'success') return;
        var data = res.data || [];
        var total = data.length, sent = 0, failed = 0, other = 0;
        data.forEach(function (x) {
            if (x.status === 'sent') sent++;
            else if (x.status === 'failed') failed++;
            else other++;
        });
        $('#kpiTotal').text(total);
        $('#kpiSent').text(sent);
        $('#kpiFailed').text(failed);
        $('#kpiOther').text(other);

        var html = '';
        if (!data.length) html = '<tr><td colspan="8" class="text-center py-4 text-muted">No delivery logs found</td></tr>';
        else data.forEach(function (row) {
            var canRetry = row.status === 'failed';
            var badgeClass = row.status === 'sent' ? 'success' : row.status === 'failed' ? 'danger' : row.status === 'pending' ? 'warning' : 'secondary';
            html += '<tr>'
                + '<td class="text-nowrap">' + esc(row.created_at || '') + '</td>'
                + '<td>' + esc(row.event_key || '') + '</td>'
                + '<td>' + esc(row.channel || '') + '</td>'
                + '<td>' + esc(row.recipient || '') + '</td>'
                + '<td><span class="badge bg-' + badgeClass + '">' + esc(row.status || '') + '</span></td>'
                + '<td>' + (row.attempts || 0) + '</td>'
                + '<td class="text-truncate" style="max-width:260px;" title="' + esc(row.provider_response || '') + '">' + esc(row.provider_response || '-') + '</td>'
                + '<td class="text-end">'
                + (canRetry ? '<button class="btn btn-sm btn-outline-primary btn-retry" data-id="' + row.id + '"><i class="bi bi-arrow-repeat"></i> Retry</button>' : '')
                + '</td></tr>';
        });
        $('#alertDeliveryTable').html(html);
    });
}

$(document).on('click', '.btn-retry', function () {
    var id = $(this).data('id');
    var btn = $(this);
    btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span>');
    $.post('api/alerts.php?action=retry', { id: id, csrf_token: window.CSRF_TOKEN }, function (res) {
        if (res.status === 'success') {
            showAlert('Retry successful', 'success');
            loadAlertDeliveries();
        } else {
            showAlert(res.message || 'Retry failed', 'danger');
        }
    }).always(function () {
        btn.prop('disabled', false).html('<i class="bi bi-arrow-repeat"></i> Retry');
    });
});

function showAlert(msg, type) {
    var box = $('#alertBox');
    box.removeClass('d-none alert-success alert-danger alert-warning alert-info')
        .addClass('alert-' + type).text(msg);
    setTimeout(function () { box.addClass('d-none'); }, 5000);
}

function esc(t) { return $('<div>').text(t || '').html(); }
function debounce(fn, ms) { var t; return function () { var c = this, a = arguments; clearTimeout(t); t = setTimeout(function () { fn.apply(c, a); }, ms); }; }
