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

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

// Handle form submission to update the transaction status
if (isset($_POST['transaction_id']) && isset($_POST['status'])) {
    $transactionId = $_POST['transaction_id'];
    $newStatus = $_POST['status'];
    $note = !empty($_POST['note']) ? $_POST['note'] : 'N/A';

    // Begin a transaction to ensure atomicity
    $conn->begin_transaction();

    try {
        // 1. Update the transaction status and note
        $updateQuery = "UPDATE transactions SET status = ?, note = ? WHERE id = ?";
        $stmt = $conn->prepare($updateQuery);
        $stmt->bind_param('ssi', $newStatus, $note, $transactionId);

        if ($stmt->execute()) {
            echo "Transaction status updated successfully.<br>";
        } else {
            echo "Error updating transaction status: " . $stmt->error . "<br>";
            $conn->rollback();
            exit;
        }

        // If the status is 'completed', update the user's balance
        if ($newStatus === 'Completed') {
            $selectQuery = "SELECT user_id, amount FROM transactions WHERE id = ?";
            $stmt = $conn->prepare($selectQuery);
            $stmt->bind_param('i', $transactionId);

            if ($stmt->execute()) {
                $result = $stmt->get_result();
                if ($result->num_rows > 0) {
                    $transactionData = $result->fetch_assoc();
                    $userId = $transactionData['user_id'];
                    $amount = $transactionData['amount'];

                    $updateBalanceQuery = "UPDATE users SET balance = balance + ? WHERE id = ?";
                    $stmt = $conn->prepare($updateBalanceQuery);
                    $stmt->bind_param('di', $amount, $userId);

                    if ($stmt->execute()) {
                        echo "User balance updated successfully.<br>";
                    } else {
                        echo "Error updating user balance: " . $stmt->error . "<br>";
                        $conn->rollback();
                        exit;
                    }
                } else {
                    echo "Transaction not found.<br>";
                    $conn->rollback();
                    exit;
                }
            } else {
                echo "Error fetching transaction details: " . $stmt->error . "<br>";
                $conn->rollback();
                exit;
            }
        }

        // Commit the transaction if everything is successful
        $conn->commit();

    } catch (Exception $e) {
        // Rollback the transaction in case of an error
        $conn->rollback();
        echo "Error: " . $e->getMessage();
    }
}

// Fetch all transactions based on the status filter
$statusFilter = isset($_GET['status']) ? $_GET['status'] : 'pending'; // Default to pending transactions
$addMoneyQuery = "SELECT t.id, u.name, t.payment_method, t.payment_number, t.amount, t.transaction_date, t.status 
                  FROM transactions t
                  JOIN users u ON t.user_id = u.id
                  WHERE t.type = 'add' AND t.status = ?
                  ORDER BY t.transaction_date DESC";
$stmt = $conn->prepare($addMoneyQuery);
$stmt->bind_param('s', $statusFilter);
$stmt->execute();
$result = $stmt->get_result();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Money Transactions</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 0;
        }
        .header {
            display: flex;
            align-items: center;
            background-color: #4CAF50;
            color: white;
            padding: 15px;
            text-align: center;
            justify-content: space-between;
        }
        .back-icon {
            cursor: pointer;
        }
        .back-icon img {
            width: 18px;
            height: 18px;
        }
        .container {
            max-width: 1000px;
            margin: 20px auto;
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        .transaction-card {
            background-color: #f9f9f9;
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .transaction-card .transaction-info {
            margin-bottom: 15px;
        }
        .transaction-card h3 {
            margin: 0;
            font-size: 18px;
            font-weight: bold;
            color: #333;
        }
        .transaction-card p {
            margin: 5px 0;
            font-size: 14px;
            color: #555;
        }
        .transaction-card .transaction-amount {
            font-size: 16px;
            font-weight: bold;
            color: #4CAF50;
            margin-bottom: 15px;
        }
        .btn-container {
            display: flex;
            justify-content: flex-start;
            margin-top: 10px;
        }
        .btn-container button {
            margin-right: 10px; /* Spacing between buttons */
        }
        .btn {
            padding: 8px 12px;
            border-radius: 5px;
            text-decoration: none;
            cursor: pointer;
        }
        .btn-failed { background-color: red; color: white; }
        .btn-success { background-color: green; color: white; }

        /* Popup Styling */
        .popup {
            visibility: hidden;
            position: fixed;
            top: -100%;
            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;
        }
        .popup.show {
            visibility: visible;
            top: 20px;
        }
        .popup h4 {
            text-align: center;
            margin-top: 0;
            font-size: 18px;
        }
        .popup input[type="text"] {
            width: 100%;
            padding: 8px;
            margin-bottom: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        .popup .btn-confirm {
            width: 100%;
            padding: 10px;
            background-color: #4CAF50;
            color: white;
            border: none;
            cursor: pointer;
            border-radius: 5px;
        }
        .popup .btn-close {
            margin-top: 10px;
            width: 100%;
            padding: 10px;
            background-color: #f44336;
            color: white;
            border: none;
            cursor: pointer;
            border-radius: 5px;
        }
        /* 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>
    <h2>Add Money Transactions</h2>
</div>

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

    <?php while ($transaction = $result->fetch_assoc()): ?>
        <div class="transaction-card">
            <div class="transaction-info">
                <h3><?php echo htmlspecialchars($transaction['name']); ?></h3>
                <p><strong>Payment Method:</strong> <?php echo htmlspecialchars($transaction['payment_method']); ?></p>
                <p><strong>Payment Number:</strong> <?php echo htmlspecialchars($transaction['payment_number']); ?></p>
                <p><strong>Date:</strong> <?php echo htmlspecialchars($transaction['transaction_date']); ?></p>
            </div>
            <div class="transaction-amount">
                ৳<?php echo number_format($transaction['amount'], 2); ?>
            </div>
            <p><strong>Status:</strong> 
    <span style="color: 
        <?php 
            if ($transaction['status'] == 'completed') {
                echo 'green; font-weight: bold;';
            } elseif ($transaction['status'] == 'failed') {
                echo 'red; font-weight: bold;';
            } else {
                echo 'gray; font-weight: bold;';
            }
        ?>">
        <?php echo htmlspecialchars($transaction['status']); ?>
    </span>
</p>

            <!-- Action buttons for pending transactions only -->
            <?php if ($transaction['status'] == 'pending'): ?>
            <div class="btn-container">
                <button class="btn btn-failed" onclick="openPopup(<?php echo $transaction['id']; ?>, 'Failed')">Failed</button>
                <button class="btn btn-success" onclick="openPopup(<?php echo $transaction['id']; ?>, 'Completed')">Success</button>
            </div>
            <?php endif; ?>
        </div>
    <?php endwhile; ?>
</div>

<!-- Pop-up for adding a note -->
<div class="popup" id="popupNote">
    <h4>Add Note</h4>
    <form method="post">
        <input type="hidden" name="transaction_id" id="transaction_id">
        <input type="hidden" name="status" id="transaction_status">
        <input type="text" name="note" placeholder="Enter note (Optional)">
        <button type="submit" class="btn-confirm">Confirm</button>
        <button type="button" class="btn-close" onclick="closePopup()">Close</button>
    </form>
</div>

<script>
    function openPopup(transactionId, status) {
        document.getElementById('transaction_id').value = transactionId;
        document.getElementById('transaction_status').value = status;
        document.getElementById('popupNote').classList.add('show');
    }

    function closePopup() {
        document.getElementById('popupNote').classList.remove('show');
    }
</script>

</body>
</html>
