<?php
$pageTitle = 'Manage Cards';
require_once __DIR__ . '/includes/header.php';
?>

<style>
#tblCards th, #tblCards td { vertical-align: middle; }
.badge-active   { background:#16a34a; }
.badge-inactive { background:#dc2626; }
.btn-toggle-active   { --bs-btn-color:#fff; --bs-btn-bg:#dc2626; --bs-btn-border-color:#dc2626; }
.btn-toggle-inactive { --bs-btn-color:#fff; --bs-btn-bg:#16a34a; --bs-btn-border-color:#16a34a; }
</style>

<div class="d-flex align-items-center gap-3 flex-wrap mb-4">
    <h4 class="mb-0">
        <i class="bi bi-credit-card-2-front me-2 text-primary"></i>Manage Cards
    </h4>
    <span class="badge bg-light text-dark border fs-6" id="totalCount">Loading…</span>
</div>

<!-- Search + Filter -->
<div class="card shadow-sm mb-3">
    <div class="card-body py-2">
        <div class="d-flex gap-2 flex-wrap align-items-center">
            <div class="input-group" style="max-width:340px">
                <span class="input-group-text"><i class="bi bi-search"></i></span>
                <input type="text" class="form-control" id="searchInput"
                       placeholder="Search card code or member name…">
            </div>
            <select class="form-select" id="filterStatus" style="max-width:160px">
                <option value="">All Status</option>
                <option value="active">Active</option>
                <option value="inactive">Deactivated</option>
            </select>
            <select class="form-select" id="filterReg" style="max-width:180px">
                <option value="">All Cards</option>
                <option value="registered">Registered</option>
                <option value="unregistered">Unregistered</option>
            </select>
            <button class="btn btn-outline-secondary btn-sm" id="btnRefresh">
                <i class="bi bi-arrow-clockwise me-1"></i>Refresh
            </button>
        </div>
    </div>
</div>

<!-- Bootstrap Confirm Modal -->
<div class="modal fade" id="confirmModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header border-0 pb-0">
                <h5 class="modal-title fw-bold" id="confirmTitle">Confirm Action</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body pt-2" id="confirmBody"></div>
            <div class="modal-footer border-0 pt-0">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn" id="confirmOkBtn">Confirm</button>
            </div>
        </div>
    </div>
</div>

<!-- Toast notification -->
<div class="position-fixed top-0 end-0 p-3" style="z-index:9999">
    <div id="toast" class="toast align-items-center border-0" role="alert">
        <div class="d-flex">
            <div class="toast-body fw-semibold" id="toastMsg"></div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto"
                    data-bs-dismiss="toast"></button>
        </div>
    </div>
</div>

<!-- Cards table -->
<div class="card shadow-sm">
    <div class="table-responsive">
        <table class="table table-hover align-middle mb-0" id="tblCards">
            <thead class="table-light">
                <tr>
                    <th>#</th>
                    <th>Card Code</th>
                    <th>Member Name</th>
                    <th>Points</th>
                    <th>Registered</th>
                    <th>Status</th>
                    <th>Created</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody id="cardBody">
                <tr>
                    <td colspan="8" class="text-center text-muted py-4">
                        <span class="spinner-border spinner-border-sm me-2"></span>Loading…
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

<div id="noResults" class="text-center text-muted py-5" style="display:none">
    <i class="bi bi-search fs-2 d-block mb-2 opacity-50"></i>
    No cards match your search.
</div>

<?php
$extraJS = '<script>var BASE_URL=' . json_encode(BASE_URL) . ';</script>' . <<<'ENDJS'
<script>
var allCards = [];
var toast    = new bootstrap.Toast(document.getElementById('toast'), { delay: 3000 });

function showToast(msg, type) {
    var el = document.getElementById('toast');
    el.className = 'toast align-items-center border-0 text-bg-' + (type || 'success');
    document.getElementById('toastMsg').textContent = msg;
    toast.show();
}

function loadCards() {
    document.getElementById('cardBody').innerHTML =
        '<tr><td colspan="8" class="text-center text-muted py-4">' +
        '<span class="spinner-border spinner-border-sm me-2"></span>Loading…</td></tr>';

    $.getJSON(BASE_URL + '/ajax/get_all_cards.php', function(res) {
        if (!res.success) {
            document.getElementById('cardBody').innerHTML =
                '<tr><td colspan="8" class="text-danger text-center py-3">Failed to load cards.</td></tr>';
            return;
        }
        allCards = res.cards;
        document.getElementById('totalCount').textContent = res.cards.length + ' cards total';
        applyFilters();
    });
}

function applyFilters() {
    var q      = document.getElementById('searchInput').value.trim().toLowerCase();
    var status = document.getElementById('filterStatus').value;
    var reg    = document.getElementById('filterReg').value;

    var filtered = allCards.filter(function(c) {
        var matchQ = !q ||
            c.card_code.toLowerCase().includes(q) ||
            (c.name || '').toLowerCase().includes(q);
        var matchStatus = !status || (c.status || 'active') === status;
        var matchReg = !reg ||
            (reg === 'registered'   &&  c.name) ||
            (reg === 'unregistered' && !c.name);
        return matchQ && matchStatus && matchReg;
    });

    renderTable(filtered);
}

function renderTable(cards) {
    var tbody    = document.getElementById('cardBody');
    var noResult = document.getElementById('noResults');

    if (!cards.length) {
        tbody.innerHTML = '';
        noResult.style.display = 'block';
        return;
    }
    noResult.style.display = 'none';

    var rows = '';
    cards.forEach(function(c, i) {
        var isActive = (c.status || 'active') === 'active';
        var isReg    = !!c.name;
        var date     = (c.created_at || '').substring(0, 10);
        var pts      = Number(c.points || 0).toLocaleString();

        rows += '<tr data-code="' + c.card_code + '">' +
            '<td class="text-muted small">' + (i + 1) + '</td>' +
            '<td><code class="small">' + c.card_code + '</code></td>' +
            '<td>' + (c.name || '<span class="text-muted fst-italic">—</span>') + '</td>' +
            '<td class="text-end small">' + pts + '</td>' +
            '<td>' + (isReg
                ? '<span class="badge bg-success-subtle text-success-emphasis">Registered</span>'
                : '<span class="badge bg-secondary-subtle text-secondary-emphasis">Unregistered</span>') + '</td>' +
            '<td>' + (isActive
                ? '<span class="badge badge-active">Active</span>'
                : '<span class="badge badge-inactive">Deactivated</span>') + '</td>' +
            '<td class="text-muted small">' + date + '</td>' +
            '<td>' +
                '<button class="btn btn-sm ' + (isActive ? 'btn-outline-danger' : 'btn-outline-success') +
                '" data-code="' + c.card_code + '" data-status="' + (isActive ? 'active' : 'inactive') + '">' +
                '<i class="bi bi-' + (isActive ? 'slash-circle' : 'check-circle') + ' me-1"></i>' +
                (isActive ? 'Deactivate' : 'Activate') +
                '</button>' +
            '</td>' +
            '</tr>';
    });
    tbody.innerHTML = rows;

    // Bind toggle buttons
    tbody.querySelectorAll('[data-status]').forEach(function(btn) {
        btn.addEventListener('click', function() { toggleCard(btn.dataset.code, btn); });
    });
}

var _confirmModal    = null;
var _confirmCallback = null;

function showConfirm(opts, callback) {
    if (!_confirmModal) _confirmModal = new bootstrap.Modal(document.getElementById('confirmModal'));
    document.getElementById('confirmTitle').textContent = opts.title || 'Confirm';
    document.getElementById('confirmBody').innerHTML    = opts.body  || '';
    var okBtn = document.getElementById('confirmOkBtn');
    okBtn.textContent = opts.btnText || 'Confirm';
    okBtn.className   = 'btn ' + (opts.btnClass || 'btn-primary');
    _confirmCallback  = callback;
    _confirmModal.show();
}

document.getElementById('confirmOkBtn').addEventListener('click', function() {
    _confirmModal.hide();
    if (_confirmCallback) _confirmCallback();
    _confirmCallback = null;
});

function toggleCard(code, btn) {
    // data-status is 'active' or 'inactive' — what the card IS right now
    var currentStatus  = btn.dataset.status;
    var cardIsActive   = currentStatus === 'active';

    // What we're DOING: if card is active → we deactivate it, and vice versa
    var action         = cardIsActive ? 'deactivate' : 'activate';
    var actionLabel    = cardIsActive ? 'Deactivate' : 'Activate';
    var icon           = cardIsActive ? 'slash-circle'       : 'check-circle-fill';
    var iconColor      = cardIsActive ? 'text-danger'        : 'text-success';
    var btnClass       = cardIsActive ? 'btn-danger'         : 'btn-success';
    var note           = cardIsActive
        ? 'The cardholder will not be able to earn or redeem points until reactivated.'
        : 'The cardholder will be able to earn and redeem points again.';

    showConfirm({
        title:    actionLabel + ' Card',
        body:     '<div class="d-flex align-items-start gap-3">' +
                      '<i class="bi bi-' + icon + ' fs-3 ' + iconColor + ' flex-shrink-0 mt-1"></i>' +
                      '<div>' +
                          '<p class="mb-1">Are you sure you want to <strong>' + action + '</strong> this card?</p>' +
                          '<code class="small">' + code + '</code>' +
                          '<p class="text-muted small mt-2 mb-0">' + note + '</p>' +
                      '</div>' +
                  '</div>',
        btnText:  'Yes, ' + actionLabel,
        btnClass: btnClass
    }, function() {
        btn.disabled = true;
        btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span>';

        $.post(BASE_URL + '/ajax/toggle_card_status.php', { card_code: code }, function(res) {
            if (res.success) {
                // Update local data so re-render shows correct status
            var card = allCards.find(function(ac) { return ac.card_code === code; });
            if (card) card.status = res.new_status;
                showToast(res.message, res.is_active ? 'success' : 'danger');
                applyFilters();
            } else {
                showToast(res.error || 'Error toggling card.', 'danger');
                btn.disabled = false;
            }
        }, 'json').fail(function() {
            showToast('Server error. Please try again.', 'danger');
            btn.disabled = false;
        });
    });
}

// Filter listeners
document.getElementById('searchInput').addEventListener('input', applyFilters);
document.getElementById('filterStatus').addEventListener('change', applyFilters);
document.getElementById('filterReg').addEventListener('change', applyFilters);
document.getElementById('btnRefresh').addEventListener('click', loadCards);

// Boot
loadCards();
</script>
ENDJS;
require_once __DIR__ . '/includes/footer.php';
