<?php 
$this->load->view('layouts/header');
$this->load->helper('layout');
$banks = [
    ['code' => 'CHAS', 'name' => 'Chase'],
    ['code' => 'BOFA', 'name' => 'Bank of America'],
    ['code' => 'WELS', 'name' => 'Wells Fargo'],
    ['code' => 'CITI', 'name' => 'Citibank'],
    ['code' => 'USBG', 'name' => 'US Bank'],
    ['code' => 'PNC', 'name' => 'PNC Bank'],
    ['code' => 'TRUI', 'name' => 'Truist'],
    ['code' => 'CAP1', 'name' => 'Capital One'],
    ['code' => 'TDBK', 'name' => 'TD Bank'],
    ['code' => 'ALLY', 'name' => 'Ally Bank'],
    ['code' => 'SCHW', 'name' => 'Charles Schwab Bank'],
    ['code' => 'DISC', 'name' => 'Discover Bank'],
    ['code' => 'GOLD', 'name' => 'Goldman Sachs'],
    ['code' => 'MSBK', 'name' => 'Morgan Stanley'],
    ['code' => 'HSBC', 'name' => 'HSBC Bank USA'],
];
?>

    <!-- App Header -->
    <div class="appHeader">
        <div class="left">
            <a href="<?php echo base_url('transfers'); ?>" class="headerButton">
                <ion-icon name="chevron-back-outline"></ion-icon>
            </a>
        </div>
        <div class="pageTitle">Bank Transfer</div>
        <div class="right"></div>
    </div>

    <!-- App Capsule -->
    <div id="appCapsule">
        
        <?php if ($this->session->flashdata('error')): ?>
        <div class="section mt-2">
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <?php echo $this->session->flashdata('error'); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        </div>
        <?php endif; ?>

        <div class="section mt-2">
            <div class="section-title">Transfer to Other Bank</div>
            <p class="text-muted small">After verification, your transfer will be submitted with <strong>pending</strong> status for processing.</p>
            <form action="<?php echo base_url('transfers/external'); ?>" method="POST" id="transferForm">
                <input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>">
                
                <div class="card">
                    <div class="card-body">
                        <div class="form-group basic">
                            <div class="input-wrapper">
                                <label class="label">From Account</label>
                                <select class="form-control custom-select" name="source_account" id="sourceAccount" required>
                                    <option value="">Select Account</option>
                                    <?php foreach ($accounts as $account): ?>
                                    <option value="<?php echo $account->id; ?>">
                                        <?php echo $account->account_number; ?> - <?php echo format_money($account->available_balance ?? 0, $account->currency); ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>

                        <div class="form-group basic">
                            <div class="input-wrapper">
                                <label class="label">Select Beneficiary (optional)</label>
                                <select class="form-control" id="beneficiarySelect">
                                    <option value="">Enter manually below</option>
                                    <?php foreach ($beneficiaries as $b): ?>
                                    <option value="<?php echo htmlspecialchars($b->account_number); ?>" 
                                            data-name="<?php echo htmlspecialchars($b->name); ?>" 
                                            data-bank="<?php echo htmlspecialchars($b->bank_code ?? ''); ?>" 
                                            data-bankname="<?php echo htmlspecialchars($b->bank_name ?? ''); ?>">
                                        <?php echo htmlspecialchars($b->name); ?> - <?php echo $b->account_number; ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>

                        <div class="form-group basic">
                            <div class="input-wrapper">
                                <label class="label">Recipient Name</label>
                                <input type="text" class="form-control" name="recipient_name" id="recipientName" placeholder="Full name" required value="<?php echo isset($to_name) ? htmlspecialchars($to_name) : ''; ?>">
                            </div>
                        </div>

                        <div class="form-group basic">
                            <div class="input-wrapper">
                                <label class="label">Recipient Account Number</label>
                                <input type="text" class="form-control" name="recipient_account" id="recipientAccount" placeholder="Account number" required value="<?php echo isset($to_account) ? htmlspecialchars($to_account) : ''; ?>">
                            </div>
                        </div>

                        <div class="form-group basic">
                            <div class="input-wrapper">
                                <label class="label">Bank</label>
                                <select class="form-control" name="bank_code" id="bankCode" required>
                                    <option value="">Select Bank</option>
                                    <?php foreach ($banks as $bank): ?>
                                    <option value="<?php echo $bank['code']; ?>" data-name="<?php echo htmlspecialchars($bank['name']); ?>" <?php echo (isset($to_bank_code) && $to_bank_code === $bank['code']) ? 'selected' : ''; ?>><?php echo $bank['name']; ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <input type="hidden" name="bank_name" id="bankName" value="<?php echo isset($to_name) ? '' : ''; ?>">
                            </div>
                        </div>

                        <div class="form-group basic">
                            <label class="label">Amount</label>
                            <div class="input-group mb-2">
                                <span class="input-group-text">$</span>
                                <input type="number" class="form-control" name="amount" id="amount" placeholder="0.00" required min="1" step="0.01">
                            </div>
                        </div>

                        <div class="form-group basic">
                            <div class="input-wrapper">
                                <label class="label">Narration (Optional)</label>
                                <input type="text" class="form-control" name="narration" placeholder="What's this for?">
                            </div>
                        </div>
                    </div>
                </div>

                <div class="form-button-group transparent" style="bottom: 56px;">
                    <?php if ($user->user_type !== 'admin'): ?>
                    <button type="button" class="btn btn-primary btn-block btn-lg" id="submitBtn" onclick="initiateTransfer()">
                        Continue
                    </button>
                    <?php else: ?>
                    <button type="submit" class="btn btn-primary btn-block btn-lg" id="submitBtn">
                        Submit Transfer
                    </button>
                    <?php endif; ?>
                </div>
            </form>
        </div>
    </div>

    <?php if ($user->user_type !== 'admin'): ?>
    <?php $this->load->view('partials/otp_modal'); ?>
    <?php endif; ?>

    <?php echo get_bottom_menu('transfers'); ?>

