<?php
ob_start();
session_start();
error_reporting(0);
include("../config/theconfig.php");
include("header.php");

// Redirect if the user is not logged in
if (!isset($_SESSION['customerid'])) {
    header('Location: login.php?error=nologin');
    exit();
}

// Check for the database connection
if (!isset($conn) || !$conn) {
    die("Database connection failed. Please check the 'theconfig.php' file.");
}

// Use a prepared statement to get the customer's account data
$sql_acc = "SELECT * FROM accounts WHERE customerid = ?";
if ($stmt_acc = mysqli_prepare($conn, $sql_acc)) {
    mysqli_stmt_bind_param($stmt_acc, "s", $_SESSION['customerid']);
    mysqli_stmt_execute($stmt_acc);
    $acc_result = mysqli_stmt_get_result($stmt_acc);
    mysqli_stmt_close($stmt_acc);
} else {
    die('Error preparing account statement: ' . mysqli_error($conn));
}

// Get the values from the POST request safely for older PHP versions
$beneficiary_rname = isset($_POST['rname']) ? $_POST['rname'] : '';
$beneficiary_acctno = isset($_POST['acctno']) ? $_POST['acctno'] : '';
$sender_name = isset($_SESSION['customername']) ? $_SESSION['customername'] : '';
$sender_acct = isset($_POST['acct']) ? $_POST['acct'] : '';
$amountTransferred = isset($_POST['pay_amt']) ? $_POST['pay_amt'] : '';

// Variables for success message, using the corrected values
$beneficiaryDetails = htmlspecialchars($beneficiary_rname) . " (Account No: " . htmlspecialchars($beneficiary_acctno) . ")";
$senderDetails = htmlspecialchars($sender_name) . " (Account No: " . htmlspecialchars($sender_acct) . ")";
$theReference = "TXN" . rand(1000000, 9999999);
$paymentType = "Outward Transfer";
$paidOn = date("d M Y h:i A");

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Ue</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="shortcut icon" href="assets/images/favicon.ico">
    <link href="assets/css/bootstrap.min.css" id="bootstrap-style" rel="stylesheet" type="text/css" />
    <link href="assets/css/icons.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/css/app.min.css" id="app-style" rel="stylesheet" type="text/css" />
    <script src="assets/libs2/custom/sweetalert.min.js"></script>
    <style>
        .swal-text {
            font-size: 13px;
        }
    </style>
</head>

