<?php
session_start();
include 'db.php';
include 'layout.php';
include 'includes/payment_methods.php';

$message = '';
$error = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'add':
                $data = [
                    'method_name' => strtolower(trim($_POST['method_name'])),
                    'display_name' => trim($_POST['display_name']),
                    'icon_class' => trim($_POST['icon_class']),
                    'color_class' => trim($_POST['color_class']),
                    'is_active' => isset($_POST['is_active']) ? 1 : 0,
                    'requires_bank_account' => isset($_POST['requires_bank_account']) ? 1 : 0,
                    'sort_order' => intval($_POST['sort_order'])
                ];
                
                if (addPaymentMethod($conn, $data)) {
                    $message = "Payment method added successfully!";
                } else {
                    $error = "Failed to add payment method. Method name might already exist.";
                }
                break;
                
            case 'update':
                $id = intval($_POST['id']);
                $data = [
                    'display_name' => trim($_POST['display_name']),
                    'icon_class' => trim($_POST['icon_class']),
                    'color_class' => trim($_POST['color_class']),
                    'is_active' => isset($_POST['is_active']) ? 1 : 0,
                    'requires_bank_account' => isset($_POST['requires_bank_account']) ? 1 : 0,
                    'sort_order' => intval($_POST['sort_order'])
                ];
                
                if (updatePaymentMethod($conn, $id, $data)) {
                    $message = "Payment method updated successfully!";
                } else {
                    $error = "Failed to update payment method.";
                }
                break;
                
            case 'delete':
                $id = intval($_POST['id']);
                if (deletePaymentMethod($conn, $id)) {
                    $message = "Payment method deleted successfully!";
                } else {
                    $error = "Failed to delete payment method. It might be in use.";
                }
                break;
        }
    }
}

// Get all payment methods
$all_methods = $conn->query("SELECT * FROM payment_methods ORDER BY sort_order, method_name")->fetch_all(MYSQLI_ASSOC);

// Check if we have payment methods
if (empty($all_methods)) {
    $error = "No payment methods found. Please run the update_payment_methods.sql script first.";
}
?>

<div class="page-wrapper">
    <div class="content">
        <div class="page-header d-flex justify-content-between align-items-center">
            <div class="page-title">
                <h4>💳 Payment Methods Management</h4>
                <h6>Manage payment methods for your POS system</h6>
            </div>
            <div class="page-btn">
                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addMethodModal">
                    <i class="fas fa-plus"></i> Add New Method
                </button>
            </div>
        </div>

        <div class="card">
            <div class="card-body">
                <?php if ($message): ?>
                    <div class="alert alert-success"><?= htmlspecialchars($message) ?></div>
                <?php endif; ?>
                <?php if ($error): ?>
                    <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
                <?php endif; ?>
                
                <div class="table-responsive">
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>Method Name</th>
                                <th>Display Name</th>
                                <th>Icon</th>
                                <th>Color</th>
                                <th>Status</th>
                                <th>Bank Account Required</th>
                                <th>Sort Order</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($all_methods as $method): ?>
                            <tr>
                                <td><code><?= htmlspecialchars($method['method_name']) ?></code></td>
                                <td><?= htmlspecialchars($method['display_name']) ?></td>
                                <td>
                                    <?php if ($method['icon_class']): ?>
                                        <i class="<?= htmlspecialchars($method['icon_class']) ?>"></i>
                                        <small><?= htmlspecialchars($method['icon_class']) ?></small>
                                    <?php else: ?>
                                        <span class="text-muted">None</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if ($method['color_class']): ?>
                                        <span class="badge <?= htmlspecialchars($method['color_class']) ?>">
                                            <?= htmlspecialchars($method['color_class']) ?>
                                        </span>
                                    <?php else: ?>
                                        <span class="text-muted">Default</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <span class="badge bg-<?= $method['is_active'] ? 'success' : 'danger' ?>">
                                        <?= $method['is_active'] ? 'Active' : 'Inactive' ?>
                                    </span>
                                </td>
                                <td>
                                    <span class="badge bg-<?= $method['requires_bank_account'] ? 'warning' : 'secondary' ?>">
                                        <?= $method['requires_bank_account'] ? 'Yes' : 'No' ?>
                                    </span>
                                </td>
                                <td><?= $method['sort_order'] ?></td>
                                <td>
                                    <button class="btn btn-sm btn-outline-primary" 
                                            onclick="editMethod(<?= htmlspecialchars(json_encode($method)) ?>)">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <?php if ($method['method_name'] !== 'cash' && $method['method_name'] !== 'card'): ?>
                                    <button class="btn btn-sm btn-outline-danger" 
                                            onclick="deleteMethod(<?= $method['id'] ?>, '<?= htmlspecialchars($method['method_name']) ?>')">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add Method Modal -->
