<div class="d-flex justify-content-between align-items-center mb-4">
    <h4 class="mb-0"><i class="fas fa-print me-2"></i><?= lang('cards.print_batches') ?></h4>
    <form method="POST" action="/cards/print-batches" id="createBatchForm">
        <?= csrf_field() ?>
        <button type="submit" class="btn btn-primary"><i class="fas fa-plus me-1"></i>Create Batch from Approved Requests</button>
    </form>
</div>

<div class="card">
    <div class="card-body">
        <table id="printTable" class="table table-striped table-hover w-100">
            <thead><tr><th>#</th><th>Batch #</th><th>Date</th><th>Total</th><th>Printed</th><th>Failed</th><th>Status</th><th>Printed By</th><th>Actions</th></tr></thead>
        </table>
    </div>
</div>

<div class="modal fade" id="batchItemsModal" tabindex="-1">
    <div class="modal-dialog modal-lg"><div class="modal-content">
        <div class="modal-header"><h5 class="modal-title">Batch Items</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
        <div class="modal-body" id="batchItemsBody"><div class="text-center py-3"><div class="spinner-border"></div></div></div>
    </div></div>
</div>

<?php $__view->push('scripts') ?>
<script>
$(function(){
    const dt = $('#printTable').DataTable({
        processing: true, serverSide: true,
        ajax: { url: '/api/cards/print-batches/datatable', type: 'GET' },
        columns: [
            { data: 'id' },
            { data: 'batch_number', render: function(d){ return `<strong>${d}</strong>`; }},
            { data: 'batch_date' },
            { data: 'total_cards' },
            { data: 'printed_cards' },
            { data: 'failed_cards' },
            { data: 'status', render: function(d){ const m = {pending:'warning',printing:'info',completed:'success',partial:'warning',cancelled:'dark'}; return `<span class="badge bg-${m[d]||'secondary'}">${d}</span>`; }},
            { data: 'printed_by_name', render: function(d){ return d || '-'; }},
            { data: 'id', orderable: false, render: function(d,t,r){
                let btns = `<button class="btn btn-sm btn-outline-info me-1 btn-view-items" data-id="${d}"><i class="fas fa-list"></i></button>`;
                if(r.status === 'pending' || r.status === 'partial'){
                    btns += `<button class="btn btn-sm btn-success btn-process" data-id="${d}"><i class="fas fa-print"></i> Process</button>`;
                }
                return btns;
            }}
        ],
        order: [[0, 'desc']], pageLength: 25
    });

    $('#createBatchForm').on('submit', function(e){
        e.preventDefault();
        $.post($(this).attr('action'), $(this).serialize(), function(res){
            if(res.success){ Swal.fire({icon:'success',title:res.message,timer:1500,showConfirmButton:false}); dt.ajax.reload(); }
            else { Swal.fire({icon:'error',title:'Error',text:res.message}); }
        });
    });

    $(document).on('click', '.btn-process', function(){
        const id = $(this).data('id');
        Swal.fire({title:'Process Batch?',text:'Mark all pending items as printed?',icon:'question',showCancelButton:true,confirmButtonText:'Process'}).then(r=>{
            if(r.isConfirmed){
                $.post('/cards/print-batches/'+id+'/process', {_token: $('meta[name="csrf-token"]').attr('content')}, function(res){
                    if(res.success){ Swal.fire({icon:'success',title:res.message,timer:1500,showConfirmButton:false}); dt.ajax.reload(); }
                    else { Swal.fire({icon:'error',title:'Error',text:res.message}); }
                });
            }
        });
    });

    $(document).on('click', '.btn-view-items', function(){
        const id = $(this).data('id');
        $('#batchItemsBody').html('<div class="text-center py-3"><div class="spinner-border"></div></div>');
        new bootstrap.Modal('#batchItemsModal').show();
        $.get('/api/cards/print-batches/'+id+'/items', function(res){
            if(res.success && res.data.length){
                let html = '<table class="table table-sm"><thead><tr><th>Card #</th><th>Member</th><th>Status</th></tr></thead><tbody>';
                res.data.forEach(i => { html += `<tr><td>${i.card_number||'-'}</td><td>${i.member_name_en||''} (${i.membership_number||''})</td><td><span class="badge bg-${i.print_status==='printed'?'success':'warning'}">${i.print_status}</span></td></tr>`; });
                html += '</tbody></table>';
                $('#batchItemsBody').html(html);
            } else { $('#batchItemsBody').html('<p class="text-center text-muted">No items</p>'); }
        });
    });
});
</script>
<?php $__view->endPush() ?>