<?php
$isEdit = !is_null($contribution);
$isAddPayment = !empty($isAddPayment);
$title = $isAddPayment ? 'Add Installment Payment' : ($isEdit ? 'Edit Contribution' : 'Record Contribution');
$isPartial = $isEdit && ($contribution->balance ?? 0) > 0;
?>
<div class="d-sm-flex align-items-center justify-content-between mb-4">
    <h1 class="h3 mb-0 text-white font-weight-bold"><i class="fas fa-<?= $isAddPayment ? 'plus-circle' : ($isEdit ? 'edit' : 'plus') ?> mr-2"></i><?= $title ?></h1>
</div>

<?php if (!empty($relatedPayments)): ?>
<div class="glass-card mb-4">
    <h5 class="font-weight-bold mb-3"><i class="fas fa-history mr-2"></i>Installment Payments for This Obligation</h5>
    <div class="glass-table">
        <table class="table table-sm">
            <thead><tr><th>#</th><th>Date</th><th>Amount</th><th>Method</th><th>Balance After</th><th>Status</th></tr></thead>
            <tbody>
                <?php $i = 1; $totalPaid = 0; ?>
                <?php foreach ($relatedPayments as $rp): ?>
                <tr>
                    <td><?= $i++ ?></td>
                    <td><?= date('M d, Y', strtotime($rp->payment_date)) ?></td>
                    <td><strong>GHS <?= number_format($rp->amount, 2) ?></strong></td>
                    <td><?= htmlspecialchars(ucwords(str_replace('_', ' ', $rp->payment_method ?? '-'))) ?></td>
                    <td>GHS <?= number_format($rp->balance ?? 0, 2) ?></td>
                    <td><span class="glass-badge" style="background: <?= $rp->status === 'completed' ? 'rgba(28,200,138,0.2)' : ($rp->status === 'partial' ? 'rgba(246,194,62,0.2)' : 'rgba(255,255,255,0.1)') ?>; color: <?= $rp->status === 'completed' ? '#1cc88a' : ($rp->status === 'partial' ? '#f6c23e' : 'rgba(255,255,255,0.5)') ?>;"><?= htmlspecialchars(ucfirst($rp->status)) ?></span></td>
                </tr>
                <?php $totalPaid += $rp->amount; ?>
                <?php endforeach; ?>
            </tbody>
            <tfoot>
                <tr style="font-weight: bold;">
                    <td colspan="2" class="text-right">Total Paid:</td>
                    <td>GHS <?= number_format($totalPaid, 2) ?></td>
                    <td></td>
                    <td>Balance: GHS <?= number_format(end($relatedPayments)->balance ?? ($contribution->balance ?? 0), 2) ?></td>
                    <td></td>
                </tr>
            </tfoot>
        </table>
    </div>
</div>
<?php endif; ?>

