<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('subs.create_subscription') ?></h5></div>
            <div class="card-body">
                <form id="sub-create-form" method="POST" action="/subscriptions" data-ajax="true">
                    <?= csrf_field() ?>
                    <!-- Member Lookup -->
                    <div class="mb-3">
                        <label class="form-label"><?= lang('subs.member') ?> <span class="text-danger">*</span></label>
                        <select name="member_id" id="member-select" class="form-select select2" style="width:100%"
                                data-placeholder="Search member..." required>
                            <?php if ($member): ?>
                            <option value="<?= $member['id'] ?>" selected><?= e($member['membership_number'] . ' - ' . $member['full_name_en']) ?></option>
                            <?php endif; ?>
                        </select>
                        <div class="invalid-feedback" data-field="member_id"></div>
                    </div>
                    <!-- Period -->
                    <div class="mb-3">
                        <label class="form-label"><?= lang('subs.period') ?> <span class="text-danger">*</span></label>
                        <select name="subscription_period_id" id="period-select" class="form-select" required>
                            <option value="">-- Select Period --</option>
                            <?php foreach ($periods as $p): ?>
                            <option value="<?= $p['id'] ?>" data-start="<?= $p['start_date'] ?>" data-end="<?= $p['end_date'] ?>">
                                <?= e($p['name_en'] . ' (' . $p['start_date'] . ' → ' . $p['end_date'] . ')') ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                        <div class="invalid-feedback" data-field="subscription_period_id"></div>
                    </div>
                    <!-- Fee Calculation -->
                    <div id="fee-section" class="d-none">
                        <div class="card bg-light mb-3">
                            <div class="card-body">
                                <div class="row g-2">
                                    <div class="col-md-4"><label class="form-label">Base Amount</label><input type="text" class="form-control-plaintext fw-bold" id="disp-base" readonly></div>
                                    <div class="col-md-4"><label class="form-label">Dependents (<span id="disp-dep-count">0</span>)</label><input type="text" class="form-control-plaintext" id="disp-dep" readonly></div>
                                    <div class="col-md-4"><label class="form-label">Late Fee</label><input type="text" class="form-control-plaintext text-danger" id="disp-late" readonly></div>
                                </div>
                                <hr>
                                <div class="row g-2">
                                    <div class="col-md-6"><label class="form-label">Discount</label>
                                        <input type="number" step="0.01" min="0" name="discount_amount" id="discount-input" class="form-control" value="0">
                                    </div>
                                    <div class="col-md-6"><label class="form-label fw-bold">Total</label>
                                        <input type="text" class="form-control-plaintext fs-4 fw-bold text-primary" id="disp-total" readonly>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <input type="hidden" name="amount" id="amount-input">
                        <input type="hidden" name="dependents_amount" id="dep-amount-input">
                        <input type="hidden" name="late_fee" id="late-fee-input">
                    </div>
                    <!-- Notes -->
                    <div class="mb-3">
                        <label class="form-label"><?= lang('subs.notes') ?></label>
                        <textarea name="notes" class="form-control" rows="2"></textarea>
                    </div>
                    <div class="d-flex gap-2">
                        <button type="submit" class="btn btn-primary" id="btn-submit-sub" disabled>
                            <i class="fas fa-save me-1"></i><?= lang('common.save') ?>
                        </button>
                        <a href="/subscriptions" class="btn btn-secondary"><?= lang('common.cancel') ?></a>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<?php $__view->push('scripts') ?>
<script>
$(function(){
    // Member Select2 AJAX
    $('#member-select').select2({
        theme: 'bootstrap-5', width: '100%', minimumInputLength: 2, allowClear: true,
        ajax: {
            url: '/api/members/search',
            dataType: 'json', delay: 300,
            data: function(params){ return { q: params.term }; },
            processResults: function(data){
                return { results: (data.data || data).map(function(m){
                    return { id: m.id, text: m.membership_number + ' - ' + m.name };
                })};
            }
        }
    });

    function calculateFee(){
        var memberId = $('#member-select').val();
        var periodId = $('#period-select').val();
        if(!memberId || !periodId){ $('#fee-section').addClass('d-none'); $('#btn-submit-sub').prop('disabled',true); return; }

        $.get('/api/subscriptions/calculate-fee', { member_id: memberId, period_id: periodId }, function(res){
            if(res.success){
                var d = res;
                $('#disp-base').val(d.base_amount.toFixed(2) + ' EGP');
                $('#disp-dep-count').text(d.dep_count);
                $('#disp-dep').val(d.dep_amount.toFixed(2) + ' EGP');
                $('#disp-late').val(d.late_fee.toFixed(2) + ' EGP');
                $('#amount-input').val(d.base_amount);
                $('#dep-amount-input').val(d.dep_amount);
                $('#late-fee-input').val(d.late_fee);
                updateTotal();
                $('#fee-section').removeClass('d-none');
                $('#btn-submit-sub').prop('disabled', false);
            }
        });
    }

    function updateTotal(){
        var base = parseFloat($('#amount-input').val()) || 0;
        var dep  = parseFloat($('#dep-amount-input').val()) || 0;
        var late = parseFloat($('#late-fee-input').val()) || 0;
        var disc = parseFloat($('#discount-input').val()) || 0;
        var total = base + dep + late - disc;
        $('#disp-total').val(total.toFixed(2) + ' EGP');
    }

    $('#member-select, #period-select').on('change', calculateFee);
    $('#discount-input').on('input', updateTotal);

    <?php if ($member): ?>
    setTimeout(calculateFee, 300);
    <?php endif; ?>
});
</script>
<?php $__view->endPush() ?>