<div class="modal fade" id="addMethodModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="action" value="add">
                <div class="modal-header">
                    <h5 class="modal-title">Add New Payment Method</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Method Name (Code)</label>
                        <input type="text" name="method_name" class="form-control" required 
                               placeholder="e.g., paypal, crypto" pattern="[a-z_]+" 
                               title="Only lowercase letters and underscores allowed">
                        <small class="form-text text-muted">Use lowercase letters and underscores only</small>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Display Name</label>
                        <input type="text" name="display_name" class="form-control" required 
                               placeholder="e.g., PayPal Payment">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Icon</label>
                        <select name="icon_class" class="form-select">
                            <option value="">No Icon</option>
                            <option value="fas fa-money-bill-wave">💰 Cash/Money</option>
                            <option value="fas fa-credit-card">💳 Credit Card</option>
                            <option value="fas fa-mobile-alt">📱 Mobile/Phone</option>
                            <option value="fas fa-university">🏦 Bank</option>
                            <option value="fas fa-clock">⏰ Clock/Time</option>
                            <option value="fab fa-paypal">PayPal</option>
                            <option value="fab fa-google-pay">Google Pay</option>
                            <option value="fab fa-apple-pay">Apple Pay</option>
                            <option value="fas fa-wallet">👛 Wallet</option>
                            <option value="fas fa-exchange-alt">🔄 Transfer</option>
                            <option value="fas fa-qrcode">📱 QR Code</option>
                            <option value="fas fa-coins">🪙 Coins</option>
                            <option value="fas fa-gift">🎁 Gift Card</option>
                            <option value="fas fa-handshake">🤝 Handshake</option>
                            <option value="fas fa-shield-alt">🛡️ Secure</option>
                            <option value="fas fa-star">⭐ Star</option>
                            <option value="fas fa-heart">❤️ Heart</option>
                            <option value="fas fa-gem">💎 Diamond</option>
                        </select>
                        <small class="form-text text-muted">Choose an icon for this payment method (optional)</small>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Color Class (Bootstrap)</label>
                        <select name="color_class" class="form-select">
                            <option value="btn-outline-primary">Primary (Blue)</option>
                            <option value="btn-outline-success">Success (Green)</option>
                            <option value="btn-outline-warning">Warning (Yellow)</option>
                            <option value="btn-outline-danger">Danger (Red)</option>
                            <option value="btn-outline-info">Info (Cyan)</option>
                            <option value="btn-outline-secondary">Secondary (Gray)</option>
                            <option value="btn-outline-dark">Dark (Black)</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <div class="form-check">
                            <input type="checkbox" name="is_active" class="form-check-input" checked>
                            <label class="form-check-label">Active</label>
                        </div>
                    </div>
                    <div class="mb-3">
                        <div class="form-check">
                            <input type="checkbox" name="requires_bank_account" class="form-check-input">
                            <label class="form-check-label">Requires Bank Account Selection</label>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Sort Order</label>
                        <input type="number" name="sort_order" class="form-control" value="10" min="0">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Add Method</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Method Modal -->
