<?php $page_title = "Withdraw funds"; ?>
<?php

include 'user_header.php';
include 'session.php';

?>

<style>
#bank_transfer, #crypto {
  display: none;
}

/* Custom modal styles */
.custom-modal {
  display: none;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.custom-modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  width: 400px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.custom-modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #ddd;
  padding-bottom: 10px;
  margin-bottom: 10px;
}

.custom-modal-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>

<?php
require "../database/connect.php";



$mods = "";
$error = ""; // Initialize error variable
$msg = "";



if (isset($_POST['withdraw'])) {
    $amount = $_POST['amount'];
    $method = $_POST['method'];
    $coin = $_POST['coin'] ?? '';
    $wallet_add = $_POST['wallet_add'] ?? '';
    $bank_name = $_POST['bankName'] ?? '';
    $acct_name = $_POST['accountName'] ?? '';
    $acct_no = $_POST['accountNumber'] ?? '';
    $acct_swift = $_POST['sort_code'] ?? '';

    if ($method == "Bank") {
        $withdrawal_des = "Bank Name:$bank_name, Acct No:$acct_no, Account Name:$acct_name, Swift Code:$acct_swift";
        $t_mode = "$method";
    } else {
        $withdrawal_des = $wallet_add;
        $t_mode = "$method ($coin)";
    }

    if ($amount > $profit) {
        $error = "<div class='alert alert-danger d-flex align-items-center' role='alert'>
          <i class='fa fa-warning'></i> &nbsp; Please your balance is too low, make a deposit!
        </div>";
    } elseif($upgrade == 0) {
        $error = "<div class='alert alert-danger d-flex align-items-center' role='alert'>
          <i class='fa fa-warning'></i> &nbsp; Please upgrade your account to be able to make withdrawal!
        </div>";
    } else {
        $_SESSION['amount'] = $amount;
        $_SESSION['method'] = $method;
        $_SESSION['coin'] = $coin;
        $_SESSION['wallet_add'] = $wallet_add;
        $_SESSION['bankName'] = $bank_name;
        $_SESSION['accountName'] = $acct_name;
        $_SESSION['accountNumber'] = $acct_no;
        $_SESSION['sort_code'] = $acct_swift;
        $mods = "show"; // Set mods to show the modal
    }
}


