<?php

ini_set('display_errors', 1);
error_reporting(E_ALL);

header("Access-Control-Allow-Origin: *");

session_start();
include "../../connect/db.php";

// Check if session variable 'chap' is set
if (!isset($_SESSION['chap'])) {
    echo "Error: Session variable 'chap' is not set.";
    exit();
}

$chap = $_SESSION['chap'];

// Fetch user details
$sql = mysqli_query($con, "SELECT * FROM users WHERE email = '$chap'");
if (!$sql) {
    echo "Error fetching user details: " . mysqli_error($con);
    exit();
}

$row = mysqli_fetch_assoc($sql);
if (!$row) {
    echo "Error: User not found.";
    exit();
}


$account_num = $row['account_num'];

// Validate POST data
$required_fields = ['bankname', 'accountnumber', 'accountholder', 'sortcode', 'description', 'amount', 'balance', 'currency'];
foreach ($required_fields as $field) {
    if (!isset($_POST[$field])) {
        echo "Error: Missing required field $field.";
        exit();
    }
}

$bankname = $_POST['bankname'];
$accountnumber = $_POST['accountnumber'];
$accountholder = $_POST['accountholder'];
$sortcode = $_POST['sortcode'];
$description = $_POST['description'];
$amount = $_POST['amount'];
$balance = $_POST['balance'];
$currency = $_POST['currency'];

$account = $_POST['account'];

// Generate a random transaction ID
$seed = str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789');
shuffle($seed);
$rand = '';
foreach (array_rand($seed, 7) as $k) $rand .= $seed[$k];
$transId = $rand;