<body data-sidebar="colored">
    <div id="layout-wrapper">
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0 font-size-18">Bank Transfer</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="javascript: void(0);">Dashboard</a></li>
                                        <li class="breadcrumb-item active">Bank Transfer</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-xl-12">
                            <div class="card">
                                <div class="card-body">
                                    <h5 class="card-title">Dear, <?php echo htmlspecialchars($_SESSION['customername']); ?></h5>
                                    <p class="card-title-desc">
                                        Your IP Address: <?php echo htmlspecialchars($_SERVER['REMOTE_ADDR']); ?> has been logged on our server <br />
                                        at <?php echo date("h:i A d M Y"); ?> to monitor money laundering.
                                    </p>
                                    Please, ensure to fill in the fields correctly. <br/>
                                    
                                    <form id="transferForm" name="form1" method="post" action="internationalbankstransfer.php">
                                        <?php 
                                        if (isset($_REQUEST['error'])) {
                                            switch ($_REQUEST['error']) {
                                                case 'nodetails':
                                                    echo "<h3 style=\"color:red; width:fill-available; text-align:center;\">Details Missing or Invalid. <br/>Payment Failed</h3>";
                                                    break;
                                                case 'WrongPassword':
                                                    echo "<script>swal('Error!', 'Wrong Password Entered!', 'error').then((value) => {window.location='international.php'})</script>";
                                                    break;
                                                case 'insufficientbalance':
                                                    echo "<script>swal('Error!', 'Dear customer upon every international transfer 10% would be charged from you in other to complete transaction contact customer support via email!', 'error').then((value) => {window.location='international.php'})</script>";
                                                    break;
                                                case 'cot':
                                                    echo "<script>swal('Error!', 'Wrong COT Code Entered! Dear customer upon every international transfer 10% would be charged from you in other to complete transaction contact customer support via email', 'error').then((value) => {window.location='international.php'})</script>";
                                                    break;
                                                case 'imf':
                                                    echo "<script>swal('Error!', 'Wrong IMF Code Entered! Dear customer upon every international transfer 10% would be charged from you in other to complete transaction contact customer support via email', 'error').then((value) => {window.location='international.php'})</script>";
                                                    break;
                                                case 'accountnotfound':
                                                    echo "<script>swal('Error!', 'Wrong Account Number. Please Check The Account Number And Try Again!', 'error').then((value) => {window.location='international.php'})</script>";
                                                    break;
                                                default:
                                                    echo "<h3 style=\"color:red; width:fill-available; text-align:center;\">" . htmlspecialchars($_REQUEST['error']) . "</h3>";
                                                    break;
                                            }
                                        }

                                        if (isset($_REQUEST['success']) && $_REQUEST['success'] == 'successful') {
                                            // The JavaScript for the success message is unchanged.
                                            // Ensure the PHP variables are correctly set before this block.
                                            echo '<script>
                                                swal({
                                                    title: "Transfer Successful!",
                                                    html: `
                                                        <div style="font-size: 16px;">
                                                            <div style="text-align: center; font-weight: bold; font-size: 18px;">
                                                                Amount: ₦<?php echo htmlspecialchars($amountTransferred); ?>
                                                            </div>
                                                            <hr>
                                                            <div style="display: flex; justify-content: space-between;">
                                                                <div><strong>Beneficiary Details:</strong></div>
                                                                <div><?php echo htmlspecialchars($beneficiaryDetails); ?></div>
                                                            </div>
                                                            <hr>
                                                            <div style="display: flex; justify-content: space-between;">
                                                                <div><strong>Sender Details:</strong></div>
                                                                <div><?php echo htmlspecialchars($senderDetails); ?></div>
                                                            </div>
                                                            <hr>
                                                            <div style="display: flex; justify-content: space-between;">
                                                                <div><strong>Paid On:</strong></div>
                                                                <div><?php echo htmlspecialchars($paidOn); ?></div>
                                                            </div>
                                                            <hr>
                                                            <div style="display: flex; justify-content: space-between;">
                                                                <div><strong>Transaction Reference:</strong></div>
                                                                <div><?php echo htmlspecialchars($theReference); ?></div>
                                                            </div>
                                                            <hr>
                                                            <div style="display: flex; justify-content: space-between;">
                                                                <div><strong>Payment Type:</strong></div>
                                                                <div><?php echo htmlspecialchars($paymentType); ?></div>
                                                            </div>
                                                            <hr>
                                                            <div style="text-align: center; margin-top: 20px;">
                                                                <button onclick="window.print();" style="padding: 10px 20px; background-color: #4CAF50; color: white; border: none; cursor: pointer;">Print Receipt</button>
                                                            </div>
                                                        </div>
                                                    `,
                                                    icon: "success",
                                                    confirmButtonText: "OK3",
                                                    customClass: {
                                                        container: "swal-text",
                                                    }
                                                }).then((value) => {
                                                    window.location = "international.php";
                                                });
                                            </script>';
                                        }
                                        ?>

                                        <div class="form-floating mb-3">
                                            <input type="text" class="form-control" name="bank" id="bank" placeholder="Enter Receiver's Bank" required>
                                            <label for="floatingnameInput">Receiver's Bank</label>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="form-floating mb-3">
                                                    <input type="text" class="form-control" name="bankadd" id="bankadd" placeholder="Receiver's Bank Address" required>
                                                    <label for="bankadd">Receiver's Bank Address</label>
                                                </div>
                                            </div>

                                            <div class="col-md-6">
                                                <div class="form-floating mb-3">
                                                    <input type="text" class="form-control" name="rname" id="ac_no" placeholder="Receiver's Name" required>
                                                    <label for="rname">Receiver's Name</label>
                                                </div>
                                            </div>

                                            <div class="col-md-6">
                                                <div class="form-floating mb-3">
                                                    <input type="text" class="form-control" name="acctno" id="acctno" placeholder="Receiver's Bank Account Number" required>
                                                    <label for="acctno">Receiver's Bank Account Number</label>
                                                </div>
                                            </div>

                                            <div class="col-md-6">
                                                <div class="form-floating mb-3">
                                                    <input type="text" class="form-control" name="swift" id="swift" placeholder="Swift/Aba Routing Number" required>
                                                    <label for="swift">Swift/Aba Routing Number</label>
                                                </div>
                                            </div>

                                            <div class="col-md-6">
                                                <div class="form-floating mb-3">
                                                    <input type="text" class="form-control" min="0" name="pay_amt" id="pay_amt" placeholder="Enter Amount To Transfer" required>
                                                    <label for="pay_amt">Enter Amount To Transfer</label>
                                                    <span id="amountError" class="text-danger"></span> </div>
                                            </div>

                                            <div class="col-md-6">
                                                <div class="form-floating mb-3">
                                                    <select class="form-select" name="acct" id="acct" aria-label="Select Sender's Account">
                                                        <?php 
                                                        if ($acc_result) {
                                                            mysqli_data_seek($acc_result, 0); // Reset result pointer
                                                            while ($rowsacc = mysqli_fetch_array($acc_result)) {
                                                                echo "<option value='" . htmlspecialchars($rowsacc['accno']) . "'>" . htmlspecialchars($rowsacc['accno']) . "</option>";
                                                            }
                                                        }
                                                        ?>
                                                    </select>
                                                    <label for="acct">Select Sender's Account</label>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <?php
                                        // Fetch available balance again to display
                                        $availableBalance = 0;
                                        $cur = '';
                                        $results_balance = mysqli_query($conn, "SELECT * FROM accounts WHERE customerid='". mysqli_real_escape_string($conn, $_SESSION['customerid']) ."'");
                                        if ($results_balance) {
                                            while ($arrow = mysqli_fetch_array($results_balance)) {
                                                $availableBalance = $arrow['accountbalance'];
                                                $cur = '$'; // Default currency symbol
                                                echo '<h5 class="card-title">Available Balance: ' . htmlspecialchars($cur) . ' ' . number_format($availableBalance, 2) . '</h5>';
                                                echo '<p class="card-title-desc">Account Balance: ' . htmlspecialchars($cur) . ' ' . number_format($arrow['accountbalance'], 2) . '</p>';
                                            }
                                            mysqli_free_result($results_balance);
                                        }
                                        ?>

                                        <div>
                                            <button type="submit" name="pay" id="pay" class="btn btn-primary w-md">Transfer</button>
                                        </div>
                                    </form>
                                </div>
                                </div>
                            </div>
                        </div>
                    </div> </div>
            <?php include 'footer.php' ?>
        </div>
        </div>
    <script src="assets/libs/jquery/jquery.min.js"></script>
    <script src="assets/libs/simplebar/simplebar.min.js"></script>
    <script src="assets/libs/node-waves/waves.min.js"></script>
    <script src="assets/js/app.js"></script>
    <script src="assets/libs2/node_modules/sweetalert2/dist/sweetalert2.js"></script>
    <script src="assets/libs2/customizer.js"></script>
    <script src="assets/libs2/script.js"></script>
    <script src="assets/libs2/custom/sweet-alert.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function () {
            $('#pay_amt').on('input', function () {
                var enteredValue = $(this).val().replace(/[^\d.]/g, '');
                var parsedValue = parseFloat(enteredValue);
                var availableBalance = parseFloat(<?php echo json_encode($availableBalance); ?>);

                if (isNaN(parsedValue) || parsedValue <= 0) {
                    $('#pay').prop('disabled', true);
                    $('#amountError').text('Amount must be greater than 0').show();
                } else if (parsedValue > availableBalance) {
                    $('#pay').prop('disabled', true);
                    $('#amountError').text('Entered amount exceeds available balance!').show();
                } else {
                    $('#pay').prop('disabled', false);
                    $('#amountError').hide();
                }
            });
        });
    </script>
</body>
</html>