<div class="glass-card">
    <form method="POST" action="<?= $baseUrl ?>/contributions/<?= $isEdit ? $contribution->id . '/update' : 'store' ?>">
        <?php if ($isAddPayment): ?>
        <input type="hidden" name="user_id" value="<?= $contribution->user_id ?>">
        <input type="hidden" name="contribution_type_id" value="<?= $contribution->contribution_type_id ?>">
        <input type="hidden" name="paid_month" value="<?= htmlspecialchars($contribution->paid_month) ?>">
        <?php endif; ?>
        <div class="form-group">
            <label style="color: rgba(255,255,255,0.7);">Member</label>
            <?php if ($isAddPayment): ?>
            <input type="text" class="form-control glass-input" value="<?= htmlspecialchars($contribution->first_name ? trim($contribution->first_name . ' ' . $contribution->last_name) : $contribution->name) ?>" disabled>
            <input type="hidden" name="user_id" value="<?= $contribution->user_id ?>">
            <?php else: ?>
            <div style="position: relative;">
                <input type="text" id="member-search" class="form-control glass-input" placeholder="Search by name, email or phone..." autocomplete="off" required>
                <input type="hidden" name="user_id" id="member-id" value="<?= ($isEdit && isset($contribution->user_id)) ? $contribution->user_id : '' ?>">
                <div id="member-search-results" style="position: absolute; top: 100%; left: 0; right: 0; z-index: 1000; background: rgba(15,12,41,0.98); border: 1px solid rgba(78,115,223,0.3); border-radius: 0 0 12px 12px; max-height: 260px; overflow-y: auto; display: none;"></div>
            </div>
            <small style="color: rgba(255,255,255,0.4);">Type to search by name, email address, or phone number</small>
            <?php endif; ?>
        </div>
        <div class="row">
            <div class="col-md-4 form-group">
                <label style="color: rgba(255,255,255,0.7);">Contribution Type</label>
                <select name="contribution_type_id" class="form-control glass-input" required <?= $isAddPayment ? 'disabled' : '' ?>>
                    <option value="">Select Type</option>
                    <?php if (!empty($types)): ?>
                        <?php foreach ($types as $t): ?>
                        <option value="<?= $t->id ?>" data-amount="<?= $t->amount ?>" <?= (($isEdit || $isAddPayment) && ($contribution->contribution_type_id ?? 0) == $t->id) ? 'selected' : '' ?>><?= htmlspecialchars($t->name) ?> - GHS <?= number_format($t->amount, 2) ?> (<?= $t->frequency ?>)</option>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </select>
            </div>
            <div class="col-md-4 form-group">
                <label style="color: rgba(255,255,255,0.7);">Total Obligation Amount (GHS)</label>
                <input type="number" step="0.01" name="total_amount" id="totalAmount" class="form-control glass-input" value="<?= ($isEdit || $isAddPayment) && ($contribution->total_amount ?? 0) > 0 ? number_format($contribution->total_amount, 2, '.', '') : '' ?>" placeholder="Full amount due">
            </div>
            <div class="col-md-4 form-group">
                <label style="color: rgba(255,255,255,0.7);">Amount Paid (GHS)</label>
                <input type="number" step="0.01" name="amount" class="form-control glass-input" value="<?= ($isEdit && !$isAddPayment) ? number_format($contribution->amount, 2, '.', '') : '' ?>" required>
            </div>
        </div>
        <div class="row">
            <div class="col-md-3 form-group">
                <label style="color: rgba(255,255,255,0.7);">Payment Date</label>
                <input type="date" name="payment_date" class="form-control glass-input" value="<?= ($isEdit || $isAddPayment) ? $contribution->payment_date : date('Y-m-d') ?>" required>
            </div>
            <div class="col-md-3 form-group">
                <label style="color: rgba(255,255,255,0.7);">Payment Month <small style="color: rgba(255,255,255,0.4);">(for tracking)</small></label>
                <input type="month" name="paid_month" class="form-control glass-input" value="<?= ($isEdit || $isAddPayment) ? ($contribution->paid_month ?? date('Y-m')) : date('Y-m') ?>" <?= $isAddPayment ? 'disabled' : '' ?>>
            </div>
            <div class="col-md-3 form-group">
                <label style="color: rgba(255,255,255,0.7);">Payment Method</label>
                <select name="payment_method" class="form-control glass-input">
                    <option value="">Select</option>
                    <?php foreach (['cash' => 'Cash', 'mobile_money' => 'Mobile Money', 'bank_transfer' => 'Bank Transfer', 'cheque' => 'Cheque', 'card' => 'Card'] as $val => $label): ?>
                    <option value="<?= $val ?>" <?= (($isEdit || $isAddPayment) && $contribution->payment_method === $val) ? 'selected' : '' ?>><?= $label ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3 form-group">
                <label style="color: rgba(255,255,255,0.7);">Status</label>
                <select name="status" class="form-control glass-input">
                    <option value="pending" <?= (($isEdit || $isAddPayment) && $contribution->status === 'pending') ? 'selected' : '' ?>>Pending</option>
                    <option value="completed" <?= (($isEdit || $isAddPayment) && $contribution->status === 'completed') ? 'selected' : '' ?>>Completed</option>
                    <option value="partial" <?= (($isEdit || $isAddPayment) && $contribution->status === 'partial') ? 'selected' : '' ?>>Partial</option>
                </select>
            </div>
        </div>
        <?php if ($isPartial || ($contribution->balance ?? 0) > 0): ?>
        <div class="form-group">
            <div style="padding: 15px; background: rgba(246,194,62,0.1); border: 1px solid rgba(246,194,62,0.3); border-radius: 8px;">
                <div style="display: flex; justify-content: space-between; align-items: center;">
                    <span style="color: #f6c23e;"><i class="fas fa-exclamation-triangle mr-1"></i>Outstanding Balance</span>
                    <span style="color: #fff; font-weight: 700; font-size: 1.2rem;">GHS <?= number_format($contribution->balance ?? 0, 2) ?></span>
                </div>
            </div>
        </div>
        <?php endif; ?>
        <div class="row">
            <div class="col-md-6 form-group">
                <label style="color: rgba(255,255,255,0.7);">Transaction Reference</label>
                <input type="text" name="transaction_ref" class="form-control glass-input" value="<?= ($isEdit || $isAddPayment) ? htmlspecialchars($contribution->transaction_ref ?? '') : '' ?>">
            </div>
            <div class="col-md-6 form-group">
                <label style="color: rgba(255,255,255,0.7);">Notes</label>
                <textarea name="notes" class="form-control glass-input" rows="1"><?= ($isEdit || $isAddPayment) ? htmlspecialchars($contribution->notes ?? '') : '' ?></textarea>
            </div>
        </div>
        <div class="text-right">
            <a href="<?= $baseUrl ?>/contributions" class="glass-btn mr-2">Cancel</a>
            <button type="submit" class="glass-btn glass-btn-primary"><i class="fas fa-<?= $isEdit ? 'save' : 'plus' ?> mr-1"></i><?= $isAddPayment ? 'Add Payment' : ($isEdit ? 'Update' : 'Record') ?> Contribution</button>
        </div>
    </form>
