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

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

// Fetch M-Bank transactions from the database (assuming type 'mbank')
$statusFilter = isset($_GET['status']) ? $_GET['status'] : 'pending'; // Default to pending transactions
$transactionQuery = $conn->prepare("SELECT transactions.*, users.name as user_name, users.id as user_id FROM transactions JOIN users ON transactions.user_id = users.id WHERE type = 'mbank' AND status = ? ORDER BY date DESC");
$transactionQuery->bind_param("s", $statusFilter);
$transactionQuery->execute();
$transactionResult = $transactionQuery->get_result();
$transactions = [];
while ($row = $transactionResult->fetch_assoc()) {
    $transactions[] = $row;
}

// Update transaction status when the form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['transaction_id'])) {
    $transactionId = $_POST['transaction_id'];
    $status = $_POST['status'];
    $note = !empty($_POST['note']) ? $_POST['note'] : 'N/A';

    // Get the transaction details to fetch the user ID and amount
    $transactionDetailQuery = $conn->prepare("SELECT user_id, amount, status FROM transactions WHERE id = ?");
    $transactionDetailQuery->bind_param("i", $transactionId);
    $transactionDetailQuery->execute();
    $transactionDetailResult = $transactionDetailQuery->get_result();
    $transaction = $transactionDetailResult->fetch_assoc();

    // Only update balance if the transaction is marked as "failed"
    if ($transaction['status'] === 'pending' && $status === 'failed') {
        // Add the amount back to the user's balance
        $updateBalanceQuery = $conn->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
        $updateBalanceQuery->bind_param("di", $transaction['amount'], $transaction['user_id']);
        $updateBalanceQuery->execute();
    }

    // Update the transaction status and note
    $updateQuery = $conn->prepare("UPDATE transactions SET status = ?, note = ? WHERE id = ?");
    $updateQuery->bind_param("ssi", $status, $note, $transactionId);
    $updateQuery->execute();
    
    // Reload the page after update
    header("Location: mbank.php?status=$statusFilter");
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>M-Bank Transactions</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 0;
        }
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            background-color: #4CAF50;
            color: white;
            padding: 1px 7px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            height: 50px;
        }
        .back-icon {
            display: flex;
            align-items: center;
            cursor: pointer;
        }
        .back-icon img {
            width: 18px;
            height: 18px;
            margin-right: 8px;
        }
        .header h3 {
            font-size: 20px;
        }
        .container {
            padding: 20px;
        }
        .transaction {
            background-color: #fff;
            margin-bottom: 20px;
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        .transaction p {
            margin: 5px 0;
        }
        .status {
            font-weight: bold;
        }
        .status-completed {
            color: green;
        }
        .status-failed {
            color: red;
        }
        .status-pending {
            color: gray;
        }
        .btn-container {
            display: flex;
            margin-top: 10px;
        }
        .btn {
            padding: 10px 20px;
            border: none;
            margin-right: 10px;
            cursor: pointer;
        }
        .btn-success {
            background-color: #4CAF50;
            color: white;
        }
        .btn-failed {
            background-color: #f44336;
            color: white;
        }
        /* Popup styling for note input */
        .popup {
            visibility: hidden;
            position: fixed;
            top: -200px;
            left: 50%;
            transform: translateX(-50%);
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
            width: 300px;
            z-index: 100;
            transition: top 0.5s ease;
            overflow: hidden;
            max-height: 80vh;
        }
        .popup.show {
            visibility: visible;
            top: 20px;
        }
        .popup h4 {
            margin-top: 0;
            text-align: center;
            font-size: 20px;
        }
        .popup textarea {
            width: 100%;
            height: 80px;
            padding: 10px;
            margin-bottom: 10px;
        }
        .close-btn, .confirm-btn {
            background-color: #4CAF50;
            color: white;
            padding: 10px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            width: 100%;
        }
        .close-btn {
            background-color: #f44336;
            margin-top: 10px;
        }
        /* Filter Buttons */
        .filter-buttons {
            display: flex;
            margin-bottom: 20px;
        }
        .filter-btn {
            padding: 10px 20px;
            margin-right: 10px;
            background-color: #4CAF50;
            color: white;
            border: none;
            cursor: pointer;
            border-radius: 5px;
        }
    </style>
</head>
<body>

    <!-- Header Section -->
    <div class="header">
        <div class="back-icon" onclick="window.history.back()">
            <img src="https://cdn-icons-png.flaticon.com/512/93/93634.png" alt="Back">
        </div>
        <h3>M-Bank Transactions</h3>
    </div>

    <!-- Container -->
    <div class="container">
        <!-- Filter Buttons -->
        <div class="filter-buttons">
            <button class="filter-btn" onclick="window.location.href='mbank.php?status=pending'">Pending</button>
            <button class="filter-btn" onclick="window.location.href='mbank.php?status=completed'">Completed</button>
            <button class="filter-btn" onclick="window.location.href='mbank.php?status=failed'">Failed</button>
        </div>

        <!-- Transactions -->
        <?php foreach($transactions as $transaction): ?>
            <div class="transaction">
                <h4>
                    <?php echo empty($transaction['account_holder_name']) ? "Mobile Banking" : "Bank Transaction"; ?>
                </h4>

                <!-- User Name -->
                <p><strong>User:</strong> <?php echo htmlspecialchars($transaction['user_name']); ?></p>

                <?php if (!empty($transaction['account_holder_name'])): ?>
                    <!-- Bank Transaction -->
                    <p><strong>Bank Name:</strong> <span onclick="copyToClipboard('<?php echo htmlspecialchars($transaction['bank_name']); ?>')"><?php echo htmlspecialchars($transaction['bank_name']); ?></span></p>
                    <p><strong>Account Holder Name:</strong> <span onclick="copyToClipboard('<?php echo htmlspecialchars($transaction['account_holder_name']); ?>')"><?php echo htmlspecialchars($transaction['account_holder_name']); ?></span></p>
                    <p><strong>Account Number:</strong> <span onclick="copyToClipboard('<?php echo htmlspecialchars($transaction['account_number']); ?>')"><?php echo htmlspecialchars($transaction['account_number']); ?></span></p>
                <?php else: ?>
                    <!-- Mobile Banking -->
                    <p><strong>Payment Method:</strong> <?php echo htmlspecialchars($transaction['payment_method']); ?></p>
                    <p><strong>Payment Number:</strong> <span onclick="copyToClipboard('<?php echo htmlspecialchars($transaction['payment_number']); ?>')"><?php echo htmlspecialchars($transaction['payment_number']); ?></span></p>
                <?php endif; ?>

                <!-- Common Fields -->
                <p><strong>Amount:</strong> ৳<?php echo number_format($transaction['amount'], 2); ?></p>
                <p><strong>Date:</strong> <?php echo htmlspecialchars($transaction['date']); ?></p>
                <p><strong>Reference:</strong> <?php echo htmlspecialchars($transaction['reference']) ?: "N/A"; ?></p>
                <p><strong>Status:</strong> 
                    <span class="status 
                        <?php 
                            echo $transaction['status'] == 'completed' ? 'status-completed' : 
                            ($transaction['status'] == 'failed' ? 'status-failed' : 'status-pending'); 
                        ?>">
                        <?php echo htmlspecialchars($transaction['status']); ?>
                    </span>
                </p>

                <!-- Action Buttons for Pending Transactions -->
                <?php if ($transaction['status'] == 'pending'): ?>
                <div class="btn-container">
                    <button class="btn btn-success" onclick="showPopup(<?php echo $transaction['id']; ?>, 'completed')">Success</button>
                    <button class="btn btn-failed" onclick="showPopup(<?php echo $transaction['id']; ?>, 'failed')">Failed</button>
                </div>
                <?php endif; ?>
            </div>
        <?php endforeach; ?>
    </div>

    <!-- Popup for Note -->
<div class="popup" id="notePopup">
    <h4 id="popupTitle">Enter Note</h4>
    <form method="POST">
        <textarea id="noteText" name="note" placeholder="Optional note"></textarea> <!-- Added name attribute here -->
        <input type="hidden" name="transaction_id" id="transaction_id">
        <input type="hidden" name="status" id="statusInput">
        <button class="confirm-btn" type="submit">Confirm</button>
    </form>
    <button class="close-btn" onclick="closePopup()">Close</button>
</div>


    <script>
        // Function to show popup with transaction id and status
        function showPopup(transactionId, status) {
            document.getElementById('notePopup').classList.add('show');
            document.getElementById('transaction_id').value = transactionId;
            document.getElementById('statusInput').value = status;

            if (status === 'completed') {
                document.getElementById('popupTitle').innerText = 'Confirm Success';
            } else {
                document.getElementById('popupTitle').innerText = 'Confirm Failure';
            }
        }

        // Function to close popup
        function closePopup() {
            document.getElementById('notePopup').classList.remove('show');
        }

        // Function to copy data to clipboard
        function copyToClipboard(text) {
            navigator.clipboard.writeText(text).then(function() {
                alert('Copied: ' + text);
            }, function(err) {
                console.error('Failed to copy: ', err);
            });
        }
    </script>

</body>
</html>