<?php 
$this->load->view('layouts/header');
$this->load->helper('layout');
?>

    <!-- App Header -->
    <div class="appHeader">
        <div class="left">
            <a href="<?php echo base_url('dashboard'); ?>" class="headerButton">
                <ion-icon name="chevron-back-outline"></ion-icon>
            </a>
        </div>
        <div class="pageTitle">Transfer Money</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">Send Money to <?php echo get_app_name(); ?> Account</div>
            <form action="<?php echo base_url('transfers/internal'); ?>" 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">
                        <!-- Source Account -->
                        <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; ?>" data-balance="<?php echo $account->available_balance ?? 0; ?>">
                                        <?php echo $account->account_number; ?> - <?php echo format_money($account->available_balance ?? 0, $account->currency); ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>

                        <!-- Destination Account -->
                        <div class="form-group basic">
                            <div class="input-wrapper">
                                <label class="label">To Account Number</label>
                                <input type="text" class="form-control" name="destination_account" id="destAccount" placeholder="Enter 10-digit account number" required maxlength="10" value="<?php echo isset($to_account) ? htmlspecialchars($to_account) : ''; ?>">
                                <i class="clear-input">
                                    <ion-icon name="close-circle"></ion-icon>
                                </i>
                            </div>
                            <div id="accountName" class="text-success mt-1" style="display: none;"></div>
                        </div>

                        <!-- Amount -->
                        <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="100" step="0.01">
                            </div>
                        </div>

                        <!-- Narration -->
                        <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()">
                        Send Money
                    </button>
                    <?php else: ?>
                    <button type="submit" class="btn btn-primary btn-block btn-lg" id="submitBtn">
                        Send Money
                    </button>
                    <?php endif; ?>
                </div>
            </form>
        </div>
    </div>

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

    <!-- App Bottom Menu -->
    <?php echo get_bottom_menu('transfers'); ?>

<?php 
$extra_js = '
<script>
function lookupAccount(accountNumber) {
    if (accountNumber.length >= 10) {
        fetch("' . base_url('transfers/lookup_account') . '", {
            method: "POST",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
            },
            body: "account_number=" + accountNumber + "&' . $this->security->get_csrf_token_name() . '=' . $this->security->get_csrf_hash() . '"
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                document.getElementById("accountName").textContent = data.data.account_holder;
                document.getElementById("accountName").className = "text-success mt-1";
                document.getElementById("accountName").style.display = "block";
            } else {
                document.getElementById("accountName").textContent = data.message;
                document.getElementById("accountName").className = "text-danger mt-1";
                document.getElementById("accountName").style.display = "block";
            }
        });
    }
}

document.getElementById("destAccount").addEventListener("blur", function() {
    lookupAccount(this.value);
});

// Auto-lookup if field is pre-filled
document.addEventListener("DOMContentLoaded", function() {
    var destAccount = document.getElementById("destAccount");
    if (destAccount.value.length >= 10) {
        lookupAccount(destAccount.value);
    }
    
    // Initialize OTP verification for transfer form
    if (typeof initOtpVerification === "function") {
        initOtpVerification("transferForm", "transfer", function() {
            document.getElementById("transferForm").submit();
        });
    }
});

// Validate form and initiate OTP verification
function initiateTransfer() {
    var form = document.getElementById("transferForm");
    
    // Basic validation
    var sourceAccount = document.getElementById("sourceAccount").value;
    var destAccount = document.getElementById("destAccount").value;
    var amount = document.getElementById("amount").value;
    
    if (!sourceAccount) {
        showToast("Please select source account", "error");
        return;
    }
    if (!destAccount || destAccount.length < 10) {
        showToast("Please enter valid destination account", "error");
        return;
    }
    if (!amount || parseFloat(amount) <= 0) {
        showToast("Please enter a valid amount", "error");
        return;
    }
    
    // Show OTP verification modal
    requestOtpVerification();
}

function showToast(message, type) {
    if (typeof toastbox === "function") {
        toastbox("toast-" + type, 3000);
    } else {
        alert(message);
    }
}
</script>
';
$this->load->view('layouts/footer', ['extra_js' => $extra_js]); 
?>
