<div class="page-header">
    <div>
        <h1>Payment Methods</h1>
        <div class="page-subtitle">Configure available payment methods for purchases and sales.</div>
    </div>
</div>

<div class="card">
    <div class="card-header">
        <h3 class="card-title">Manage Payment Methods</h3>
    </div>
    <div class="card-body">
        <form action="<?= APP_URL ?>/settings/payment-methods/save" method="POST">
            <?= Security::csrfField() ?>
            
            <div class="form-group mb-6">
                <label class="form-label">Available Payment Methods</label>
                <div class="form-hint mb-4">Select the payment methods you want to make available in your system. Drag to reorder.</div>
                
                <div id="payment-methods-list" class="flex flex-column gap-3">
                    <?php
                    $defaultMethods = ['cash' => 'Cash', 'card' => 'Card', 'transfer' => 'Bank Transfer', 'cheque' => 'Cheque', 'credit' => 'Credit', 'other' => 'Other'];
                    $savedMethods = json_decode($settings['payment_methods'] ?? '[]', true) ?: array_keys($defaultMethods);
                    $paymentMethodLabels = json_decode($settings['payment_method_labels'] ?? '{}', true) ?: [];

                    foreach ($savedMethods as $method):
                        $label = $paymentMethodLabels[$method] ?? ($defaultMethods[$method] ?? ucfirst($method));
                    ?>
                    <div class="payment-method-item flex items-center gap-3 p-3 border rounded" draggable="true" data-method="<?= $method ?>">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:16px; cursor:grab; color:var(--text-muted);">
                            <circle cx="9" cy="12" r="1"></circle>
                            <circle cx="9" cy="5" r="1"></circle>
                            <circle cx="9" cy="19" r="1"></circle>
                            <circle cx="15" cy="12" r="1"></circle>
                            <circle cx="15" cy="5" r="1"></circle>
                            <circle cx="15" cy="19" r="1"></circle>
                        </svg>
                        <input type="checkbox" name="payment_methods[]" value="<?= $method ?>" checked class="form-control" style="width:auto;">
                        <span class="font-medium"><?= e($label) ?></span>
                        <input type="text" name="method_labels[<?= $method ?>]" value="<?= e($paymentMethodLabels[$method] ?? $label) ?>" class="form-control" placeholder="Edit label" style="flex:1;">
                        <input type="hidden" name="method_order[]" value="<?= $method ?>">
                    </div>
                    <?php endforeach; ?>
                </div>
                
                <div class="mt-4">
                    <button type="button" class="btn btn-outline btn-sm" onclick="addPaymentMethod()">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:14px;"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>
                        Add Custom Payment Method
                    </button>
                </div>
            </div>
            
            <div class="form-group mb-6">
                <label class="form-label">Default Payment Method</label>
                <select name="default_payment_method" class="form-control">
                    <?php foreach ($savedMethods as $method): ?>
                        <option value="<?= $method ?>" <?= ($settings['default_payment_method'] ?? 'cash') === $method ? 'selected' : '' ?>>
                            <?= e($paymentMethodLabels[$method] ?? ($defaultMethods[$method] ?? ucfirst($method))) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <div class="form-hint">This will be pre-selected when creating purchases and sales.</div>
            </div>
            
            <div class="flex justify-end">
                <button type="submit" class="btn btn-primary">Save Payment Methods</button>
            </div>
        </form>
    </div>
</div>

<script>
let customMethodCount = 0;

function addPaymentMethod() {
    const list = document.getElementById('payment-methods-list');
    const method = 'custom_' + Date.now();
    const div = document.createElement('div');
    div.className = 'payment-method-item flex items-center gap-3 p-3 border rounded';
    div.draggable = true;
    div.dataset.method = method;
    div.innerHTML = `
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:16px; cursor:grab; color:var(--text-muted);">
            <circle cx="9" cy="12" r="1"></circle>
            <circle cx="9" cy="5" r="1"></circle>
            <circle cx="9" cy="19" r="1"></circle>
            <circle cx="15" cy="12" r="1"></circle>
            <circle cx="15" cy="5" r="1"></circle>
            <circle cx="15" cy="19" r="1"></circle>
        </svg>
        <input type="checkbox" name="payment_methods[]" value="${method}" checked class="form-control" style="width:auto;">
        <span class="font-medium label-display">New Method</span>
        <input type="text" name="method_labels[${method}]" class="form-control" placeholder="Enter method name" style="flex:1;" oninput="this.previousElementSibling.textContent = this.value || 'New Method'">
        <input type="hidden" name="method_order[]" value="${method}">
        <button type="button" class="text-danger" onclick="this.parentElement.remove()">×</button>
    `;
    list.appendChild(div);
}

// Drag and drop reordering
const list = document.getElementById('payment-methods-list');
let draggedItem = null;

list.addEventListener('dragstart', (e) => {
    draggedItem = e.target;
    e.target.style.opacity = '0.5';
});

list.addEventListener('dragend', (e) => {
    e.target.style.opacity = '1';
    draggedItem = null;
});

list.addEventListener('dragover', (e) => {
    e.preventDefault();
    const afterElement = getDragAfterElement(list, e.clientY);
    if (afterElement == null) {
        list.appendChild(draggedItem);
    } else {
        list.insertBefore(draggedItem, afterElement);
    }
});

function getDragAfterElement(container, y) {
    const draggableElements = [...container.querySelectorAll('.payment-method-item:not(.dragging)')];
    
    return draggableElements.reduce((closest, child) => {
        const box = child.getBoundingClientRect();
        const offset = y - box.top - box.height / 2;
        if (offset < 0 && offset > closest.offset) {
            return { offset: offset, element: child };
        } else {
            return closest;
        }
    }, { offset: Number.NEGATIVE_INFINITY }).element;
}
</script>
