<div class="row justify-content-center">
    <div class="col-lg-8">
        <div class="card">
            <div class="card-header"><h5 class="mb-0"><i class="fas fa-plus-circle me-2"></i><?= lang('cards.new_request') ?></h5></div>
            <div class="card-body">
                <form id="requestForm" data-ajax="true">
                    <?= csrf_field() ?>
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label"><?= lang('cards.member') ?> <span class="text-danger">*</span></label>
                            <select name="member_id" class="form-select select2" id="memberSearch" required></select>
                            <div class="invalid-feedback" data-field="member_id"></div>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Request Type <span class="text-danger">*</span></label>
                            <select name="request_type" class="form-select" required>
                                <option value="new">New Card</option>
                                <option value="replacement">Replacement</option>
                                <option value="renewal">Renewal</option>
                            </select>
                            <div class="invalid-feedback" data-field="request_type"></div>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Card Type <span class="text-danger">*</span></label>
                            <select name="card_type_id" class="form-select" required>
                                <option value="">-- Select --</option>
                                <?php foreach ($cardTypes as $ct): ?>
                                <option value="<?= $ct['id'] ?>" data-fee="<?= $ct['fee'] ?>" data-repfee="<?= $ct['replacement_fee'] ?>"><?= e($ct['name_en']) ?> (<?= e($ct['name_ar']) ?>) — Fee: <?= number_format($ct['fee'], 2) ?></option>
                                <?php endforeach; ?>
                            </select>
                            <div class="invalid-feedback" data-field="card_type_id"></div>
                        </div>
                        <div class="col-md-6" id="oldCardGroup" style="display:none;">
                            <label class="form-label">Old Card ID (for replacement)</label>
                            <input type="number" name="old_card_id" class="form-control" placeholder="Old card ID">
                        </div>
                        <div class="col-12">
                            <label class="form-label">Reason / Notes</label>
                            <textarea name="reason" class="form-control" rows="3"></textarea>
                            <div class="invalid-feedback" data-field="reason"></div>
                        </div>
                    </div>
                    <div class="mt-4 d-flex gap-2">
                        <button type="submit" class="btn btn-primary"><i class="fas fa-save me-1"></i><?= lang('common.save') ?></button>
                        <a href="/cards/requests" class="btn btn-secondary"><?= lang('common.cancel') ?></a>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<?php $__view->push('scripts') ?>
<script>
$(function(){
    $('#memberSearch').select2({
        theme: 'bootstrap-5', width: '100%',
        ajax: {
            url: '/api/members/search', dataType: 'json', delay: 300,
            data: function(p){ return {q: p.term}; },
            processResults: function(d){ return {results: d.map(m => ({id: m.id, text: m.membership_number + ' - ' + m.text}))}; }
        },
        minimumInputLength: 2, placeholder: 'Search member...'
    });

    $('[name="request_type"]').on('change', function(){
        $('#oldCardGroup').toggle($(this).val() === 'replacement');
    });

    $('#requestForm').on('submit', function(e){
        e.preventDefault();
        const form = $(this);
        const btn = form.find('[type="submit"]');
        btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-1"></span>Saving...');
        $.ajax({
            url: '/cards/requests', method: 'POST', data: form.serialize(),
            success: function(res){
                if(res.success){
                    Swal.fire({icon:'success',title:res.message,timer:1500,showConfirmButton:false}).then(()=>{ window.location.href = res.redirect || '/cards/requests'; });
                } else {
                    if(res.errors){
                        Object.entries(res.errors).forEach(([k,v])=>{
                            form.find(`[name="${k}"]`).addClass('is-invalid');
                            form.find(`[data-field="${k}"]`).text(Array.isArray(v)?v[0]:v).show();
                        });
                    }
                    if(res.message) Swal.fire({icon:'error',title:'Error',text:res.message});
                }
            },
            complete: function(){ btn.prop('disabled', false).html('<i class="fas fa-save me-1"></i><?= lang("common.save") ?>'); }
        });
    });
});
</script>
<?php $__view->endPush() ?>