<?php
include 'admin-header.php';

$message = '';
// Handle the approve/reject actions from the form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['transaction_id'])) {
    $transaction_id = intval($_POST['transaction_id']);
    $action = $_POST['action'];
    $admin_notes = $_POST['admin_notes'] ?? '';

    // Fetch transaction details to prevent re-processing and get user_id/amount
    $stmt = $conn->prepare("SELECT user_id, amount, status FROM transactions WHERE id = ?");
    $stmt->bind_param("i", $transaction_id);
    $stmt->execute();
    $transaction = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if ($transaction && $transaction['status'] == 'Pending') {
        if ($action == 'approve') {
            // Use a database transaction for safety
            $conn->begin_transaction();
            try {
                // 1. Add funds to the user's wallet
                $stmt1 = $conn->prepare("UPDATE users SET wallet_balance = wallet_balance + ? WHERE id = ?");
                $stmt1->bind_param("di", $transaction['amount'], $transaction['user_id']);
                $stmt1->execute();
                
                // 2. Update the transaction status to 'Completed'
                $stmt2 = $conn->prepare("UPDATE transactions SET status = 'Completed', admin_notes = ? WHERE id = ?");
                $stmt2->bind_param("si", $admin_notes, $transaction_id);
                $stmt2->execute();
                
                $conn->commit();
                $message = '<div class="alert alert-success">Transaction approved and funds have been added to the user\'s wallet.</div>';
            } catch (mysqli_sql_exception $e) {
                $conn->rollback();
                $message = '<div class="alert alert-danger">Error processing approval. The transaction has been rolled back.</div>';
            }
        } elseif ($action == 'reject') {
            $stmt = $conn->prepare("UPDATE transactions SET status = 'Rejected', admin_notes = ? WHERE id = ?");
            $stmt->bind_param("si", $admin_notes, $transaction_id);
            $stmt->execute();
            $message = '<div class="alert alert-info">Transaction has been rejected. No funds were added.</div>';
        }
    } else {
        $message = '<div class="alert alert-warning">This transaction may have already been processed or could not be found.</div>';
    }
}
?>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">Top-Up Requests</h1>
</div>
<?php echo $message; ?>

<div class="card shadow-sm">
    <div class="card-header fw-bold">Pending Top-Up Verifications</div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover align-middle">
                <thead class="table-dark">
                    <tr>
                        <th>User</th>
                        <th>Amount</th>
                        <th>Method</th>
                        <th>Reference #</th>
                        <th class="text-center">Proof</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $sql = "SELECT t.*, u.full_name, u.email 
                            FROM transactions t 
                            JOIN users u ON t.user_id = u.id 
                            WHERE t.status = 'Pending' AND t.transaction_type = 'Top-up' 
                            ORDER BY t.created_at ASC";
                    $result = $conn->query($sql);
                    if ($result && $result->num_rows > 0):
                        while($row = $result->fetch_assoc()):
                    ?>
                    <tr>
                        <td>
                            <strong><?php echo htmlspecialchars($row['full_name']); ?></strong>
                            <br><small class="text-muted"><?php echo htmlspecialchars($row['email']); ?></small>
                        </td>
                        <td class="fw-bold text-success fs-5">₱<?php echo number_format($row['amount'], 2); ?></td>
                        <td><?php echo htmlspecialchars($row['payment_method'] ?? 'N/A'); ?></td>
                        <td><?php echo htmlspecialchars($row['reference_number'] ?? 'N/A'); ?></td>
                        <td class="text-center">
                            <a href="../<?php echo htmlspecialchars($row['proof_of_payment_url']); ?>" target="_blank" class="btn btn-sm btn-outline-primary">View Proof</a>
                        </td>
                        <td style="min-width: 280px;">
                            <form method="POST">
                                <input type="hidden" name="transaction_id" value="<?php echo $row['id']; ?>">
                                <div class="input-group input-group-sm">
                                    <input type="text" name="admin_notes" placeholder="Notes (optional for reject)" class="form-control">
                                    <button type="submit" name="action" value="approve" class="btn btn-success" title="Approve Transaction"><i class="bi bi-check-circle-fill"></i></button>
                                    <button type="submit" name="action" value="reject" class="btn btn-danger" title="Reject Transaction"><i class="bi bi-x-circle-fill"></i></button>
                                </div>
                            </form>
                        </td>
                    </tr>
                    <?php endwhile; else: ?>
                        <tr><td colspan="6" class="text-center text-muted p-4">There are no pending top-up requests.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php include 'admin-footer.php'; ?>
