$(function () {
    loadRefData();
    loadProviders();
    loadCards();
    loadTransactions();

    $('#filterCardStatus, #filterCardProvider, #filterCardSearch').on('change keyup', function () {
        loadCards();
    });

    $('#btnNewCard').on('click', function () {
        resetCardForm();
        $('#cardModalTitle').text('New Fuel Card');
        $('#cardModal').modal('show');
    });

    $('#cardForm').on('submit', function (e) {
        e.preventDefault();
        saveCard();
    });

    $('#btnNewProvider').on('click', function () {
        resetProviderForm();
        $('#providerModalTitle').text('New Provider');
        $('#providerModal').modal('show');
    });

    $('#providerForm').on('submit', function (e) {
        e.preventDefault();
        saveProvider();
    });

    $('#btnNewTransaction').on('click', function () {
        resetTransactionForm();
        $('#transactionModal').modal('show');
    });

    $('#transactionForm').on('submit', function (e) {
        e.preventDefault();
        saveTransaction();
    });

    $('#card_assigned_to_type').on('change', function () {
        loadAssignOptions();
    });

    $(document).on('click', '.btn-edit-card', function () {
        var id = $(this).data('id');
        loadCard(id);
    });

    $(document).on('click', '.btn-delete-card', function () {
        var id = $(this).data('id');
        if (confirm('Delete this fuel card?')) deleteCard(id);
    });

    $(document).on('click', '.btn-delete-provider', function () {
        var id = $(this).data('id');
        if (confirm('Delete this provider?')) deleteProvider(id);
    });
});

var cardRefData = {};

function loadRefData() {
    $.get('api/fuel_cards.php?action=reference', function (r) {
        if (r.status !== 'success') return;
        cardRefData = r.data;
        var opts = '<option value="">Select provider</option>';
        (r.data.providers || []).forEach(function (p) {
            opts += '<option value="' + p.id + '">' + esc(p.name) + '</option>';
        });
        $('#card_provider_id').html(opts);
        $('#filterCardProvider').html('<option value="">All providers</option>' + opts);
        $('#tx_card_id').html('<option value="">Select card</option>');
    }, 'json');
}

function loadProviders() {
    $.get('api/fuel_cards.php?action=providers', function (r) {
        if (r.status !== 'success') return;
        var rows = r.data || [];
        $('#kpiProviders').text(rows.length);
        var html = '';
        rows.forEach(function (p) {
            html += '<tr><td><strong>' + esc(p.name) + '</strong></td><td>' + esc(p.code || '-') + '</td>' +
                '<td class="text-end"><button class="btn btn-sm btn-outline-danger btn-delete-provider" data-id="' + p.id + '"><i class="bi bi-trash"></i></button></td></tr>';
        });
        if (!html) html = '<tr><td colspan="3" class="text-center text-muted py-3">No providers</td></tr>';
        $('#providersTable').html(html);
    }, 'json');
}

function loadCards() {
    var params = {
        status: $('#filterCardStatus').val(),
        provider_id: $('#filterCardProvider').val(),
        search: $('#filterCardSearch').val()
    };
    $.get('api/fuel_cards.php?action=list', params, function (r) {
        if (r.status !== 'success') return;
        var rows = r.data || [];
        $('#kpiActiveCards').text(r.total_active || 0);
        $('#kpiTotalBalance').text('₦' + formatNum(r.total_balance || 0));
        $('#kpiTotalCards').text(rows.length);

        var html = '';
        rows.forEach(function (c) {
            var cls = c.status === 'active' ? 'success' : (c.status === 'suspended' ? 'warning text-dark' : (c.status === 'expired' ? 'secondary' : 'danger'));
            html += '<tr>' +
                '<td><strong>' + esc(c.card_number_masked) + '</strong></td>' +
                '<td>' + esc(c.provider_name || '-') + '</td>' +
                '<td><span class="badge bg-info">' + esc(c.card_type) + '</span></td>' +
                '<td><small>' + esc(c.assigned_to_name || 'Unassigned') + '</small></td>' +
                '<td class="fw-semibold">₦' + formatNum(c.current_balance || 0) + '</td>' +
                '<td>' + (c.monthly_limit ? '₦' + formatNum(c.monthly_limit) : '-') + '</td>' +
                '<td><span class="badge bg-' + cls + '">' + esc(c.status) + '</span></td>' +
                '<td>' + (c.expiry_date || '-') + '</td>' +
                '<td class="text-end">' +
                '<button class="btn btn-sm btn-outline-primary btn-edit-card me-1" data-id="' + c.id + '"><i class="bi bi-pencil"></i></button>' +
                '<button class="btn btn-sm btn-outline-danger btn-delete-card" data-id="' + c.id + '"><i class="bi bi-trash"></i></button>' +
                '</td></tr>';
        });
        if (!html) html = '<tr><td colspan="9" class="text-center text-muted py-3">No fuel cards found</td></tr>';
        $('#cardsTable').html(html);
    }, 'json');
}

