<div class="d-flex justify-content-between align-items-center mb-4">
    <h4 class="mb-0"><i class="fas fa-clipboard-list me-2"></i><?= lang('cards.card_requests') ?></h4>
    <?php if (auth_can('cards.manage')): ?>
    <a href="/cards/requests/create" class="btn btn-primary"><i class="fas fa-plus me-1"></i><?= lang('cards.new_request') ?></a>
    <?php endif; ?>
</div>

<div class="card mb-3">
    <div class="card-body">
        <div class="row g-2">
            <div class="col-md-3">
                <select id="filter-req-status" class="form-select form-select-sm">
                    <option value="">All Statuses</option>
                    <option value="pending">Pending</option>
                    <option value="approved">Approved</option>
                    <option value="in_production">In Production</option>
                    <option value="ready">Ready</option>
                    <option value="delivered">Delivered</option>
                    <option value="rejected">Rejected</option>
                </select>
            </div>
        </div>
    </div>
</div>

<div class="card">
    <div class="card-body">
        <table id="requestsTable" class="table table-striped table-hover w-100">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Request #</th>
                    <th><?= lang('cards.member') ?></th>
                    <th><?= lang('cards.type') ?></th>
                    <th>Request Type</th>
                    <th>Fee</th>
                    <th><?= lang('common.status') ?></th>
                    <th>Date</th>
                    <th><?= lang('common.actions') ?></th>
                </tr>
            </thead>
        </table>
    </div>
</div>

<!-- Approve/Reject Modals -->
<div class="modal fade" id="approveModal" tabindex="-1">
    <div class="modal-dialog"><div class="modal-content">
        <div class="modal-header"><h5 class="modal-title">Approve Request</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
        <div class="modal-body"><p>Approve this card request and issue the card?</p></div>
        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?= lang('common.cancel') ?></button>
            <button type="button" class="btn btn-success" id="confirmApprove"><i class="fas fa-check me-1"></i>Approve & Issue Card</button>
        </div>
    </div></div>
</div>

<div class="modal fade" id="rejectModal" tabindex="-1">
    <div class="modal-dialog"><div class="modal-content">
        <form id="rejectForm">
            <?= csrf_field() ?>
            <div class="modal-header"><h5 class="modal-title">Reject Request</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <div class="mb-3"><label class="form-label">Reason</label><textarea name="reason" class="form-control" rows="3"></textarea></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?= lang('common.cancel') ?></button>
                <button type="submit" class="btn btn-danger"><i class="fas fa-times me-1"></i>Reject</button>
            </div>
        </form>
    </div></div>
</div>

<div class="modal fade" id="deliverModal" tabindex="-1">
    <div class="modal-dialog"><div class="modal-content">
        <form id="deliverForm">
            <?= csrf_field() ?>
            <div class="modal-header"><h5 class="modal-title">Mark as Delivered</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <div class="mb-3"><label class="form-label">Delivered To</label><input type="text" name="delivered_to" class="form-control" placeholder="Name of person receiving the card"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?= lang('common.cancel') ?></button>
                <button type="submit" class="btn btn-primary"><i class="fas fa-hand-holding me-1"></i>Confirm Delivery</button>
            </div>
        </form>
    </div></div>
</div>

<?php $__view->push('scripts') ?>
<script>
let activeReqId = null;

const dt = $('#requestsTable').DataTable({
    processing: true, serverSide: true,
    ajax: {
        url: '/api/cards/requests/datatable', type: 'GET',
        data: function(d){ d.status = $('#filter-req-status').val(); }
    },
    columns: [
        { data: 'id' },
        { data: 'request_number', render: function(d){ return `<strong>${d}</strong>`; }},
        { data: 'member_name_en', render: function(d,t,r){ return `${r.member_name_en || ''}<br><small class="text-muted">${r.membership_number || ''}</small>`; }},
        { data: 'type_name_en' },
        { data: 'request_type', render: function(d){ const m = {'new':'primary','replacement':'warning','renewal':'info'}; return `<span class="badge bg-${m[d]||'secondary'}">${d}</span>`; }},
        { data: 'fee_amount', render: function(d,t,r){ return parseFloat(d).toFixed(2) + (r.fee_paid == 1 ? ' <i class="fas fa-check text-success"></i>' : ''); }},
        { data: 'status', render: function(d){ const m = {pending:'warning',approved:'success',in_production:'info',ready:'primary',delivered:'success',rejected:'danger',cancelled:'dark'}; return `<span class="badge bg-${m[d]||'secondary'}">${d}</span>`; }},
        { data: 'created_at', render: function(d){ return d ? d.substring(0,10) : ''; }},
        { data: 'id', orderable: false, render: function(d,t,r){
            let btns = '';
            if(r.status === 'pending'){
                btns += `<button class="btn btn-sm btn-success me-1 btn-approve" data-id="${d}" title="Approve"><i class="fas fa-check"></i></button>`;
                btns += `<button class="btn btn-sm btn-danger me-1 btn-reject" data-id="${d}" title="Reject"><i class="fas fa-times"></i></button>`;
            }
            if(['approved','in_production','ready'].includes(r.status)){
                btns += `<button class="btn btn-sm btn-primary btn-deliver" data-id="${d}" title="Deliver"><i class="fas fa-hand-holding"></i></button>`;
            }
            return btns || '-';
        }}
    ],
    order: [[0, 'desc']], pageLength: 25
});

$('#filter-req-status').on('change', function(){ dt.ajax.reload(); });

$(document).on('click', '.btn-approve', function(){ activeReqId = $(this).data('id'); new bootstrap.Modal('#approveModal').show(); });
$(document).on('click', '.btn-reject', function(){ activeReqId = $(this).data('id'); new bootstrap.Modal('#rejectModal').show(); });
$(document).on('click', '.btn-deliver', function(){ activeReqId = $(this).data('id'); new bootstrap.Modal('#deliverModal').show(); });

$('#confirmApprove').on('click', function(){
    $.post('/cards/requests/'+activeReqId+'/approve', {_token: $('meta[name="csrf-token"]').attr('content')}, function(res){
        bootstrap.Modal.getInstance('#approveModal').hide();
        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}); }
    });
});

$('#rejectForm').on('submit', function(e){
    e.preventDefault();
    $.post('/cards/requests/'+activeReqId+'/reject', $(this).serialize(), function(res){
        bootstrap.Modal.getInstance('#rejectModal').hide();
        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}); }
    });
});

$('#deliverForm').on('submit', function(e){
    e.preventDefault();
    $.post('/cards/requests/'+activeReqId+'/deliver', $(this).serialize(), function(res){
        bootstrap.Modal.getInstance('#deliverModal').hide();
        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}); }
    });
});
</script>
<?php $__view->endPush() ?>