<?php
session_start();
include "connection.php";
include 'functions.php';
include 'config.php';

if (!isset($_POST['agree'])) {
    echo "<script>toastr.error('Please check the agreement box!', 'Error')</script>";
    exit;
}

$crypto   = $_POST['crypto'];
$amount   = (float) $_POST['amount'];
$wallet   = trim($_POST['wallet']);
$username = $_SESSION['user_name'];
$date     = date('Y-m-d');
$transaction_id = md5(uniqid(true));

if ($amount <= 0) {
    echo "<script>toastr.error('Invalid amount!', 'Error')</script>";
    exit;
}

/* 🔎 VERIFY CRYPTO COLUMN EXISTS */
$checkColumn = mysqli_query(
    $conn,
    "SELECT COLUMN_NAME 
     FROM INFORMATION_SCHEMA.COLUMNS 
     WHERE TABLE_SCHEMA = DATABASE()
       AND TABLE_NAME = 'users'
       AND COLUMN_NAME = '$crypto'"
);

if (mysqli_num_rows($checkColumn) === 0) {
    echo "<script>toastr.error('Invalid wallet selected!', 'Error')</script>";
    exit;
}

/* 🔒 LOCK USER ROW */
$user = mysqli_query($conn, "
    SELECT user_email, `$crypto`, total_balance 
    FROM users 
    WHERE user_name='$username' 
    FOR UPDATE
");

$row = mysqli_fetch_assoc($user);

$email         = $row['user_email'];
$cryptobalance = (float) $row[$crypto];
$totalbalance  = (float) $row['total_balance'];

if ($amount < $min_sending) {
    echo "<script>toastr.error('Minimum sending amount is $min_sending USD!', 'Error')</script>";
    exit;
}

if ($amount > $cryptobalance) {
    echo "<script>toastr.error('Insufficient balance!', 'Error')</script>";
    exit;
}

/* 🔐 ATOMIC UPDATE (NO NEGATIVE BALANCE) */
$update = mysqli_query($conn, "
    UPDATE users 
    SET 
        `$crypto` = `$crypto` - $amount,
        total_balance = total_balance - $amount
    WHERE user_name='$username' AND `$crypto` >= $amount
");

if (mysqli_affected_rows($conn) === 0) {
    echo "<script>toastr.error('Transaction failed. Please retry.', 'Error')</script>";
    exit;
}

/* 🧾 INSERT TRANSACTION */
mysqli_query($conn, "
    INSERT INTO transactions 
    (transaction_id, username, currency, amount, type, date, wallet_address)
    VALUES 
    ('$transaction_id','$username','$crypto','$amount','Send','$date','$wallet')
");

echo "<script>toastr.success('Crypto sent successfully!', 'Success')</script>";
echo "<script>setTimeout(() => window.location.href='transactions.php', 1000)</script>";