function loadCard(id) {
    $.get('api/fuel_cards.php?action=card', { id: id }, function (r) {
        if (r.status !== 'success') return;
        var c = r.data;
        $('#cardModalTitle').text('Edit Card - ' + esc(c.card_number_masked));
        $('#card_id').val(c.id);
        $('#card_number').val(c.card_number);
        $('#card_type').val(c.card_type || 'physical');
        $('#card_provider_id').val(c.provider_id || '');
        $('#card_status').val(c.status || 'active');
        $('#card_assigned_to_type').val(c.assigned_to_type || 'none');
        loadAssignOptions(function () {
            $('#card_assigned_to_id').val(c.assigned_to_id || '');
        });
        $('#card_current_balance').val(c.current_balance || 0);
        $('#card_monthly_limit').val(c.monthly_limit || '');
        $('#card_per_transaction_limit').val(c.per_transaction_limit || '');
        $('#card_issued_date').val(c.issued_date || '');
        $('#card_expiry_date').val(c.expiry_date || '');
        $('#card_notes').val(c.notes || '');
        $('#cardModal').modal('show');
    }, 'json');
}

function saveCard() {
    var data = $('#cardForm').serialize();
    $.post('api/fuel_cards.php?action=save', data, function (r) {
        if (r.status !== 'success') { alert(r.message); return; }
        $('#cardModal').modal('hide');
        loadCards();
    }, 'json');
}

function deleteCard(id) {
    $.post('api/fuel_cards.php?action=delete', { id: id, csrf_token: window.CSRF_TOKEN }, function (r) {
        if (r.status !== 'success') { alert(r.message); return; }
        loadCards();
    }, 'json');
}

function resetCardForm() {
    $('#cardForm')[0].reset();
    $('#card_id').val('');
    $('#card_number').val('');
    $('#card_current_balance').val('0');
    $('#card_assigned_to_id').html('<option value="">Select...</option>');
}

function saveProvider() {
    var data = $('#providerForm').serialize();
    $.post('api/fuel_cards.php?action=save_provider', data, function (r) {
        if (r.status !== 'success') { alert(r.message); return; }
        $('#providerModal').modal('hide');
        loadProviders();
        loadRefData();
    }, 'json');
}

function deleteProvider(id) {
    $.post('api/fuel_cards.php?action=delete_provider', { id: id, csrf_token: window.CSRF_TOKEN }, function (r) {
        if (r.status !== 'success') { alert(r.message); return; }
        loadProviders();
        loadRefData();
    }, 'json');
}

function resetProviderForm() {
    $('#providerForm')[0].reset();
    $('#provider_id').val('');
}

function loadTransactions() {
    $.get('api/fuel_cards.php?action=transactions', function (r) {
        if (r.status !== 'success') return;
        var rows = r.data || [];
        var html = '';
        rows.forEach(function (t) {
            var typeCls = t.transaction_type === 'purchase' || t.transaction_type === 'fee' ? 'danger' : 'success';
            html += '<tr>' +
                '<td>' + t.created_at + '</td>' +
                '<td>' + esc(t.card_number_masked) + '</td>' +
                '<td><span class="badge bg-' + typeCls + '">' + esc(t.transaction_type) + '</span></td>' +
                '<td class="fw-semibold">₦' + formatNum(t.amount) + '</td>' +
                '<td>₦' + formatNum(t.balance_before) + '</td>' +
                '<td>₦' + formatNum(t.balance_after) + '</td>' +
                '<td>' + esc(t.reference || '-') + '</td>' +
                '<td><small>' + esc(t.notes || '-') + '</small></td></tr>';
        });
        if (!html) html = '<tr><td colspan="8" class="text-center text-muted py-3">No transactions</td></tr>';
        $('#transactionsTable').html(html);
    }, 'json');
}

function saveTransaction() {
    var data = $('#transactionForm').serialize();
    $.post('api/fuel_cards.php?action=log_transaction', data, function (r) {
        if (r.status !== 'success') { alert(r.message); return; }
        $('#transactionModal').modal('hide');
        loadTransactions();
        loadCards();
    }, 'json');
}

function resetTransactionForm() {
    $('#transactionForm')[0].reset();
    loadCardOptions();
}

function loadCardOptions() {
    $.get('api/fuel_cards.php?action=list', { status: 'active' }, function (r) {
        if (r.status !== 'success') return;
        var opts = '<option value="">Select card</option>';
        (r.data || []).forEach(function (c) {
            opts += '<option value="' + c.id + '">' + esc(c.card_number_masked) + ' (' + esc(c.provider_name || '') + ')</option>';
        });
        $('#tx_card_id').html(opts);
    }, 'json');
}

function loadAssignOptions(callback) {
    var type = $('#card_assigned_to_type').val();
    if (type === 'none') {
        $('#card_assigned_to_id').html('<option value="">Not assigned</option>');
        if (callback) callback();
        return;
    }
    $.get('api/fuel_cards.php?action=assign_options', { assign_type: type }, function (r) {
        if (r.status !== 'success') return;
        var opts = '<option value="">Select...</option>';
        (r.data || []).forEach(function (o) {
            opts += '<option value="' + o.id + '">' + esc(o.label) + '</option>';
        });
        $('#card_assigned_to_id').html(opts);
        if (callback) callback();
    }, 'json');
}

function formatNum(n) {
    n = parseFloat(n) || 0;
    return n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

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