<?php
session_start();

if (isset($_SESSION['username']) == true) {
    include 'master.php';
    $username = $_SESSION['username'];
} else {
    header("location:login");
}
?>
<!--page-wrapper-->
<div class="page-wrapper">
    <!--page-content-wrapper-->
    <div class="page-content-wrapper">
        <div class="page-content">
            <!--breadcrumb-->
            <div class="page-breadcrumb d-none d-md-flex align-items-center mb-3">
                <div class="breadcrumb-title pr-3">Edit Post</div>
                <div class="pl-3">
                    <nav aria-label="breadcrumb">
                        <ol class="breadcrumb mb-0 p-0">
                            <li class="breadcrumb-item"><a href="javascript:;"><i class='bx bx-home-alt'></i></a>
                            </li>
                            <li class="breadcrumb-item active" aria-current="page">Layouts</li>
                        </ol>
                    </nav>
                </div>
                <div class="ml-auto">
                    <div class="btn-group">
                        <button type="button" class="btn btn-primary">Active</button>
                    </div>
                </div>
            </div><br><br>
            <!--end breadcrumb-->
            <div class="row">
                <div class="col-12 col-lg-9 mx-auto">
                    <div class="card radius-15">
                        <div class="card-body">
                            <form action="" method="post" enctype="multipart/form-data">
                                <div class="form-group">
                                    <label><b>Select Transaction Type</b></label>
                                    <select class="form-control border-left" name="transaction_type" id="transactionType">
									<option selected disabled value="">Select Transaction Type</option>
                                        <option value="deposit">Deposit</option>
                                        <option value="loan">Loan</option>
                                        <option value="withdrawal">Withdrawal</option>
                                        <option value="transfer">Transfer</option>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label><b>Select Email</b></label>
                                    <?php
                                    $balanceMap = [];
                                    $result = $conn->query("SELECT email, balance FROM users");
                                    if ($result && $result->num_rows > 0) {
                                        while ($row = $result->fetch_assoc()) {
                                            $balanceMap[$row['email']] = (float)$row['balance'];
                                        }
                                    }
                                    ?>
                                    <select class="form-control border-left" name="email" id="emailSelect">
                                        <option selected disabled value="">Select Email</option>
                                        <?php foreach ($balanceMap as $em => $bal): ?>
                                            <option value="<?php echo htmlspecialchars($em); ?>"><?php echo htmlspecialchars($em); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="form-group" id="currentBalanceGroup" style="display:none;">
                                    <label>Current Balance</label>
                                    <input type="text" class="form-control border-left bg-light" id="currentBalanceDisplay" readonly value="">
                                </div>
                                

                                <!-- Additional fields for each transaction type -->
                                <div id="additionalFields">
                                    <!-- Fields for Deposit -->
                                    <div class="depositFields" style="display: none;">
                                        <div class="form-group">
                                            <label>Transaction Type</label>
                                            <select class="form-control border-left" name="dtransaction_type" id="dtransaction_type">
                                                <option value="Credit">Credit</option>
                                                <option value="Debit">Debit</option>
                                            </select>
                                        </div>
                                        <div class="form-group">
                                            <label>Amount</label>
                                            <input type="number" step="0.01" min="0" class="form-control border-left" name="damount" id="damount" value="">
                                        </div>
                                        <div class="form-group">
                                            <label>New Balance</label>
                                            <input type="text" class="form-control border-left bg-light" id="dnewBalance" readonly value="">
                                        </div>
                                        <div class="form-group">
                                            <label>Transaction Details</label>
                                            <input type="text" class="form-control border-left" name="dreason" value="">
                                        </div>
                                        <div class="form-group">
                                            <label>Status</label>
                                            <select class="form-control border-left" name="dstatus">
                                                <option value="Success">Successful</option>
                                                <option value="Pending">Pending</option>
                                                <option value="Failed">Failed</option>
                                            </select>
                                        </div>
                                        <div class="form-group">
                                            <label>Date</label>
                                            <input type="text" placeholder="2026-04-30 13:36:35" class="form-control border-left" name="ddate" value="<?php echo date('Y-m-d H:i:s'); ?>">
                                        </div>
                                    </div>

                                    <!-- Fields for Loan -->
                                    <div class="loanFields" style="display: none;">
                                        <div class="form-group">
                                            <label>Transaction Type</label>
                                            <select class="form-control border-left" name="ltransaction_type" id="ltransaction_type">
                                                <option value="Credit">Credit</option>
                                                <option value="Debit">Debit</option>
                                            </select>
                                        </div>
                                        <div class="form-group">
                                            <label>Amount</label>
                                            <input type="number" step="0.01" min="0" class="form-control border-left" name="lamount" id="lamount" value="">
                                        </div>
                                        <div class="form-group">
                                            <label>New Balance</label>
                                            <input type="text" class="form-control border-left bg-light" id="lnewBalance" readonly value="">
                                        </div>
                                        <div class="form-group">
                                            <label>Transaction Details</label>
                                            <input type="text" class="form-control border-left" name="lreason" value="">
                                        </div>
                                        <div class="form-group">
                                            <label>Status</label>
                                            <select class="form-control border-left" name="lstatus">
                                                <option value="Success">Successful</option>
                                                <option value="Pending">Pending</option>
                                                <option value="Failed">Failed</option>
                                            </select>
                                        </div>
                                        <div class="form-group">
                                            <label>Date</label>
                                            <input type="text" placeholder="2026-04-30 13:36:35" class="form-control border-left" name="ldate" value="<?php echo date('Y-m-d H:i:s'); ?>">
                                            
                                        </div>
                                    </div>

                                    <!-- Fields for Transfer -->
                                    <div class="transferFields" style="display: none;">
                                        <div class="form-group">
                                            <label>Amount</label>
                                            <input type="number" step="0.01" min="0" class="form-control border-left" name="tamount" id="tamount" value="">
                                        </div>
                                        <div class="form-group">
                                            <label>Transfer Type</label>
                                            <select class="form-control border-left" name="ttransfer_type" id="ttransfer_type">
                                                <option value="Debit">Debit</option>
                                                <option value="Credit">Credit</option>
                                            </select>
                                        </div>
                                        <div class="form-group">
                                            <label>Previous Balance</label>
                                            <input type="text" class="form-control border-left bg-light" name="tpre_balance" id="tpre_balance" readonly value="">
                                        </div>
                                        <div class="form-group">
                                            <label>New Balance</label>
                                            <input type="text" class="form-control border-left bg-light" name="tnew_balance" id="tnew_balance" readonly value="">
                                        </div>
                                        <div class="form-group">
                                            <label id="tlabel_fullname">Receiver Full Name</label>
                                            <input type="text" class="form-control border-left" name="treceiver_fullname" value="">
                                        </div>
                                        <div class="form-group">
                                            <label>Account Type</label>
                                            <input type="text" class="form-control border-left" name="acc_type" value="">
                                        </div>
                                        <div class="form-group">
                                            <label id="tlabel_bankname">Receiver Bank Name</label>
                                            <input type="text" class="form-control border-left" name="treceiver_bank_name" value="">
                                        </div>
                                        <div class="form-group">
                                            <label id="tlabel_bankaddress">Receiver Bank Address</label>
                                            <input type="text" class="form-control border-left" name="treceiver_bank_address" value="">
                                        </div>
                                        <div class="form-group">
                                            <label id="tlabel_bankcountry">Receiver Bank Country</label>
                                            <input type="text" class="form-control border-left" name="treceiver_bank_country" value="">
                                        </div>
                                        <div class="form-group">
                                            <label>IBAN</label>
                                            <input type="text" class="form-control border-left" name="tiban" value="">
                                        </div>
                                        <div class="form-group">
                                            <label id="tlabel_details">Transaction Details</label>
                                            <input type="text" class="form-control border-left" name="treason" value="">
                                        </div>
                                        <div class="form-group">
                                            <label id="tlabel_senderacc">Sender Account Number</label>
                                            <input type="text" class="form-control border-left" name="tsender_acc_no" value="">
                                        </div>
                                        <div class="form-group">
                                            <label>Stat</label>
                                            <select class="form-control border-left" name="tstat">
                                                <option value="International Transfer">International Transfer</option>
                                                <option value="Local Transfer">Local Transfer</option>
                                            </select>
                                        </div>
                                        <div class="form-group">
                                            <label>Status</label>
                                            <select class="form-control border-left" id="tstatus" name="tstatus">
                                                <option value="Success">Successful</option>
                                                <option value="Pending">Pending</option>
                                                <option value="Failed">Failed</option>
                                            </select>
                                        </div>
                                        <div class="form-group">
                                            <label>Date</label>
                                            <input type="text" placeholder="2026-04-30 13:36:35" class="form-control border-left" id="tdate" name="tdate" value="<?php echo date('Y-m-d H:i:s'); ?>">
                                        </div>
                                    </div>

                                    <!-- Fields for Withdrawal -->
                                    <div class="withdrawalFields" style="display: none;">
                                        <div class="form-group">
                                            <label>Transaction Type</label>
                                            <select class="form-control border-left" name="wtransaction_type" id="wtransaction_type">
                                                <option value="Debit">Debit</option>
                                                <option value="Credit">Credit</option>
                                            </select>
                                        </div>
                                        <div class="form-group">
                                            <label>Amount</label>
                                            <input type="number" step="0.01" min="0" class="form-control border-left" name="wamount" id="wamount" value="">
                                        </div>
                                        <div class="form-group">
                                            <label>New Balance</label>
                                            <input type="text" class="form-control border-left bg-light" id="wnewBalance" readonly value="">
                                        </div>
                                        <div class="form-group">
                                            <label>Transaction Details</label>
                                            <input type="text" class="form-control border-left" name="wreason" value="">
                                        </div>
                                        <div class="form-group">
                                            <label>Status</label>
                                            <select class="form-control border-left" name="wstatus">
                                                <option value="Success">Successful</option>
                                                <option value="Pending">Pending</option>
                                                <option value="Failed">Failed</option>
                                            </select>
                                        </div>
                                        <div class="form-group">
                                            <label>Date</label>
                                            <input type="text" placeholder="2026-04-30 13:36:35" class="form-control border-left" id="wdate" name="wdate" value="<?php echo date('Y-m-d H:i:s'); ?>">
                                        </div>
                                    </div>
                                </div>
                                <!-- End Additional Fields -->

                                <div class="form-group">
                                    <button type="submit" class="btn btn-primary px-4" name="update" onclick="return confirm('Are you sure you want to proceed?')">Submit</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>

            <!--end row-->
        </div>
    </div>
    <!--end page-content-wrapper-->