<div class="modal fade" id="editMethodModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="action" value="update">
                <input type="hidden" name="id" id="edit_id">
                <div class="modal-header">
                    <h5 class="modal-title">Edit Payment Method</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Method Name</label>
                        <input type="text" id="edit_method_name" class="form-control" readonly>
                        <small class="form-text text-muted">Method name cannot be changed</small>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Display Name</label>
                        <input type="text" name="display_name" id="edit_display_name" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Icon</label>
                        <select name="icon_class" id="edit_icon_class" class="form-select">
                            <option value="">No Icon</option>
                            <option value="fas fa-money-bill-wave">💰 Cash/Money</option>
                            <option value="fas fa-credit-card">💳 Credit Card</option>
                            <option value="fas fa-mobile-alt">📱 Mobile/Phone</option>
                            <option value="fas fa-university">🏦 Bank</option>
                            <option value="fas fa-clock">⏰ Clock/Time</option>
                            <option value="fab fa-paypal">PayPal</option>
                            <option value="fab fa-google-pay">Google Pay</option>
                            <option value="fab fa-apple-pay">Apple Pay</option>
                            <option value="fas fa-wallet">👛 Wallet</option>
                            <option value="fas fa-exchange-alt">🔄 Transfer</option>
                            <option value="fas fa-qrcode">📱 QR Code</option>
                            <option value="fas fa-coins">🪙 Coins</option>
                            <option value="fas fa-gift">🎁 Gift Card</option>
                            <option value="fas fa-handshake">🤝 Handshake</option>
                            <option value="fas fa-shield-alt">🛡️ Secure</option>
                            <option value="fas fa-star">⭐ Star</option>
                            <option value="fas fa-heart">❤️ Heart</option>
                            <option value="fas fa-gem">💎 Diamond</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Color Class (Bootstrap)</label>
                        <select name="color_class" id="edit_color_class" class="form-select">
                            <option value="btn-outline-primary">Primary (Blue)</option>
                            <option value="btn-outline-success">Success (Green)</option>
                            <option value="btn-outline-warning">Warning (Yellow)</option>
                            <option value="btn-outline-danger">Danger (Red)</option>
                            <option value="btn-outline-info">Info (Cyan)</option>
                            <option value="btn-outline-secondary">Secondary (Gray)</option>
                            <option value="btn-outline-dark">Dark (Black)</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <div class="form-check">
                            <input type="checkbox" name="is_active" id="edit_is_active" class="form-check-input">
                            <label class="form-check-label">Active</label>
                        </div>
                    </div>
                    <div class="mb-3">
                        <div class="form-check">
                            <input type="checkbox" name="requires_bank_account" id="edit_requires_bank_account" class="form-check-input">
                            <label class="form-check-label">Requires Bank Account Selection</label>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Sort Order</label>
                        <input type="number" name="sort_order" id="edit_sort_order" class="form-control" min="0">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Update Method</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteMethodModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="action" value="delete">
                <input type="hidden" name="id" id="delete_id">
                <div class="modal-header">
                    <h5 class="modal-title">Delete Payment Method</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p>Are you sure you want to delete the payment method "<strong id="delete_method_name"></strong>"?</p>
                    <p class="text-warning">This action cannot be undone. If the method is in use, it will be deactivated instead of deleted.</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger">Delete Method</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    function editMethod(method) {
        document.getElementById('edit_id').value = method.id;
        document.getElementById('edit_method_name').value = method.method_name;
        document.getElementById('edit_display_name').value = method.display_name;
        document.getElementById('edit_icon_class').value = method.icon_class;
        document.getElementById('edit_color_class').value = method.color_class;
        document.getElementById('edit_is_active').checked = method.is_active == 1;
        document.getElementById('edit_requires_bank_account').checked = method.requires_bank_account == 1;
        document.getElementById('edit_sort_order').value = method.sort_order;
        
        new bootstrap.Modal(document.getElementById('editMethodModal')).show();
    }
    
    function deleteMethod(id, name) {
        document.getElementById('delete_id').value = id;
        document.getElementById('delete_method_name').textContent = name;
        new bootstrap.Modal(document.getElementById('deleteMethodModal')).show();
    }
</script> 