<div class="card mb-3">
    <div class="card-header"><h5 class="mb-0"><i class="fas fa-redo me-2"></i><?= lang('subs.bulk_renewal') ?></h5></div>
    <div class="card-body">
        <form id="bulk-renew-form" method="POST" action="/subscriptions/bulk-renew" data-ajax="true">
            <?= csrf_field() ?>
            <div class="row g-3 mb-3">
                <div class="col-md-5">
                    <label class="form-label"><?= lang('subs.period') ?> <span class="text-danger">*</span></label>
                    <select name="period_id" id="bulk-period" class="form-select" required>
                        <option value="">-- Select Period --</option>
                        <?php foreach ($periods as $p): ?>
                        <option value="<?= $p['id'] ?>"><?= e($p['name_en']) ?> (<?= $p['start_date'] ?> → <?= $p['end_date'] ?>)</option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-4">
                    <label class="form-label"><?= lang('subs.membership_type') ?></label>
                    <select id="bulk-type" class="form-select">
                        <option value="">All Types</option>
                        <?php foreach ($types as $t): ?>
                        <option value="<?= $t['id'] ?>"><?= e($t['name_en']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3 d-flex align-items-end">
                    <button type="button" class="btn btn-outline-primary w-100" id="btn-load-eligible">
                        <i class="fas fa-search me-1"></i>Load Eligible Members
                    </button>
                </div>
            </div>

            <div id="eligible-container" class="d-none">
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <div><strong id="eligible-count">0</strong> eligible members</div>
                    <div>
                        <button type="button" class="btn btn-sm btn-outline-secondary" id="btn-select-all">Select All</button>
                        <button type="button" class="btn btn-sm btn-outline-secondary" id="btn-deselect-all">Deselect All</button>
                    </div>
                </div>
                <div class="table-responsive" style="max-height:400px;overflow-y:auto">
                    <table class="table table-sm table-hover" id="eligible-table">
                        <thead class="table-light sticky-top"><tr>
                            <th style="width:40px"><input type="checkbox" id="check-all"></th>
                            <th>Member #</th><th>Name</th><th>Phone</th><th>Type</th><th>Last Sub End</th>
                        </tr></thead>
                        <tbody></tbody>
                    </table>
                </div>
                <hr>
                <button type="submit" class="btn btn-success" id="btn-process-bulk" disabled>
                    <i class="fas fa-check-double me-1"></i>Process Bulk Renewal (<span id="selected-count">0</span> selected)
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Results -->
<div id="bulk-results" class="d-none">
    <div class="alert" id="bulk-results-alert"></div>
    <div id="bulk-errors-list"></div>
</div>

<?php $__view->push('scripts') ?>
<script>
$(function(){
    function updateSelected(){
        var c = $('#eligible-table input[name="member_ids[]"]:checked').length;
        $('#selected-count').text(c);
        $('#btn-process-bulk').prop('disabled', c === 0);
    }

    $('#btn-load-eligible').on('click', function(){
        var periodId = $('#bulk-period').val();
        if(!periodId){ Swal.fire('Error','Select a period','warning'); return; }
        var btn = $(this); btn.prop('disabled',true).html('<i class="fas fa-spinner fa-spin me-1"></i>Loading...');

        $.get('/api/subscriptions/eligible', { period_id: periodId, type_id: $('#bulk-type').val() }, function(res){
            var tbody = $('#eligible-table tbody').empty();
            if(res.data && res.data.length){
                res.data.forEach(function(m){
                    tbody.append('<tr><td><input type="checkbox" name="member_ids[]" value="'+m.id+'"></td>'+
                        '<td>'+m.membership_number+'</td><td>'+m.full_name_en+'</td><td>'+(m.primary_phone||'-')+'</td>'+
                        '<td>'+m.type_name+'</td><td>'+(m.last_sub_end||'None')+'</td></tr>');
                });
                $('#eligible-count').text(res.data.length);
                $('#eligible-container').removeClass('d-none');
            } else {
                $('#eligible-container').addClass('d-none');
                Swal.fire('Info','No eligible members found','info');
            }
            btn.prop('disabled',false).html('<i class="fas fa-search me-1"></i>Load Eligible Members');
        });
    });

    $(document).on('change', '#eligible-table input[type=checkbox]', updateSelected);
    $('#check-all').on('change', function(){ $('#eligible-table input[name="member_ids[]"]').prop('checked', this.checked); updateSelected(); });
    $('#btn-select-all').on('click', function(){ $('#eligible-table input[name="member_ids[]"]').prop('checked',true); $('#check-all').prop('checked',true); updateSelected(); });
    $('#btn-deselect-all').on('click', function(){ $('#eligible-table input[name="member_ids[]"]').prop('checked',false); $('#check-all').prop('checked',false); updateSelected(); });

    // Override form submission to handle bulk result
    $('#bulk-renew-form').attr('data-ajax','false').on('submit', function(e){
        e.preventDefault();
        var btn = $('#btn-process-bulk');
        btn.prop('disabled',true).html('<i class="fas fa-spinner fa-spin me-1"></i>Processing...');

        $.ajax({
            url: $(this).attr('action'), type: 'POST', data: $(this).serialize(),
            headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'), 'X-Requested-With':'XMLHttpRequest'},
            success: function(res){
                var cls = res.failed_count > 0 ? 'alert-warning' : 'alert-success';
                $('#bulk-results-alert').attr('class','alert '+cls).html('<strong>'+res.message+'</strong>');
                if(res.errors && res.errors.length){
                    var html = '<ul class="list-group">';
                    res.errors.forEach(function(e){ html += '<li class="list-group-item list-group-item-danger small">'+e+'</li>'; });
                    html += '</ul>';
                    $('#bulk-errors-list').html(html);
                } else { $('#bulk-errors-list').html(''); }
                $('#bulk-results').removeClass('d-none');
            },
            error: function(){ Swal.fire('Error','Bulk renewal failed','error'); },
            complete: function(){ btn.prop('disabled',false).html('<i class="fas fa-check-double me-1"></i>Process Bulk Renewal (<span id="selected-count">0</span> selected)'); }
        });
    });
});
</script>
<?php $__view->endPush() ?>