<?php
include '_db.php';

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

        // $conn->beginTransaction(); // Start transaction

        // Check if the deposit is in 'pending' status
        $check_status_query = $conn->prepare("SELECT amount, userid FROM depositt WHERE payment_id = ? AND status = 'pending'");
        $check_status_query->bind_param("s", $payment_id);
        $check_status_query->execute();
        $status_row = $check_status_query->get_result()->fetch_assoc();

        if ($status_row) {
            // Update deposit status to 'confirmed'
            $update_query = $conn->prepare("UPDATE depositt SET status='confirmed' WHERE payment_id = ?");
            $update_query->bind_param("s", $payment_id);
            $update_query->execute();

            if ($update_query->affected_rows > 0) {
                // Retrieve user's current account balance
                $user_id = $status_row['userid'];
                $balance_query = $conn->prepare("SELECT account_balance FROM user_login WHERE userid = ?");
                $balance_query->bind_param("s", $user_id);
                $balance_query->execute();
                $user_balance_row = $balance_query->get_result()->fetch_assoc();

                if ($user_balance_row) {
                    // Calculate new account balance
                    $deposit_amount = $status_row['amount'];
                    $current_balance = $user_balance_row['account_balance'];
                    $new_balance = $current_balance + $deposit_amount;

                    // Update user's account balance
                    $update_balance_query = $conn->prepare("UPDATE user_login SET account_balance = ? WHERE userid = ?");
                    $update_balance_query->bind_param("ds", $new_balance, $user_id);
                    $update_balance_query->execute();

                    if ($update_balance_query->affected_rows > 0) {
                        $conn->commit(); // Commit transaction
                        $_SESSION['mgs'] = "Deposit confirmed successfully. User account balance updated!";
                    } else {
                        $_SESSION['mgs'] = "Error updating user account balance.";
                    }
                } else {
                    $_SESSION['mgs'] = "User not found.";
                }
            } else {
                $_SESSION['mgs'] = "Error confirming deposit.";
            }
        } else {
            $_SESSION['mgs'] = "Deposit is not in pending status or invalid deposit ID.";
        }
    } catch (Exception $e) {
        // Rollback transaction on error
        $conn->rollback();
        $_SESSION['mgs'] = "Database error: " . $e->getMessage();
    }

    header("Location: " . $_SERVER['HTTP_REFERER']);
} else {
    header("Location: error.php");
    exit();
}
?>