</div>
<!--end page-wrapper-->
<!--start overlay-->
<div class="overlay toggle-btn-mobile"></div>
<!--end overlay-->
<!--Start Back To Top Button-->
<a href="javaScript:;" class="back-to-top"><i class='bx bxs-up-arrow-alt'></i></a>
<!--End Back To Top Button-->

<script>
    const balanceMap = <?php echo json_encode($balanceMap); ?>;
    let currentBalance = 0;

    function fmt(n) {
        return '$' + parseFloat(n).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    }

    function calcNew(bal, amt, txnType) {
        return txnType === 'Credit' ? bal + amt : bal - amt;
    }

    function recalc() {
        const type = document.getElementById('transactionType').value;
        if (type === 'deposit') {
            const amt   = parseFloat(document.getElementById('damount').value) || 0;
            const ttype = document.getElementById('dtransaction_type').value;
            document.getElementById('dnewBalance').value = fmt(calcNew(currentBalance, amt, ttype));
        } else if (type === 'loan') {
            const amt   = parseFloat(document.getElementById('lamount').value) || 0;
            const ttype = document.getElementById('ltransaction_type').value;
            document.getElementById('lnewBalance').value = fmt(calcNew(currentBalance, amt, ttype));
        } else if (type === 'withdrawal') {
            const amt   = parseFloat(document.getElementById('wamount').value) || 0;
            const ttype = document.getElementById('wtransaction_type').value;
            document.getElementById('wnewBalance').value = fmt(calcNew(currentBalance, amt, ttype));
        } else if (type === 'transfer') {
            const amt   = parseFloat(document.getElementById('tamount').value) || 0;
            const ttype = document.getElementById('ttransfer_type').value;
            document.getElementById('tnew_balance').value = calcNew(currentBalance, amt, ttype).toFixed(2);
        }
    }

    document.getElementById('emailSelect').addEventListener('change', function () {
        const email = this.value;
        currentBalance = balanceMap[email] || 0;
        const display = document.getElementById('currentBalanceDisplay');
        display.value = fmt(currentBalance);
        document.getElementById('currentBalanceGroup').style.display = 'block';
        // Pre-fill transfer previous balance field
        const tpre = document.getElementById('tpre_balance');
        if (tpre) tpre.value = currentBalance.toFixed(2);
        recalc();
    });

    document.getElementById('transactionType').addEventListener('change', function () {
        const type = this.value;
        document.querySelectorAll('#additionalFields > div').forEach(d => d.style.display = 'none');
        document.querySelectorAll('.' + type + 'Fields').forEach(d => d.style.display = 'block');
        recalc();
    });

    ['damount', 'lamount', 'wamount', 'tamount'].forEach(function (id) {
        const el = document.getElementById(id);
        if (el) el.addEventListener('input', recalc);
    });

    ['dtransaction_type', 'ltransaction_type', 'wtransaction_type', 'ttransfer_type'].forEach(function (id) {
        const el = document.getElementById(id);
        if (el) el.addEventListener('change', recalc);
    });

    function updateTransferLabels(type) {
        var isDebit = type === 'Debit';
        document.getElementById('tlabel_fullname').textContent    = isDebit ? 'Receiver Full Name'    : 'Sender Full Name';
        document.getElementById('tlabel_bankname').textContent    = isDebit ? 'Receiver Bank Name'    : 'Sender Bank Name';
        document.getElementById('tlabel_bankaddress').textContent = isDebit ? 'Receiver Bank Address' : 'Sender Bank Address';
        document.getElementById('tlabel_bankcountry').textContent = isDebit ? 'Receiver Bank Country' : 'Sender Bank Country';
        document.getElementById('tlabel_details').textContent     = isDebit ? 'Transfer Details'       : 'Source / Reference';
        document.getElementById('tlabel_senderacc').textContent   = isDebit ? 'Sender Account Number' : 'Source Account Number';
    }

    document.getElementById('ttransfer_type').addEventListener('change', function () {
        updateTransferLabels(this.value);
    });
