
        <?php

        include('connection.php');

        if (!isset($_POST['remove'])) {
            // Invalid request method
            header("Location: add_credit.php?error=Invalid request method.");
            exit();
        }

        $userId = mysqli_real_escape_string($conn, $_POST['user_id']);
        $user_type = mysqli_real_escape_string($conn, $_POST['user_type']);
        $credit = mysqli_real_escape_string($conn, $_POST['credit']);
        $credit_note = mysqli_real_escape_string($conn, $_POST['credit_note']);
        $currentDateTime = date('Y-m-d H:i:s');
        $added_by = "Admin";
        $credit_type="Removed Credit";
       

        // Calculate the total credit removed from remove_credit table for the specific user
        $sql_remove_credit = "SELECT SUM(credit) AS total_removed_credit FROM remove_credit WHERE user_id='$userId'";
        $res_remove_credit = mysqli_query($conn, $sql_remove_credit);
        $row_remove_credit = mysqli_fetch_assoc($res_remove_credit);
        $totalRemovedCredit = $row_remove_credit['total_removed_credit'];

        // Calculate the total credit added in credit table for the specific user
        $sql_credit = "SELECT SUM(credit) AS total_credit FROM credit WHERE user_id='$userId'";
        $res_credit = mysqli_query($conn, $sql_credit);
        $row_credit = mysqli_fetch_assoc($res_credit);
        $totalCredit = $row_credit['total_credit'];

        // Calculate the net credit for the user (credit - removed_credit)
        $netCredit = $totalCredit - $totalRemovedCredit;
        if ($credit > $netCredit){
            header("Location: remove_credit.php?error=User do not have credit");
        }
        else{
            $sql = "INSERT INTO remove_credit (added_by, user_type, user_id, credit, credit_type,credit_note,date_time) VALUES ('$added_by','$user_type','$userId','$credit','$credit_type','$credit_note','$currentDateTime')";
            $result = mysqli_query($conn, $sql);
    
            if ($result) {
                header("Location: remove_credit.php?success=Credit Removed Successfully!!!");
            } else {
                header("Location: remove_credit.php?error=Failed insertion!!!");
            }
        }
       
        exit();
        ?>