<?php 
$extra_js = '
<script>
document.addEventListener("DOMContentLoaded", function() {
    document.getElementById("bankCode").addEventListener("change", function() {
        var opt = this.options[this.selectedIndex];
        document.getElementById("bankName").value = opt.dataset.name || "";
    });
    if (document.getElementById("bankCode").value) {
        document.getElementById("bankCode").dispatchEvent(new Event("change"));
    }
    document.getElementById("beneficiarySelect").addEventListener("change", function() {
        var opt = this.options[this.selectedIndex];
        if (opt.value) {
            document.getElementById("recipientName").value = opt.dataset.name || "";
            document.getElementById("recipientAccount").value = opt.value;
            document.getElementById("bankCode").value = opt.dataset.bank || "";
            document.getElementById("bankName").value = opt.dataset.bankname || "";
            var bankOpt = document.querySelector("#bankCode option[value=\"" + (opt.dataset.bank || "") + "\"]");
            if (bankOpt) bankOpt.selected = true;
        }
    });
    if (typeof initOtpVerification === "function") {
        initOtpVerification("transferForm", "bank_transfer", function() {
            document.getElementById("transferForm").submit();
        });
    }
});
function initiateTransfer() {
    var sourceAccount = document.getElementById("sourceAccount").value;
    var recipientName = document.getElementById("recipientName").value.trim();
    var recipientAccount = document.getElementById("recipientAccount").value.trim();
    var bankCode = document.getElementById("bankCode").value;
    var amount = document.getElementById("amount").value;
    if (!sourceAccount) { alert("Please select source account"); return; }
    if (!recipientName) { alert("Please enter recipient name"); return; }
    if (!recipientAccount) { alert("Please enter recipient account number"); return; }
    if (!bankCode) { alert("Please select bank"); return; }
    if (!amount || parseFloat(amount) <= 0) { alert("Please enter a valid amount"); return; }
    document.getElementById("bankCode").dispatchEvent(new Event("change"));
    requestOtpVerification();
}
</script>
';
$this->load->view('layouts/footer', ['extra_js' => $extra_js]); 
?>