</script>


<?php
include 'footer.php';

// Process form submission
if (isset($_POST['update'])) {
    $transaction_type = sanitize($_POST['transaction_type']);
    $email = sanitize($_POST['email']);
   

    // Fetch user details based on the selected email
    $result = $conn->query("SELECT acc_no, fullname, acc_type, balance FROM users WHERE email = '$email'");
    if ($result && $result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $acc_no        = $row['acc_no'];
        $fullname      = $row['fullname'];
        $acc_type_user = $row['acc_type'];
        $curr_balance  = (float)$row['balance'];

        // Update balance based on transaction type
        switch ($transaction_type) {
            case 'deposit':
                $amount      = sanitize($_POST['damount']);
                $d_txn_type  = sanitize($_POST['dtransaction_type']);
                $reason      = sanitize($_POST['dreason']);
                $status      = sanitize($_POST['dstatus']);
                $date        = sanitize($_POST['ddate']);
                $new_bal_dep = $d_txn_type === 'Credit' ? $curr_balance + (float)$amount : $curr_balance - (float)$amount;
                $conn->query("INSERT INTO transactions (name, account_number, account_type, acc_type, amount, prev_bal, new_bal, new_balance, transaction_type, transaction_details, status, stat, date_added) VALUES ('$fullname', '$acc_no', '$acc_type_user', '$acc_type_user', '$amount', '$curr_balance', '$new_bal_dep', '$new_bal_dep', '$d_txn_type', '$reason', '$status', 'Deposit', '$date')");
                break;
            case 'loan':
                $amount       = sanitize($_POST['lamount']);
                $l_txn_type   = sanitize($_POST['ltransaction_type']);
                $reason       = sanitize($_POST['lreason']);
                $status       = sanitize($_POST['lstatus']);
                $date         = sanitize($_POST['ldate']);
                $new_bal_loan = $l_txn_type === 'Credit' ? $curr_balance + (float)$amount : $curr_balance - (float)$amount;
                $conn->query("INSERT INTO transactions (name, account_number, account_type, acc_type, amount, prev_bal, new_bal, new_balance, transaction_type, transaction_details, status, stat, date_added) VALUES ('$fullname', '$acc_no', '$acc_type_user', '$acc_type_user', '$amount', '$curr_balance', '$new_bal_loan', '$new_bal_loan', '$l_txn_type', '$reason', '$status', 'Loan', '$date')");
                break;
            case 'withdrawal':
                $amount        = sanitize($_POST['wamount']);
                $w_txn_type    = sanitize($_POST['wtransaction_type']);
                $reason        = sanitize($_POST['wreason']);
                $status        = sanitize($_POST['wstatus']);
                $date          = sanitize($_POST['wdate']);
                $new_bal_wdraw = $w_txn_type === 'Credit' ? $curr_balance + (float)$amount : $curr_balance - (float)$amount;
                $conn->query("INSERT INTO transactions (name, account_number, account_type, acc_type, amount, prev_bal, new_bal, new_balance, transaction_type, transaction_details, status, stat, date_added) VALUES ('$fullname', '$acc_no', '$acc_type_user', '$acc_type_user', '$amount', '$curr_balance', '$new_bal_wdraw', '$new_bal_wdraw', '$w_txn_type', '$reason', '$status', 'Withdrawal', '$date')");
                break;
            case 'transfer':
                $amount                = sanitize($_POST['tamount']);
                $receiver_fullname     = sanitize($_POST['treceiver_fullname']);
                $acc_type              = sanitize($_POST['acc_type']);
                $new_balance           = sanitize($_POST['tnew_balance']);
                $pre_balance           = sanitize($_POST['tpre_balance']);
                $receiver_bank_name    = sanitize($_POST['treceiver_bank_name']);
                $receiver_bank_address = sanitize($_POST['treceiver_bank_address']);
                $receiver_bank_country = sanitize($_POST['treceiver_bank_country']);
                $iban                  = sanitize($_POST['tiban']);
                $reason                = sanitize($_POST['treason']);
                $transfer_type         = sanitize($_POST['ttransfer_type']);
                $sender_acc_no         = sanitize($_POST['tsender_acc_no']);
                $stat                  = sanitize($_POST['tstat']);
                $status                = sanitize($_POST['tstatus']);
                $date_added            = sanitize($_POST['tdate']);
                $conn->query("INSERT INTO transactions (name, account_number, account_type, acc_type, amount, prev_bal, new_bal, new_balance, transaction_type, transaction_details, status, stat, receiver_fullname, other_bank_name, other_bank_address, other_bank_country, iban, date_added) VALUES ('$fullname', '$acc_no', '$acc_type', '$acc_type', '$amount', '$pre_balance', '$new_balance', '$new_balance', '$transfer_type', '$reason', '$status', '$stat', '$receiver_fullname', '$receiver_bank_name', '$receiver_bank_address', '$receiver_bank_country', '$iban', '$date_added')");
                break;
            default:
                echo "<script>alert('Invalid transaction type');</script>";
                break;
        }

        // If the query was successful, display success message
        if ($conn->affected_rows > 0) {
            echo "<script>alert('Transaction recorded successfully');</script>";
        } else {
            echo "<script>alert('Failed to record transaction');</script>";
        }
    } else {
        echo "<script>alert('Failed to fetch account number');</script>";
    }
}

// Function to sanitize input
function sanitize($input)
{
    return htmlspecialchars(strip_tags(trim($input)));
}
?>
