<?php
// payment_methods.php - Manage Payment Methods
// File location: /bidwheels.net/admin/payment_methods.php

require_once '../includes/auth.php';
require_once '../includes/functions.php';
require_once 'includes/admin_header.php';

requireAdmin();

// Handle add payment method
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_method'])) {
    $method_name = sanitize($_POST['method_name']);
    $method_fields = json_encode($_POST['fields']);
    
    if (!empty($method_name)) {
        insert('payment_methods', [
            'method_name' => $method_name,
            'method_fields' => $method_fields,
            'is_active' => 1
        ]);
        setSuccess('Payment method added successfully!');
        redirect('/admin/payment_methods.php');
    }
}

// Handle toggle active status
if (isset($_GET['toggle'])) {
    $id = (int)$_GET['toggle'];
    $method = fetchOne("SELECT is_active FROM payment_methods WHERE id = $id");
    $new_status = $method['is_active'] == 1 ? 0 : 1;
    update('payment_methods', ['is_active' => $new_status], "id = $id");
    setSuccess('Payment method status updated.');
    redirect('/admin/payment_methods.php');
}

// Handle delete
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    delete('payment_methods', "id = $id");
    setSuccess('Payment method deleted.');
    redirect('/admin/payment_methods.php');
}

$payment_methods = fetchAll("SELECT * FROM payment_methods ORDER BY id");
?>

<div class="admin-page">
    <div class="page-header">
        <h1 class="page-title">Payment Methods</h1>
    </div>
    
    <?php echo getMessage(); ?>
    
    <div class="payment-layout">
        <!-- Add Payment Method -->
        <div class="payment-form-panel">
            <h3>Add New Payment Method</h3>
            <form method="POST" action="" class="admin-form" id="paymentForm">
                <div class="form-group">
                    <label>Method Name *</label>
                    <input type="text" name="method_name" class="form-control" required placeholder="e.g., PayPal, Crypto, etc.">
                </div>
                
                <div class="form-group">
                    <label>Required Fields</label>
                    <div id="fieldsContainer">
                        <div class="field-row">
                            <input type="text" name="fields[0]" placeholder="Field name (e.g., Account Email)" class="form-control" style="width: 70%; display: inline-block;">
                            <button type="button" class="btn btn-small btn-danger remove-field" style="display: none;">Remove</button>
                        </div>
                    </div>
                    <button type="button" id="addField" class="btn btn-small btn-secondary">+ Add Field</button>
                </div>
                
                <button type="submit" name="add_method" class="btn btn-primary">Add Payment Method</button>
            </form>
        </div>
        
        <!-- Existing Payment Methods -->
        <div class="payment-list-panel">
            <h3>Existing Payment Methods</h3>
            <?php if (count($payment_methods) > 0): ?>
                <table class="admin-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Method Name</th>
                            <th>Fields</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($payment_methods as $method): 
                            $fields = json_decode($method['method_fields'], true);
                        ?>
                            <tr>
                                <td><?php echo $method['id']; ?></td>
                                <td><?php echo htmlspecialchars($method['method_name']); ?></td>
                                <td>
                                    <?php 
                                    if (is_array($fields)) {
                                        echo implode(', ', array_filter($fields));
                                    } else {
                                        echo 'No fields';
                                    }
                                    ?>
                                </td>
                                <td>
                                    <?php if ($method['is_active']): ?>
                                        <span class="badge badge-success">Active</span>
                                    <?php else: ?>
                                        <span class="badge badge-danger">Inactive</span>
                                    <?php endif; ?>
                                </td>
                                <td class="actions">
                                    <a href="?toggle=<?php echo $method['id']; ?>" class="btn-icon btn-warning">
                                        <?php echo $method['is_active'] ? '<i class="fas fa-pause"></i>' : '<i class="fas fa-play"></i>'; ?>
                                    </a>
                                    <a href="?delete=<?php echo $method['id']; ?>" class="btn-icon btn-danger" onclick="return confirm('Delete this payment method?')"><i class="fas fa-trash"></i></a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <p>No payment methods found. Credit Card and Bank Transfer are available by default.</p>
            <?php endif; ?>
        </div>
    </div>
</div>

<style>
.payment-layout {
    display: grid;
    grid-template-columns: 1fr 1.5fr;
    gap: 30px;
}
.payment-form-panel, .payment-list-panel {
    background: white;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
.field-row {
    margin-bottom: 10px;
}
.field-row input {
    width: calc(100% - 80px) !important;
    margin-right: 10px;
}
.btn-small {
    padding: 5px 10px;
    font-size: 12px;
}
.btn-secondary {
    background: #6c757d;
    color: white;
}
.btn-warning {
    background: #ffc107;
    color: #333;
}
@media (max-width: 768px) {
    .payment-layout {
        grid-template-columns: 1fr;
    }
}
</style>

<script>
let fieldCount = 1;
document.getElementById('addField').addEventListener('click', function() {
    const container = document.getElementById('fieldsContainer');
    const newRow = document.createElement('div');
    newRow.className = 'field-row';
    newRow.innerHTML = `
        <input type="text" name="fields[${fieldCount}]" placeholder="Field name" class="form-control" style="width: 70%; display: inline-block;">
        <button type="button" class="btn btn-small btn-danger remove-field">Remove</button>
    `;
    container.appendChild(newRow);
    fieldCount++;
    
    // Add remove functionality to new button
    newRow.querySelector('.remove-field').addEventListener('click', function() {
        newRow.remove();
    });
});

// Make first remove button work if exists
document.querySelectorAll('.remove-field').forEach(btn => {
    btn.addEventListener('click', function() {
        btn.parentElement.remove();
    });
});
</script>

<?php require_once 'includes/admin_footer.php'; ?>