<?php
// Set the page title for the header
$page_title = "ব্যালেন্স রিকুয়েস্ট";

// 1. Include the authentication check file for security.
// This also provides the DB connection ($conn) and the create_notification() helper function.
require_once 'includes/auth_check.php';

// 2. Handle approve/reject actions submitted from the form
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['request_id'])) {
    $request_id = (int)$_POST['request_id'];
    $user_id = (int)$_POST['user_id'];
    $amount = (float)$_POST['amount'];
    $admin_id = (int)$_SESSION['admin_id'];

    // Action: Approve Request
    if (isset($_POST['approve'])) {
        $conn->begin_transaction();
        try {
            // 1. Update user's balance
            $conn->query("UPDATE users SET balance = balance + $amount WHERE id = $user_id");
            
            // 2. Update the request's status to 'Approved'
            $conn->query("UPDATE add_balance_requests SET status = 'Approved', reviewed_by_admin = $admin_id, reviewed_at = NOW() WHERE id = $request_id");
            
            // 3. Add a record to the main transactions table
            $desc = "Balance added by admin from request #" . $request_id;
            $conn->query("INSERT INTO transactions (user_id, type, amount, description) VALUES ($user_id, 'Add Balance', $amount, '$desc')");
            
            // 4. Log this admin activity
            $log_details = "Request ID: $request_id, User ID: $user_id, Amount: $amount";
            log_activity($conn, $admin_id, 'Approved Balance Request', $log_details);

            // 5. Send a notification to the user
            $notification_title = "ব্যালেন্স যোগ হয়েছে";
            $notification_message = "আপনার ৳" . number_format($amount, 2) . " টাকার ব্যালেন্স রিকুয়েস্টটি Approve করা হয়েছে।";
            create_notification($conn, $user_id, $notification_title, $notification_message);

            $conn->commit();
        } catch (Exception $e) {
            $conn->rollback();
            // Optionally, you can log the error $e->getMessage()
        }
    } 
    // Action: Reject Request
    elseif (isset($_POST['reject'])) {
        $stmt = $conn->prepare("UPDATE add_balance_requests SET status = 'Rejected', reviewed_by_admin = ?, reviewed_at = NOW() WHERE id = ?");
        $stmt->bind_param("ii", $admin_id, $request_id);
        $stmt->execute();
        $stmt->close();
        
        // Log this admin activity
        $log_details = "Request ID: $request_id, User ID: $user_id, Amount: $amount";
        log_activity($conn, $admin_id, 'Rejected Balance Request', $log_details);
        // Optionally, send a notification for rejection as well
    }

    // Redirect to the same page to prevent form resubmission on page refresh
    header("Location: balance_requests.php");
    exit;
}

// 6. Fetch all pending requests to display in the table
$requests = $conn->query(
    "SELECT r.id, r.amount, r.method, r.transaction_id, r.created_at, u.full_name, u.mobile, u.id as user_id
     FROM add_balance_requests r 
     JOIN users u ON r.user_id = u.id 
     WHERE r.status = 'Pending' 
     ORDER BY r.created_at ASC"
);

// Include the admin panel header and sidebar
include 'includes/header.php';
?>

<div class="container-fluid">
    <h2 class="mb-4">পেন্ডিং ব্যালেন্স রিকুয়েস্ট</h2>
    <div class="card shadow-sm">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered table-striped table-hover">
                    <thead class="table-light">
                        <tr>
                            <th>ইউজার</th>
                            <th>মোবাইল</th>
                            <th>পরিমাণ (৳)</th>
                            <th>মাধ্যম</th>
                            <th>TrxID</th>
                            <th>সময়</th>
                            <th>একশন</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($requests && $requests->num_rows > 0): ?>
                            <?php while($row = $requests->fetch_assoc()): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($row['full_name']); ?></td>
                                    <td><?php echo htmlspecialchars($row['mobile']); ?></td>
                                    <td><?php echo number_format($row['amount'], 2); ?></td>
                                    <td><?php echo htmlspecialchars($row['method']); ?></td>
                                    <td><?php echo htmlspecialchars($row['transaction_id']); ?></td>
                                    <td><?php echo date("d M, Y, h:i A", strtotime($row['created_at'])); ?></td>
                                    <td>
                                        <form method="POST" class="d-inline">
                                            <input type="hidden" name="request_id" value="<?php echo $row['id']; ?>">
                                            <input type="hidden" name="user_id" value="<?php echo $row['user_id']; ?>">
                                            <input type="hidden" name="amount" value="<?php echo $row['amount']; ?>">
                                            <button type="submit" name="approve" class="btn btn-success btn-sm" onclick="return confirm('আপনি কি এই রিকুয়েস্টটি Approve করতে নিশ্চিত?')">Approve</button>
                                            <button type="submit" name="reject" class="btn btn-danger btn-sm" onclick="return confirm('আপনি কি এই রিকুয়েস্টটি Reject করতে নিশ্চিত?')">Reject</button>
                                        </form>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="7" class="text-center">কোনো পেন্ডিং রিকুয়েস্ট নেই।</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<?php
// Include the admin panel footer
include 'includes/footer.php';
$conn->close();
?>