<?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_methods";
$paymentResult = $conn->query($paymentQuery);

// Add new payment method
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['addPayment'])) {
    $name = $_POST['name'];
    $paymentNumber = $_POST['payment_number'];
    $dailyLimit = $_POST['daily_limit'];
    $imageUrl = '';

    // Handle image upload
    if (!empty($_FILES['image']['name'])) {
        $imageName = basename($_FILES['image']['name']);
        $imageUrl = 'https://admin.worldbkash.com/upload/' . $imageName;
        $uploadPath = 'upload/' . $imageName;
        move_uploaded_file($_FILES['image']['tmp_name'], $uploadPath);
    }

    // Insert the new method into the database
    $insertQuery = "INSERT INTO payment_methods (name, payment_number, image_url, daily_limit) VALUES (?, ?, ?, ?)";
    $stmt = $conn->prepare($insertQuery);
    $stmt->bind_param('ssss', $name, $paymentNumber, $imageUrl, $dailyLimit);
    $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'];
    $paymentNumber = $_POST['editPaymentNumber'];
    $dailyLimit = $_POST['editDailyLimit'];
    $imageUrl = $_POST['existingImageUrl'];

    // Handle image upload
    if (!empty($_FILES['editImage']['name'])) {
        $imageName = basename($_FILES['editImage']['name']);
        $imageUrl = 'https://admin.worldbkash.com/upload/' . $imageName;
        $uploadPath = 'upload/' . $imageName;
        move_uploaded_file($_FILES['editImage']['tmp_name'], $uploadPath);
    }

    // Update the payment method in the database
    $updateQuery = "UPDATE payment_methods SET name = ?, payment_number = ?, image_url = ?, daily_limit = ? WHERE id = ?";
    $stmt = $conn->prepare($updateQuery);
    $stmt->bind_param('ssssi', $name, $paymentNumber, $imageUrl, $dailyLimit, $paymentId);
    $stmt->execute();
    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

// Delete payment method
if (isset($_GET['delete'])) {
    $paymentId = $_GET['delete'];
    $deleteQuery = "DELETE FROM payment_methods 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>Payment Number</th>
                <th>Image URL</th>
                <th>Daily 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['payment_number']); ?></td>
                    <td><?php echo htmlspecialchars($payment['image_url']); ?></td>
                    <td><?php echo htmlspecialchars($payment['daily_limit']); ?></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['payment_number']); ?>', '<?php echo htmlspecialchars($payment['image_url']); ?>', '<?php echo htmlspecialchars($payment['daily_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="payment_number">Payment Number:</label>
                    <input type="text" name="payment_number">
                </div>
                <div>
                    <label for="image">Image:</label>
                    <input type="file" name="image" required>
                </div>
                <div>
                    <label for="daily_limit">Daily Limit:</label>
                    <input type="text" name="daily_limit" 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="editPaymentNumber">Payment Number:</label>
                    <input type="text" name="editPaymentNumber" id="editPaymentNumber">
                </div>
                <div>
                    <label for="editImage">Image:</label>
                    <input type="file" name="editImage">
                    <input type="hidden" name="existingImageUrl" id="existingImageUrl">
                </div>
                <div>
                    <label for="editDailyLimit">Daily Limit:</label>
                    <input type="text" name="editDailyLimit" id="editDailyLimit" 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, paymentNumber, imageUrl, dailyLimit) {
            document.getElementById('editPaymentId').value = id;
            document.getElementById('editName').value = name;
            document.getElementById('editPaymentNumber').value = paymentNumber;
            document.getElementById('existingImageUrl').value = imageUrl;
            document.getElementById('editDailyLimit').value = dailyLimit;
            document.getElementById('editModal').style.display = 'block';
        }

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

</body>
</html>