// Prepare and execute transfer insertion
$utcNow = date('Y-m-d H:i:s');
$stmt = $con->prepare("INSERT INTO transfers (bankname, accountnumber, accountholder, sortcode, description, amount, transfer_ref, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
if (!$stmt) {
    echo "Error preparing statement: " . mysqli_error($con);
    exit();
}

$stmt->bind_param("ssssssss", $bankname, $accountnumber, $accountholder, $sortcode, $description, $amount, $transId, $utcNow);
if (!$stmt->execute()) {
    echo "Error executing transfer statement: " . $stmt->error;
    exit();
}
$stmt->close();

// Update user transfer reference
$sqlnewn = mysqli_query($con, "UPDATE users SET transfer_ref = '$transId' WHERE email = '$chap'");
if (!$sqlnewn) {
    echo "Error updating user transfer reference: " . mysqli_error($con);
    exit();
}



?>


<div class='modal fade' id='detailsModal' tabindex='-1' aria-labelledby='detailsModalLabel' aria-hidden='true'>
  <div class='modal-dialog'>
  <div class='modal-content'>
    <a href='#' class='close' data-dismiss='modal'><em class='icon ni ni-cross-sm'></em></a>
    <div class='modal-body modal-body-lg'>
        <div class='nk-block-head nk-block-head-xs text-center'>
            <h5 class='nk-block-title'>Review transaction</h5>
            <div class='nk-block-text'>
                <div class='caption-text text-primary display-4'>Kindly review this transaction before proceeding.</div>
            </div>
        </div>
        <div class='nk-block'>
            <div class='buysell-overview'>
               <form action="" id="thisform">
               <ul class='buysell-overview-list'>
                    <li class='buysell-overview-item'>
                        <span class='pm-title'><em class='icon ni ni-alert-circle'></em> Amount</span>
                        <span class='pm-title'><?php echo $amount; ?></span>
                    </li>
                    <li class='buysell-overview-item'>
                        <span class='pm-title'><em class='icon ni ni-alert-circle'></em> Bank Name</span>
                        <span class='pm-currency'><?php echo $bankname; ?></span>
                    </li>
                    <li class='buysell-overview-item'>
                        <span class='pm-title'><em class='icon ni ni-alert-circle'></em> Account Number</span>
                        <span class='pm-currency'><?php echo $accountnumber; ?></span>
                    </li>
                    <li class='buysell-overview-item'>
                        <span class='pm-title'><em class='icon ni ni-alert-circle'></em> Account Holder</span>
                        <span class='pm-currency'><?php echo $accountholder; ?></span>
                    </li>
                    <li class='buysell-overview-item'>
                        <span class='pm-title'><em class='icon ni ni-alert-circle'></em> Description</span>
                        <span class='pm-currency'><?php echo $description; ?></span>
                    </li>
                </ul>
               </form>
            </div>
            <div class='buysell-field form-group'>
                <div class='form-label-group'>
                    <label class='form-label'>Sending from:</label>
                </div>
                <input type='hidden' value='btc' name='bs-currency' id='buysell-choose-currency-modal'>
                <div class='dropdown buysell-cc-dropdown'>
                    <a href='#' class='buysell-cc-choosen dropdown-indicator'>
                        <div class='coin-item coin-btc'>
                            <div class='coin-icon'>
                                <em class='icon ni ni-wallet-out'></em>
                            </div>
                        <?php
$currency = $row['usercurrency'];
$account  = isset($_POST['account']) ? $_POST['account'] : 'checking'; // default is checking

if ($account === 'bsl') {
    $balance = $row['bsl_balance'];
    $accountName = "BSL BALANCE";
} else {
    $balance = $row['checking_balance'];
    $accountName = "CHECKING ACCOUNT";
}
?>

<div class='coin-info'>
    <span class='coin-name'><?php echo $accountName; ?></span>
    <span class='coin-text'><?php echo formatCurrency($balance, $currency); ?></span>
</div>

                        </div>
                    </a>
                </div>
                <div class='clearfix'></div>
                <div class='sub-text-sm text-primary'>* Our transaction fee is included.</div>
            </div>
            <div class='buysell-field form-action text-center'>
                <div>
                    <form action='' method='post'>
                        <input type='hidden' value='1'>
                        <button type="button" class="btn btn-primary btn-block btn-lg eg-swal-av5" 
           data-toggle="modal" data-target="#processingModal" 
        onclick="submitform();">
        Continue transaction
            </button>
                    </form>
                </div>
                <div class='pt-3'>
                    <a href='#' data-dismiss='modal' class='link link-danger'>Cancel transaction</a>
                </div>
            </div>
        </div>
    </div>
</div>

  </div>
</div>



<script>
    function submitform() {
        $.ajax({
            url: "../apps/user/submit-transaction-success.php", // PHP file to process the request
            type: "POST",
            data: {
                transId: "<?php echo addslashes($transId); ?>",
                amount: "<?php echo addslashes($amount); ?>",
                bankname: "<?php echo addslashes($bankname); ?>",
                accountnumber: "<?php echo addslashes($accountnumber); ?>",
                accountholder: "<?php echo addslashes($accountholder); ?>",
                description: "<?php echo addslashes($description); ?>",
                currency: "<?php echo addslashes($currency); ?>",
                account: "<?php echo addslashes($account); ?>"

            },
            success: function(response) {
                if (response == "success") {
                    
                    Swal.fire("Success!", "Transaction successful.", "success");
                    setTimeout(function(){ window.location="transfer_successful.php"} , 2200);

                } else {
                    Swal.fire("Error!", response, "error");
                }
            },
            error: function() {
                Swal.fire("Error!", "Something went wrong.", "error");
            }
        });
    }
</script>


<!-- Processing Modal -->
<!-- Processing Modal -->
<div class="modal fade" id="processingModal" tabindex="-1" aria-labelledby="processingModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content text-center">
      <div class="modal-body">
        <div class="spinner-border text-primary" role="status">
          <span class="sr-only"></span>
        </div>
        <h5 class="mt-3">Transaction Processing</h5>
        <p class="text-muted">Please wait...</p>
      </div>
    </div>
  </div>
</div>
