<?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 'other' type transactions from the database based on the selected filter
$statusFilter = isset($_GET['status']) ? $_GET['status'] : 'pending';

$transactionQuery = $conn->prepare("SELECT transactions.*, users.name as user_name, users.id as user_id, receiver.name as receiver_name FROM transactions LEFT JOIN users ON transactions.user_id = users.id LEFT JOIN users as receiver ON transactions.receiver_id = receiver.id WHERE type = 'other' AND transactions.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'];

    // Fetch the transaction amount and user details
    $getTransactionDetails = $conn->prepare("SELECT amount, user_id, status FROM transactions WHERE id = ?");
    $getTransactionDetails->bind_param("i", $transactionId);
    $getTransactionDetails->execute();
    $transactionDetails = $getTransactionDetails->get_result()->fetch_assoc();

    // If the transaction is marked as failed and was previously pending, return the balance to the user
    if ($status === 'failed' && $transactionDetails['status'] === 'pending') {
        $amount = $transactionDetails['amount'];
        $userId = $transactionDetails['user_id'];

        // Update the user's balance by returning the transaction amount
        $updateBalanceQuery = $conn->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
        $updateBalanceQuery->bind_param("di", $amount, $userId);
        $updateBalanceQuery->execute();
    }

    // Update the transaction status
    $updateTransactionQuery = $conn->prepare("UPDATE transactions SET status = ? WHERE id = ?");
    $updateTransactionQuery->bind_param("si", $status, $transactionId);
    $updateTransactionQuery->execute();

    // Reload the page after update
    header("Location: other.php?status=pending");
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Other 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;
        }
        .filter-buttons {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;
        }
        .filter-btn {
            padding: 10px 20px;
            border: none;
            cursor: pointer;
            background-color: #4CAF50;
            color: white;
            border-radius: 5px;
            margin-right: 10px;
        }
        .filter-btn.active {
            background-color: #2E7D32;
        }
    </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>Other Transactions</h3>
    </div>

    <!-- Container -->
    <div class="container">
        
        <!-- Filter Buttons -->
        <div class="filter-buttons">
            <a href=" other.php?status=pending">
                <button class="filter-btn <?php echo ($statusFilter == 'pending') ? 'active' : ''; ?>">Pending</button>
            </a>
            <a href=" other.php?status=completed">
                <button class="filter-btn <?php echo ($statusFilter == 'completed') ? 'active' : ''; ?>">Completed</button>
            </a>
            <a href=" other.php?status=failed">
                <button class="filter-btn <?php echo ($statusFilter == 'failed') ? 'active' : ''; ?>">Failed</button>
            </a>
            <a href=" other.php?status=all">
                <button class="filter-btn <?php echo ($statusFilter == 'all') ? 'active' : ''; ?>">All</button>
            </a>
        </div>

        <!-- Transaction List -->
        <?php foreach($transactions as $transaction): ?>
            <div class="transaction">
                <!-- Title -->
                <h4><?php echo htmlspecialchars($transaction['title']); ?></h4>
                
                <!-- User Name -->
                <p><strong>User:</strong> <?php echo htmlspecialchars($transaction['user_name']); ?></p>

                <!-- Dynamic fields based on title -->
                <?php if ($transaction['title'] == 'SEND MONEY'): ?>
                    <!-- Receiver Name -->
                    <p><strong>Receiver:</strong> <?php echo htmlspecialchars($transaction['receiver_name']); ?></p>
                    <p><strong>Amount:</strong> ৳<?php echo number_format($transaction['amount'], 2); ?></p>
                    <p><strong>Date:</strong> <?php echo htmlspecialchars($transaction['date']); ?></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>

                <?php elseif ($transaction['title'] == 'MOBILE RECHARGE'): ?>
                    <!-- Mobile Recharge -->
                    <p><strong>Account Number:</strong> <span onclick="copyToClipboard('<?php echo htmlspecialchars($transaction['account_number']); ?>')"><?php echo htmlspecialchars($transaction['account_number']); ?></span>   </p>
                    <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>
                    <div class="btn-container">
                        <button class="btn btn-success" onclick="updateStatus(<?php echo $transaction['id']; ?>, 'completed')">Success</button>
                        <button class="btn btn-failed" onclick="updateStatus(<?php echo $transaction['id']; ?>, 'failed')">Failed</button>
                    </div>

                <?php elseif ($transaction['title'] == 'SIM OFFER'): ?>
                    <!-- SIM Offer -->
                    <p><strong>Offer Name:</strong> <?php echo htmlspecialchars($transaction['offer_name']); ?></p>
                    <p><strong>Account Number:</strong> <span onclick="copyToClipboard('<?php echo htmlspecialchars($transaction['account_number']); ?>')"><?php echo htmlspecialchars($transaction['account_number']); ?></span>   </p>
                    <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>
                    <div class="btn-container">
                        <button class="btn btn-success" onclick="updateStatus(<?php echo $transaction['id']; ?>, 'completed')">Success</button>
                        <button class="btn btn-failed" onclick="updateStatus(<?php echo $transaction['id']; ?>, 'failed')">Failed</button>
                    </div>

                <?php elseif ($transaction['title'] == 'PAY BILL'): ?>
                    <!-- Pay Bill -->
                    <p><strong>Bill Name:</strong> <?php echo htmlspecialchars($transaction['bill_name']); ?></p>
                    <p><strong>Account Holder:</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>
                    <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>
                    <div class="btn-container">
                        <button class="btn btn-success" onclick="updateStatus(<?php echo $transaction['id']; ?>, 'completed')">Success</button>
                        <button class="btn btn-failed" onclick="updateStatus(<?php echo $transaction['id']; ?>, 'failed')">Failed</button>
                    </div>
                <?php endif; ?>
            </div>
        <?php endforeach; ?>
    </div>

    <script>
        // Function to update transaction status
        function updateStatus(transactionId, status) {
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = '';

            const inputId = document.createElement('input');
            inputId.type = 'hidden';
            inputId.name = 'transaction_id';
            inputId.value = transactionId;

            const inputStatus = document.createElement('input');
            inputStatus.type = 'hidden';
            inputStatus.name = 'status';
            inputStatus.value = status;

            form.appendChild(inputId);
            form.appendChild(inputStatus);

            document.body.appendChild(form);
            form.submit();
        }

        // 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>
