<?php
include '_db.php';

if (isset($_GET['id']) && isset($_GET['status']) && $_GET['status'] == 'confirm') {
    try {
        $wid = $_GET['id'];

        // Turn off autocommit
        $conn->autocommit(false);

        // Check if the current status is 'pending' before updating to 'confirmed'
        $check_status_query = $conn->prepare("SELECT status, amount, userid FROM withdrawals WHERE wid = ?");
        $check_status_query->bind_param("s", $wid); // "s" indicates a string parameter
        $check_status_query->execute();
        $result = $check_status_query->get_result();
        $status_row = $result->fetch_assoc();

        if ($status_row && $status_row['status'] == 'pending') {
            // Update withdrawal status to 'confirmed'
            $update_query = $conn->prepare("UPDATE withdrawals SET status='confirmed' WHERE wid = ?");
            $update_query->bind_param("s", $wid); // "s" indicates a string parameter
            $update_query->execute();

            // Commit transaction
            $conn->commit();

            // Redirect back to the previous page
            header("Location: " . $_SERVER['HTTP_REFERER']);
            exit(); // Stop further execution
        } else {
            $_SESSION['mgs'] = "Withdrawal is not in pending status or invalid withdrawal ID.";
        }
    } catch (mysqli_sql_exception $e) {
        $conn->rollback(); // Rollback transaction
        $_SESSION['mgs'] = "Database error: " . $e->getMessage();
    } finally {
        // Always turn autocommit back on
        $conn->autocommit(true);
    }

    // If an error occurred or the status was not pending, redirect to error page
    header("Location: error.php");
    exit();
} else {
    header("Location: error.php");
    exit();
}

?>
