<?php
// withdraw.php
require 'connect.php';

$total_balance = 0;
$success_message = '';
$error_message = '';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Remove commas from the amount for database storage
    $amount = str_replace(',', '', $_POST['amount']);
    $name = $_POST['name'];
    $usage = $_POST['usage'];

    // Calculate the total balance
    $balance_sql = "SELECT SUM(CASE WHEN type = 'Deposit' THEN amount ELSE -amount END) AS total_balance FROM transactions";
    $balance_result = mysqli_query($conn, $balance_sql);
    $balance_row = mysqli_fetch_assoc($balance_result);
    $total_balance = $balance_row['total_balance'];

    // Check if withdrawal amount is greater than available balance
    if ($amount > $total_balance) {
        $error_message = "Error: Withdrawal amount exceeds available balance.";
    } else {
        // Insert the withdrawal transaction
        $sql = "INSERT INTO transactions (type, amount, name, purpose_usage) VALUES ('Withdraw', '$amount', '$name', '$usage')";

        if (mysqli_query($conn, $sql)) {
            // Format the amount and total balance for display
            $formatted_amount = number_format($amount, 2, '.', ',');
            $formatted_balance = number_format($total_balance - $amount, 2, '.', ',');

            // Prepare the success message
            $success_message = "Withdrawal successful. Amount withdrawn: $formatted_amount. Total balance: $formatted_balance.";
        } else {
            echo "Error: " . $sql . "<br>" . mysqli_error($conn);
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Withdraw</title>
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <script>
        function formatNumber(input) {
            // Remove any non-digit characters except the decimal point
            let value = input.value.replace(/[^\d.]/g, '');

            // Split the value into integer and decimal parts
            let parts = value.split('.');
            let integerPart = parts[0];
            let decimalPart = parts.length > 1 ? parts[1] : '';

            // Format the integer part with thousand separators
            integerPart = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, ',');

            // Limit to two decimal places
            if (decimalPart.length > 2) {
                decimalPart = decimalPart.substring(0, 2);
            }

            // Combine the integer and decimal parts
            input.value = decimalPart ? integerPart + '.' + decimalPart : integerPart;
        }

        function confirmWithdrawal() {
            // Get the withdrawal amount
            var amount = document.getElementById("amount").value;

            // Display a confirmation prompt
            if (confirm("Are you sure you want to withdraw " + amount + "?")) {
                // If the user clicks "OK", the form will be submitted
                document.getElementById("withdrawForm").submit();
            } else {
                // If the user clicks "Cancel", nothing happens
                return false;
            }
        }

        // Go back to the previous page
        function goBack() {
            window.history.back();
        }
    </script>
</head>
<body>
    <div class="container mt-5">
        <h2>Withdraw Form</h2>

        <!-- Show success or error message -->
        <?php
        if (!empty($success_message)) {
            echo "<div class='alert alert-success' role='alert'>$success_message</div>";
        } elseif (!empty($error_message)) {
            echo "<div class='alert alert-danger' role='alert'>$error_message</div>";
        }
        ?>

        <form method="post" action="withdraw.php" id="withdrawForm">
            <div class="form-group">
                <label for="amount">Amount</label>
                <input type="text" class="form-control" id="amount" name="amount" onblur="formatNumber(this)" required>
            </div>
            <div class="form-group">
                <label for="name">Name</label>
                <input type="text" class="form-control" id="name" name="name" required>
            </div>
            <div class="form-group">
                <label for="usage">Usage</label>
                <textarea class="form-control" id="usage" name="usage" rows="3" required></textarea>
            </div><br>
            <button type="button" class="btn btn-primary" onclick="confirmWithdrawal()">Withdraw</button>
            <!--<button type="button" class="btn btn-secondary ml-2" onclick="goBack()">Go Back</button>-->
            <a href="banking.php" class="btn btn-secondary ml-2">Go Back</a>
        </form>
    </div>

    <!-- Bootstrap JS and dependencies -->
    <script src="js/jquery-3.3.1.slim.min.js"></script>
    <script src="js/popper.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
</body>
</html>
