<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

include('con.php');


// Approve QR Payment
if (isset($_GET['approve'])) {
    $qrId = intval($_GET['approve']); // get QR request id
    $date = date("Y-m-d H:i:s");

    // Get the QR request details
    $qrQuery = mysqli_query($ahk_conn, "SELECT * FROM manqr WHERE id='$qrId' AND status=0");
    if (mysqli_num_rows($qrQuery) > 0) {
        $qrData = mysqli_fetch_assoc($qrQuery);
        $username = $qrData['username'];
        $amount   = floatval($qrData['amount']);
        $utr      = $qrData['utr'];

        // Get user balance
        $userQuery = mysqli_query($ahk_conn, "SELECT * FROM users WHERE phone='$username'");
        $userData  = mysqli_fetch_assoc($userQuery);
        $beforeBalance = floatval($userData['balance']);
        $afterBalance  = $beforeBalance + $amount;

        // Start transaction
        mysqli_begin_transaction($ahk_conn);

        try {
            // 1. Update manqr status
            mysqli_query($ahk_conn, "UPDATE manqr SET status=1, afterbalance='$afterBalance' WHERE id='$qrId'");

            // 2. Credit users table
            mysqli_query($ahk_conn, "UPDATE users SET balance='$afterBalance' WHERE phone='$username'");

            // 3. Insert into wallethistory
            mysqli_query($ahk_conn, "
                INSERT INTO wallethistory
                (userid, amount, balance, purpose, status, type)
                VALUES
                ('$username', '$amount', '$afterBalance', 'Qr Payment', 1, 'Credit')
            ");

            // 4. Insert into wallet table
            mysqli_query($ahk_conn, "
                INSERT INTO wallet
                (phone, amount, txn_date, PAYMENTMODE, RESPMSG, BANKTXNID, status)
                VALUES
                ('$username', '$amount', '$date', 'QrCode', 'Txn Success', '$utr', 'success')
            ");

            // Commit transaction
            mysqli_commit($ahk_conn);

            $successMsg = "QR Payment approved and wallet credited successfully.";

        } catch (Exception $e) {
            mysqli_rollback($ahk_conn);
            $errorMsg = "Error approving payment: " . $e->getMessage();
        }
    } else {
        $errorMsg = "Invalid or already approved QR request.";
    }
}

/* ================= FETCH PENDING QR PAYMENTS ================= */
$pending = mysqli_query($ahk_conn, "SELECT * FROM manqr WHERE status=0 ORDER BY id DESC");
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Admin QR Approvals</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container py-4">
    <h3>Pending QR Payments</h3>

    <?php if(isset($errorMsg)): ?>
        <div class="alert alert-danger"><?= $errorMsg ?></div>
    <?php endif; ?>

    <?php if(isset($successMsg)): ?>
        <div class="alert alert-success"><?= $successMsg ?></div>
    <?php endif; ?>

    <table class="table table-bordered table-hover mt-3">
        <thead class="table-primary">
            <tr>
                <th>ID</th>
                <th>User</th>
                <th>Amount</th>
                <th>UTR</th>
                <th>Date</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
        <?php if(mysqli_num_rows($pending) > 0): ?>
            <?php while($row = mysqli_fetch_assoc($pending)): ?>
            <tr>
                <td><?= $row['id'] ?></td>
                <td><?= htmlspecialchars($row['username']) ?></td>
                <td>₹<?= $row['amount'] ?></td>
                <td><?= htmlspecialchars($row['utr']) ?></td>
                <td><?= $row['date'] ?></td>
                <td>
                    <a href="?approve=<?= $row['id'] ?>" class="btn btn-success btn-sm"
                       onclick="return confirm('Approve this payment?');">
                        Approve
                    </a>
                </td>
            </tr>
            <?php endwhile; ?>
        <?php else: ?>
            <tr>
                <td colspan="6" class="text-center">No pending payments</td>
            </tr>
        <?php endif; ?>
        </tbody>
    </table>
</div>
</body>
</html>