if (isset($_POST['wpin'])) {  // Ensure we check the correct POST key
    $pin = trim($_POST['wpin']);
    
    if (!empty($pin)) {
        if ($pin != $Withdrawal_Pins) { // Ensure `$Withdrawal_Pins` is defined
            $error = "<div class='alert alert-danger d-flex align-items-center' role='alert'>
              <i class='fa fa-warning'></i> &nbsp; Withdrawal pin is not correct!
            </div>";
        } else {
            // Ensure session variables exist
            if (!isset($_SESSION['amount'])) {
                die("Some session variables are missing!");
            }

            // $method = $_SESSION['method'];
            $amount = $_SESSION['amount'];
            // $wallett = $_SESSION['wallett'];
            // $bname = $_SESSION['bname'];
            // $anum = $_SESSION['anum'];
            // $aname = $_SESSION['aname'];

            $transaction_status = "pending";
            $transaction_type = "Profit withdrawal";
            $transaction_date = date("Y-m-d H:i:s"); // Corrected to 24-hour format

            // Generate a unique transaction reference
            $trnx_hash = rand(100000, 999999);

            // Ensure `$connection` and `$user_id` are defined before using them
            if (!isset($connection) || !isset($user_id)) {
                die("Database connection or user ID is missing!");
            }

            // Use prepared statements to prevent SQL injection
            $query = $connection->prepare("INSERT INTO transaction 
                (trans_ref, transaction_user_id, transaction_type, transaction_status, t_mode, transaction_amount, transaction_date) 
                VALUES (?, ?, ?, ?, ?, ?, ?)");
            $query->bind_param("sssssss", $trnx_hash, $user_id, $transaction_type, $transaction_status, $transaction_type, $amount, $transaction_date);
            $query->execute();

            if ($query->affected_rows > 0) {
                // Update balance safely
                $update_bal = $connection->prepare("UPDATE users SET profit = profit - ? WHERE user_id = ?");
                $update_bal->bind_param("di", $amount, $user_id);
                $update_bal->execute();

                if ($update_bal->affected_rows > 0) {
                    $msg = "<div class='alert alert-success d-flex align-items-center' role='alert'>
                      <i class='fa fa-check'></i> &nbsp; Withdrawal successful!
                    </div>";
                } else {
                    $msg = "<div class='alert alert-warning d-flex align-items-center' role='alert'>
                      <i class='fa fa-exclamation-triangle'></i> &nbsp; Withdrawal recorded, but balance update failed.
                    </div>";
                }
            } else {
                $msg = "<div class='alert alert-danger d-flex align-items-center' role='alert'>
                  <i class='fa fa-warning'></i> &nbsp; Failed to process withdrawal!
                </div>";
            }
        }
    }
}


?>

<?php
$dep_status = $_GET['status'] ?? '';
if ($dep_status == "success") {
    echo "<div class='alert alert-success d-flex align-items-center' role='alert'>
      <i class='fa fa-check'></i> &nbsp; Proof of Deposit Uploaded successfully
    </div>";
} elseif ($dep_status == "error") {
    echo "<div class='alert alert-danger d-flex align-items-center' role='alert'>
      <i class='fa fa-warning'></i> &nbsp; Sorry an error occurred. Please try again later or contact support
    </div>";
} else {
    echo $error; // Display any other errors
}
?>

<?php 
if($mods != ""){
    echo "<script>  
    window.onload = function() {
        showCustomModal();
    };
    </script>";
}
?>

<div class="container-fluid content-inner pb-0">
    <div class="row">
        <div class="col-lg-12">
            <div class="card">
                <h5 class="p-3">Make a Withdrawal</h5>
                <div class="p-3">
                    <div class="mb-3">
                        <label for="exampleInputEmail1" class="form-label">Select a Withdrawal Method</label>
                        <select name="method" class="form-control" onchange="showDiv(this)">
                            <option value="" readonly>-- select --</option>
                            <option value="crypto">Crypto withdrawal</option>
                            <option value="bank">Bank withdrawal</option>
                        </select>
                        <br>
                        <button type="button" class="btn btn-primary" onclick="popUpError()" id="popUpError">Proceed</button>
                    </div>

                    <div class="p-3" id="bank_transfer">
                        <form action="" method="post">
                            <fieldset>
                                <input type="text" name="method" class="form-control" value="Bank" style="display:none">
                                <div class="mb-3">
                                    <label for="exampleInputAmount" class="form-label">Amount</label>
                                    <input type="text" name="amount" class="form-control" id="exampleInputAmount" required>
                                </div>
                                <div class="mb-3">
                                    <label for="exampleInputAdd" class="form-label">Bank Account Number</label>
                                    <input type="text" name="accountNumber" class="form-control" id="exampleInputAdd" required>
                                </div>
                                <div class="mb-3">
                                    <label for="exampleInputAd" class="form-label">Bank Name</label>
                                    <input type="text" name="bankName" class="form-control" id="exampleInputAd" required>
                                </div>
                                <div class="mb-3">
                                    <label for="exampleInputAdsd" class="form-label">Account Name</label>
                                    <input type="text" name="accountName" class="form-control" id="exampleInputAdsd" required>
                                </div>
                                <div class="mb-3">
                                    <label for="exampleInputssn" class="form-label">Bank Sort Code</label>
                                    <input type="text" name="sort_code" class="form-control" id="exampleInputssn">
                                </div>
                                <button name="withdraw" type="submit" class="btn btn-primary">Proceed</button>
                            </fieldset>
                        </form>
                    </div>

                    <div class="p-3" id="crypto">
                        <form action="" method="post">
                            <fieldset>
                                <input type="text" name="method" class="form-control" value="Crypto" style="display:none">
                                <div class="mb-3">
                                    <label for="exampleInputAmount" class="form-label">Amount</label>
                                    <input type="text" name="amount" class="form-control" id="exampleInputAmount" required>
                                </div>
                                <div class="mb-3">
                                    <label for="exampleInputAdd" class="form-label">Select a Coin</label>
                                    <select name="coin" class="form-control" required>
                                        <option value="">--Select Coin--</option>
                                        <option value="BTC">BTC</option>
                                        <option value="ETH">ETH</option>
                                        <option value="LTC">LTC</option>
                                        <option value="USDT">USDT</option>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label for="exampleInputAd" class="form-label">Wallet Address</label>
                                    <input type="text" name="wallet_add" class="form-control" id="exampleInputAd" required>
                                </div>
                                <button name="withdraw" type="submit" class="btn btn-primary">Proceed</button>
                            </fieldset>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- Custom Modal -->
        <div id="customModal" class="custom-modal">
            <div class="custom-modal-content">
                <div class="custom-modal-header">
                    <h5>Withdrawal</h5>

        
                    <button type="button" onclick="hideCustomModal()">&times;</button>
                </div>
                <span style="color: red";> <i class='fa fa-warning'></i> &nbsp; Request for your withdrawal pin </span> <br> <br>
                <div class="custom-modal-body">
                    <form method="post" action="">
                        <input type="text" name="wpin" placeholder="Enter withdrawal pin">
                        <div class="custom-modal-footer">
                            <button type="submit" name="pin" class="btn btn-primary">CONTINUE</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <?php include 'tradingview_widget.php'; ?>
    </div>
</div>

<script>
function popUpError() {
    alert("ERROR! Please select a withdrawal method!");
}

function showDiv(select) {
    if (select.value == 'crypto') {
        document.getElementById('bank_transfer').style.display = "none";
        document.getElementById('crypto').style.display = "block";
        document.getElementById('popUpError').style.display = "none";
    } else {
        document.getElementById('crypto').style.display = "none";
        document.getElementById('popUpError').style.display = "block";
    }

    if (select.value == 'bank') {
        document.getElementById('bank_transfer').style.display = "block";
        document.getElementById('crypto').style.display = "none";
        document.getElementById('popUpError').style.display = "none";
    } else {
        document.getElementById('bank_transfer').style.display = "none";
    }
}

// Custom Modal Functions
function showCustomModal() {
    document.getElementById('customModal').style.display = "flex";
}

function hideCustomModal() {
    document.getElementById('customModal').style.display = "none";
}
</script>

<?php include 'user_footer.php'; ?>