let insurers = [];
let editId = 0;

function escapeHtml(t) { return $('<div>').text(t || '').html(); }

$(function () {
    loadInsurers();

    $('#btnAddInsurer').on('click', function () { openModal(); });
    $('#btnSaveInsurer').on('click', saveInsurer);
    $(document).on('click', '.edit-insurer', function () { openModal($(this).data('id')); });
    $(document).on('click', '.delete-insurer', function () { deleteInsurer($(this).data('id')); });

    $('#searchBox, #statusFilter').on('change keyup', function () { renderTable(); });
});

function showAlert(msg, type) {
    const box = $('#alertBox');
    box.removeClass('d-none alert-success alert-danger alert-warning')
        .addClass('alert-' + (type || 'success')).html(msg);
    clearTimeout(window._alertTimer);
    window._alertTimer = setTimeout(function () { box.addClass('d-none'); }, 4000);
}

function loadInsurers() {
    $.get('api/insurers.php', { action: 'list' }, function (res) {
        if (res.status !== 'success') { showAlert(res.message, 'danger'); return; }
        insurers = res.data || [];
        renderTable();
        updateKpis();
    }, 'json').fail(function (jq, status, err) {
        showAlert('API error: ' + status + ' - ' + (err || 'unknown'), 'danger');
    });
}

function renderTable() {
    const q = $('#searchBox').val().toLowerCase();
    const s = $('#statusFilter').val();
    const filtered = insurers.filter(function (r) {
        if (s && r.status !== s) return false;
        if (q && r.name.toLowerCase().indexOf(q) === -1 && (r.short_name || '').toLowerCase().indexOf(q) === -1 && (r.email || '').toLowerCase().indexOf(q) === -1) return false;
        return true;
    });
    let html = '';
    if (!filtered.length) {
        html = '<tr><td colspan="7" class="text-center text-muted py-4">No insurers found.</td></tr>';
    } else {
        $.each(filtered, function (_, r) {
            html += '<tr>' +
                '<td>' + escapeHtml(r.name) + '</td>' +
                '<td>' + escapeHtml(r.short_name || '-') + '</td>' +
                '<td>' + escapeHtml(r.phone || '-') + '</td>' +
                '<td>' + escapeHtml(r.email || '-') + '</td>' +
                '<td>' + escapeHtml(r.contact_person || '-') + '</td>' +
                '<td><span class="badge ' + (r.status === 'active' ? 'bg-success' : 'bg-secondary') + '">' + escapeHtml(r.status) + '</span></td>' +
                '<td>' +
                '<button class="btn btn-outline-primary btn-sm edit-insurer me-1" data-id="' + r.id + '"><i class="bi bi-pencil"></i></button>' +
                '<button class="btn btn-outline-danger btn-sm delete-insurer" data-id="' + r.id + '"><i class="bi bi-trash"></i></button>' +
                '</td></tr>';
        });
    }
    $('#insurerTableBody').html(html);
}

function updateKpis() {
    const total = insurers.length;
    const active = insurers.filter(function (r) { return r.status === 'active'; }).length;
    const inactive = total - active;
    $('#kpiTotal').text(total);
    $('#kpiActive').text(active);
    $('#kpiInactive').text(inactive);
    $('#kpiPolicies').text('-');
}

function openModal(id) {
    editId = id || 0;
    $('#insurer_id').val(editId);
    $('#insurerModalTitle').text(editId ? 'Edit Insurer' : 'Add Insurer');

    if (editId) {
        var r = insurers.find(function (x) { return x.id === editId; });
        if (r) {
            $('#insurer_name').val(r.name);
            $('#insurer_short_name').val(r.short_name || '');
            $('#insurer_address').val(r.address || '');
            $('#insurer_phone').val(r.phone || '');
            $('#insurer_email').val(r.email || '');
            $('#insurer_website').val(r.website || '');
            $('#insurer_contact_person').val(r.contact_person || '');
            $('#insurer_contact_phone').val(r.contact_phone || '');
            $('#insurer_status').val(r.status);
        }
    } else {
        $('#insurer_name, #insurer_short_name, #insurer_address, #insurer_phone, #insurer_email, #insurer_website, #insurer_contact_person, #insurer_contact_phone').val('');
        $('#insurer_status').val('active');
    }

    $('#insurerModal').modal('show');
}

function saveInsurer() {
    const name = $('#insurer_name').val().trim();
    if (!name) { showAlert('Company name is required.', 'warning'); return; }

    const data = {
        action: 'save',
        id: $('#insurer_id').val(),
        name: name,
        short_name: $('#insurer_short_name').val().trim(),
        address: $('#insurer_address').val().trim(),
        phone: $('#insurer_phone').val().trim(),
        email: $('#insurer_email').val().trim(),
        website: $('#insurer_website').val().trim(),
        contact_person: $('#insurer_contact_person').val().trim(),
        contact_phone: $('#insurer_contact_phone').val().trim(),
        status: $('#insurer_status').val(),
    };

    $.post('api/insurers.php', data, function (res) {
        if (res.status !== 'success') { showAlert(res.message, 'danger'); return; }
        $('#insurerModal').modal('hide');
        showAlert(res.message, 'success');
        loadInsurers();
    }, 'json');
}

function deleteInsurer(id) {
    if (!confirm('Delete this insurer?')) return;
    $.post('api/insurers.php', { action: 'delete', id: id }, function (res) {
        if (res.status !== 'success') { showAlert(res.message, 'danger'); return; }
        showAlert(res.message, 'success');
        loadInsurers();
    }, 'json');
}