</div>

<script>
$(function() {
    var typeSelect = document.querySelector('select[name="contribution_type_id"]');
    var totalInput = document.getElementById('totalAmount');
    if (typeSelect && totalInput) {
        typeSelect.addEventListener('change', function() {
            var opt = typeSelect.options[typeSelect.selectedIndex];
            if (opt && opt.dataset.amount && !totalInput.value) {
                totalInput.value = opt.dataset.amount;
            }
        });
    }

    var searchInput = $('#member-search');
    var results = $('#member-search-results');
    var hiddenId = $('#member-id');
    var timer;

    <?php if (($isEdit || $isAddPayment) && isset($contribution->user_id)): ?>
    var initialName = '<?= htmlspecialchars(addslashes($contribution->first_name ? trim($contribution->first_name . ' ' . $contribution->last_name) : $contribution->name)) ?>';
    searchInput.val(initialName);
    <?php endif; ?>

    searchInput.on('input', function() {
        var q = $(this).val();
        clearTimeout(timer);
        hiddenId.val('');
        if (q.length < 1) { results.hide(); return; }
        timer = setTimeout(function() {
            $.get('<?= $baseUrl ?>/contributions/search-members', { q: q }, function(data) {
                if (!data.length) { results.html('<div class="result-item" style="color:rgba(255,255,255,0.4);padding:0.6rem 1rem;">No members found</div>').show(); return; }
                var html = '';
                $.each(data, function(i, u) {
                    html += '<div class="result-item" data-id="' + u.id + '" data-name="' + $('<span>').text(u.name).html() + '" data-email="' + u.email + '">';
                    html += '<strong>' + $('<span>').text(u.name).html() + '</strong><br><small>' + u.email + (u.phone ? ' &middot; ' + u.phone : '') + '</small>';
                    html += '</div>';
                });
                results.html(html).show();
                results.find('.result-item').on('click', function() {
                    var id = $(this).data('id');
                    var name = $(this).data('name');
                    searchInput.val(name);
                    hiddenId.val(id);
                    results.hide();
                });
            }, 'json');
        }, 250);
    });

    searchInput.on('blur', function() { setTimeout(function() { results.hide(); }, 200); });
    searchInput.on('focus', function() { if ($(this).val().length > 0 && results.children().length) results.show(); });

    $('form').on('submit', function() {
        if (!hiddenId.val()) {
            alert('Please select a member from the search results');
            searchInput.focus();
            return false;
        }
    });
});
</script>
