<?php
session_start();
include('db.php'); // Your database connection

// Check if the admin is logged in
if (!isset($_SESSION['admin_logged_in'])) {
    header("Location: login.php");
    exit;
}

// Fetch all payment methods
$paymentQuery = "SELECT * FROM payment_method";
$paymentResult = $conn->query($paymentQuery);

// Add new payment method
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['addPayment'])) {
    $name = $_POST['name'];
    $minLimit = $_POST['min_limit'];
    $maxLimit = $_POST['max_limit'];
    $logoUrl = '';

    // Handle logo upload
    if (!empty($_FILES['logo']['name'])) {
        $logoName = basename($_FILES['logo']['name']);
        $logoUrl = 'https://admin.ramitwallet.com/upload/' . $logoName;
        $uploadPath = 'upload/' . $logoName;
        move_uploaded_file($_FILES['logo']['tmp_name'], $uploadPath);
    }

    // Insert the new method into the database
    $insertQuery = "INSERT INTO payment_method (name, logo_url, min_limit, max_limit) VALUES (?, ?, ?, ?)";
    $stmt = $conn->prepare($insertQuery);
    $stmt->bind_param('ssdd', $name, $logoUrl, $minLimit, $maxLimit);
    $stmt->execute();
    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

// Update payment method
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['editPaymentId'])) {
    $paymentId = $_POST['editPaymentId'];
    $name = $_POST['editName'];
    $minLimit = $_POST['editMinLimit'];
    $maxLimit = $_POST['editMaxLimit'];
    $logoUrl = $_POST['existingLogoUrl'];

    // Handle logo upload
    if (!empty($_FILES['editLogo']['name'])) {
        $logoName = basename($_FILES['editLogo']['name']);
        $logoUrl = 'https://admin.ramitwallet.com/upload/' . $logoName;
        $uploadPath = 'upload/' . $logoName;
        move_uploaded_file($_FILES['editLogo']['tmp_name'], $uploadPath);
    }

    // Update the payment method in the database
    $updateQuery = "UPDATE payment_method SET name = ?, logo_url = ?, min_limit = ?, max_limit = ? WHERE id = ?";
    $stmt = $conn->prepare($updateQuery);
    $stmt->bind_param('ssddi', $name, $logoUrl, $minLimit, $maxLimit, $paymentId);
    $stmt->execute();
    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

// Delete payment method
if (isset($_GET['delete'])) {
    $paymentId = $_GET['delete'];
    $deleteQuery = "DELETE FROM payment_method WHERE id = ?";
    $stmt = $conn->prepare($deleteQuery);
    $stmt->bind_param('i', $paymentId);
    $stmt->execute();
    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Panel - Payment Methods</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 0;
        }
        .container {
            width: 80%;
            margin: 20px auto;
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        table, th, td {
            border: 1px solid #ddd;
        }
        th, td {
            padding: 10px;
            text-align: left;
        }
        th {
            background-color: #f2f2f2;
        }
        .action-buttons {
            display: flex;
            gap: 10px;
        }
        .edit-btn, .delete-btn, .add-btn {
            padding: 5px 10px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
        .edit-btn {
            background-color: #4CAF50;
            color: white;
        }
        .delete-btn {
            background-color: #f44336;
            color: white;
        }
        .add-btn {
            background-color: #2196F3;
            color: white;
            margin-bottom: 20px;
        }
        .modal {
            display: none;
            position: fixed;
            z-index: 100;
            padding-top: 100px;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            overflow: auto;
        }
        .modal-content {
            background-color: #fff;
            margin: auto;
            padding: 20px;
            border: 1px solid #888;
            width: 50%;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
        }
        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
        }
        .close:hover, .close:focus {
            color: black;
            text-decoration: none;
            cursor: pointer;
        }
        .save-btn {
            background-color: #4CAF50;
            color: white;
            border: none;
            padding: 10px;
            border-radius: 5px;
            cursor: pointer;
        }
    </style>
</head>
<body>

    <div class="container">
        <h2>Admin Panel - Payment Methods</h2>

        <button class="add-btn" onclick="showAddModal()">Add New Method</button>
        
        <table>
            <tr>
                <th>#</th>
                <th>Name</th>
                <th>Logo URL</th>
                <th>Min Limit</th>
                <th>Max Limit</th>
                <th>Action</th>
            </tr>
            <?php if ($paymentResult->num_rows > 0): ?>
                <?php while($payment = $paymentResult->fetch_assoc()): ?>
                <tr>
                    <td><?php echo $payment['id']; ?></td>
                    <td><?php echo htmlspecialchars($payment['name']); ?></td>
                    <td><?php echo htmlspecialchars($payment['logo_url']); ?></td>
                    <td><?php echo number_format($payment['min_limit'], 2); ?></td>
                    <td><?php echo number_format($payment['max_limit'], 2); ?></td>
                    <td>
                        <div class="action-buttons">
                            <button class="edit-btn" onclick="showEditModal('<?php echo $payment['id']; ?>', '<?php echo htmlspecialchars($payment['name']); ?>', '<?php echo htmlspecialchars($payment['logo_url']); ?>', '<?php echo $payment['min_limit']; ?>', '<?php echo $payment['max_limit']; ?>')">Edit</button>
                            <a href="?delete=<?php echo $payment['id']; ?>" class="delete-btn" onclick="return confirm('Are you sure you want to delete this payment method?')">Delete</a>
                        </div>
                    </td>
                </tr>
                <?php endwhile; ?>
            <?php else: ?>
                <tr>
                    <td colspan="6">No payment methods found.</td>
                </tr>
            <?php endif; ?>
        </table>
    </div>

    <!-- Add Modal -->
    <div id="addModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeModal('addModal')">&times;</span>
            <h3>Add New Payment Method</h3>
            <form method="POST" enctype="multipart/form-data">
                <div>
                    <label for="name">Name:</label>
                    <input type="text" name="name" required>
                </div>
                <div>
                    <label for="logo">Logo:</label>
                    <input type="file" name="logo" required>
                </div>
                <div>
                    <label for="min_limit">Min Limit:</label>
                    <input type="number" name="min_limit" step="0.01" required>
                </div>
                <div>
                    <label for="max_limit">Max Limit:</label>
                    <input type="number" name="max_limit" step="0.01" required>
                </div>
                <button type="submit" class="save-btn" name="addPayment">Add Method</button>
            </form>
        </div>
    </div>

    <!-- Edit Modal -->
    <div id="editModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeModal('editModal')">&times;</span>
            <h3>Edit Payment Method</h3>
            <form method="POST" enctype="multipart/form-data">
                <input type="hidden" name="editPaymentId" id="editPaymentId">
                <div>
                    <label for="editName">Name:</label>
                    <input type="text" name="editName" id="editName" required>
                </div>
                <div>
                    <label for="editLogo">Logo:</label>
                    <input type="file" name="editLogo">
                    <input type="hidden" name="existingLogoUrl" id="existingLogoUrl">
                </div>
                <div>
                    <label for="editMinLimit">Min Limit:</label>
                    <input type="number" name="editMinLimit" id="editMinLimit" step="0.01" required>
                </div>
                <div>
                    <label for="editMaxLimit">Max Limit:</label>
                    <input type="number" name="editMaxLimit" id="editMaxLimit" step="0.01" required>
                </div>
                <button type="submit" class="save-btn">Save Changes</button>
            </form>
        </div>
    </div>

    <script>
        // Show Add Modal
        function showAddModal() {
            document.getElementById('addModal').style.display = 'block';
        }

        // Show Edit Modal
        function showEditModal(id, name, logoUrl, minLimit, maxLimit) {
            document.getElementById('editPaymentId').value = id;
            document.getElementById('editName').value = name;
            document.getElementById('existingLogoUrl').value = logoUrl;
            document.getElementById('editMinLimit').value = minLimit;
            document.getElementById('editMaxLimit').value = maxLimit;
            document.getElementById('editModal').style.display = 'block';
        }

        // Close Modal
        function closeModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
        }
    </script>

</body>
</html>
