<?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">Beneficiaries</div>
        <div class="right">
            <a href="#" class="headerButton" data-bs-toggle="modal" data-bs-target="#addBeneficiaryModal">
                <ion-icon name="add-outline"></ion-icon>
            </a>
        </div>
    </div>

    <!-- App Capsule -->
    <div id="appCapsule">
        
        <?php if (empty($beneficiaries)): ?>
        <!-- Empty State -->
        <div class="section mt-5 text-center">
            <ion-icon name="people-outline" style="font-size: 64px; color: #ccc;"></ion-icon>
            <h3 class="mt-2">No Beneficiaries</h3>
            <p class="text-muted">You haven't added any beneficiaries yet</p>
            <a href="#" class="btn btn-primary mt-2" data-bs-toggle="modal" data-bs-target="#addBeneficiaryModal">
                <ion-icon name="add-outline"></ion-icon> Add Beneficiary
            </a>
        </div>
        <?php else: ?>

        <!-- Search -->
        <div class="section mt-2">
            <div class="card">
                <div class="card-body p-2">
                    <div class="form-group basic">
                        <div class="input-wrapper">
                            <input type="text" class="form-control" id="searchBeneficiary" placeholder="Search beneficiaries...">
                            <i class="clear-input">
                                <ion-icon name="close-circle"></ion-icon>
                            </i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Beneficiaries List -->
        <div class="section mt-2 mb-3">
            <div class="section-title">All Beneficiaries</div>
            <div class="card">
                <ul class="listview image-listview flush" id="beneficiaryList">
                    <?php foreach ($beneficiaries as $ben): ?>
                    <li data-name="<?php echo strtolower($ben->name); ?>" onclick="selectBeneficiary('<?php echo $ben->account_number; ?>', '<?php echo $ben->beneficiary_type; ?>')" style="cursor: pointer;">
                        <div class="item">
                            <div class="icon-box bg-<?php echo $ben->beneficiary_type == 'internal' ? 'primary' : 'secondary'; ?>">
                                <ion-icon name="person-outline"></ion-icon>
                            </div>
                            <div class="in">
                                <div>
                                    <strong><?php echo htmlspecialchars($ben->name); ?></strong>
                                    <p><?php echo $ben->account_number; ?><?php if ($ben->bank_name): ?> - <?php echo $ben->bank_name; ?><?php endif; ?></p>
                                </div>
                                <div>
                                    <span class="badge badge-<?php echo $ben->beneficiary_type == 'internal' ? 'success' : 'secondary'; ?>">
                                        <?php echo ucfirst($ben->beneficiary_type); ?>
                                    </span>
                                    <a href="#" class="text-danger ms-2" onclick="event.stopPropagation(); deleteBeneficiary(<?php echo $ben->id; ?>)">
                                        <ion-icon name="trash-outline"></ion-icon>
                                    </a>
                                </div>
                            </div>
                        </div>
                    </li>
                    <?php endforeach; ?>
                </ul>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <!-- Add Beneficiary Modal -->
    <div class="modal fade action-sheet" id="addBeneficiaryModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Add Beneficiary</h5>
                </div>
                <div class="modal-body">
                    <div class="action-sheet-content">
                        <form id="addBeneficiaryForm">
                            <input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>">
                            
                            <div class="form-group basic">
                                <div class="input-wrapper">
                                    <label class="label">Beneficiary Type</label>
                                    <select class="form-control" name="beneficiary_type" id="beneficiaryType" required>
                                        <option value="internal"><?php echo get_app_name(); ?> Account</option>
                                        <option value="external">Other Bank</option>
                                        <option value="international">International</option>
                                    </select>
                                </div>
                            </div>
                            
                            <div class="form-group basic">
                                <div class="input-wrapper">
                                    <label class="label">Beneficiary Name</label>
                                    <input type="text" class="form-control" name="name" placeholder="Enter name" required>
                                </div>
                            </div>
                            
                            <div class="form-group basic">
                                <div class="input-wrapper">
                                    <label class="label">Account Number</label>
                                    <input type="text" class="form-control" name="account_number" id="beneficiaryAccount" placeholder="Enter account number" required>
                                </div>
                                <div id="accountLookupResult" class="input-info text-success"></div>
                            </div>
                            
                            <div id="externalBankFields" style="display: none;">
                                <div class="form-group basic">
                                    <div class="input-wrapper">
                                        <label class="label">Bank Name</label>
                                        <select class="form-control" name="bank_code" id="bankSelect">
                                            <option value="">Select Bank</option>
                                            <option value="CHAS" data-name="Chase">Chase</option>
                                            <option value="BOFA" data-name="Bank of America">Bank of America</option>
                                            <option value="WELS" data-name="Wells Fargo">Wells Fargo</option>
                                            <option value="CITI" data-name="Citibank">Citibank</option>
                                            <option value="USBG" data-name="US Bank">US Bank</option>
                                            <option value="PNC" data-name="PNC Bank">PNC Bank</option>
                                            <option value="TRUI" data-name="Truist">Truist</option>
                                            <option value="CAP1" data-name="Capital One">Capital One</option>
                                            <option value="TDBK" data-name="TD Bank">TD Bank</option>
                                            <option value="ALLY" data-name="Ally Bank">Ally Bank</option>
                                            <option value="SCHW" data-name="Charles Schwab Bank">Charles Schwab Bank</option>
                                            <option value="DISC" data-name="Discover Bank">Discover Bank</option>
                                            <option value="GOLD" data-name="Goldman Sachs">Goldman Sachs</option>
                                            <option value="MSBK" data-name="Morgan Stanley">Morgan Stanley</option>
                                            <option value="HSBC" data-name="HSBC Bank USA">HSBC Bank USA</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <div id="internationalBankFields" style="display: none;">
                                <div class="form-group basic">
                                    <div class="input-wrapper">
                                        <label class="label">SWIFT / BIC Code</label>
                                        <input type="text" class="form-control" name="swift_code" id="intlSwift" placeholder="e.g. CHASUS33">
                                    </div>
                                </div>
                                <div class="form-group basic">
                                    <div class="input-wrapper">
                                        <label class="label">Country</label>
                                        <input type="text" class="form-control" name="country_name" id="intlCountry" placeholder="e.g. United States">
                                    </div>
                                </div>
                                <div class="form-group basic">
                                    <div class="input-wrapper">
                                        <label class="label">Currency</label>
                                        <select class="form-control" name="currency" id="intlCurrency">
                                            <option value="USD">USD</option>
                                            <option value="EUR">EUR</option>
                                            <option value="GBP">GBP</option>
                                            <option value="NGN">NGN</option>
                                            <option value="CAD">CAD</option>
                                            <option value="AUD">AUD</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <input type="hidden" name="bank_name" id="bankName">
                            
                            <div class="form-group basic mt-3">
                                <button type="submit" class="btn btn-primary btn-block btn-lg">Add Beneficiary</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

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

    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Toggle external/international bank fields
        document.getElementById('beneficiaryType').addEventListener('change', function() {
            var externalFields = document.getElementById('externalBankFields');
            var internationalFields = document.getElementById('internationalBankFields');
            var bankNameHidden = document.getElementById('bankName');
            if (this.value === 'external') {
                externalFields.style.display = 'block';
                if (internationalFields) internationalFields.style.display = 'none';
                if (bankNameHidden) bankNameHidden.type = 'hidden';
            } else if (this.value === 'international') {
                if (externalFields) externalFields.style.display = 'none';
                if (internationalFields) internationalFields.style.display = 'block';
                if (bankNameHidden) bankNameHidden.type = 'hidden';
            } else {
                if (externalFields) externalFields.style.display = 'none';
                if (internationalFields) internationalFields.style.display = 'none';
                if (bankNameHidden) bankNameHidden.type = 'hidden';
            }
        });
        
        // Bank select - update bank name
        document.getElementById('bankSelect').addEventListener('change', function() {
            var selected = this.options[this.selectedIndex];
            document.getElementById('bankName').value = selected.dataset.name || '';
        });
        
        // Account lookup for internal
        var lookupTimeout;
        document.getElementById('beneficiaryAccount').addEventListener('input', function() {
            var accountNumber = this.value;
            var type = document.getElementById('beneficiaryType').value;
            
            if (type === 'internal' && accountNumber.length >= 10) {
                clearTimeout(lookupTimeout);
                lookupTimeout = setTimeout(function() {
                    lookupAccount(accountNumber);
                }, 500);
            }
        });
        
        // Search beneficiaries
        document.getElementById('searchBeneficiary')?.addEventListener('input', function() {
            var query = this.value.toLowerCase();
            var items = document.querySelectorAll('#beneficiaryList li');
            items.forEach(function(item) {
                var name = item.dataset.name;
                if (name.includes(query)) {
                    item.style.display = '';
                } else {
                    item.style.display = 'none';
                }
            });
        });
        
        // Form submit
        document.getElementById('addBeneficiaryForm').addEventListener('submit', function(e) {
            e.preventDefault();
            addBeneficiary(this);
        });
    });
    
    function lookupAccount(accountNumber) {
        fetch(base_url + 'api/transfer/lookup', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'account_number=' + accountNumber + '&csrf_token=' + csrf_token
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                document.getElementById('accountLookupResult').innerHTML = 
                    '<ion-icon name="checkmark-circle"></ion-icon> ' + data.data.account_holder;
            } else {
                document.getElementById('accountLookupResult').innerHTML = '';
            }
        });
    }
    
    function addBeneficiary(form) {
        var formData = new FormData(form);
        
        fetch(base_url + 'transfers/add_beneficiary', {
            method: 'POST',
            body: new URLSearchParams(formData)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                MeridianDialog.success(data.message);
                setTimeout(function() {
                    location.reload();
                }, 1500);
            } else {
                MeridianDialog.error(data.message);
            }
        });
    }
    
    function deleteBeneficiary(id) {
        MeridianDialog.confirm('Are you sure you want to delete this beneficiary?', function() {
            fetch(base_url + 'transfers/delete_beneficiary/' + id, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'csrf_token=' + csrf_token
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    MeridianDialog.success(data.message);
                    setTimeout(function() {
                        location.reload();
                    }, 1500);
                } else {
                    MeridianDialog.error(data.message);
                }
            });
        });
    }
    
    function selectBeneficiary(accountNumber, type) {
        if (type === 'internal') {
            window.location.href = base_url + 'transfers/internal?to=' + encodeURIComponent(accountNumber);
        } else if (type === 'external') {
            window.location.href = base_url + 'transfers/external?to=' + encodeURIComponent(accountNumber);
        } else if (type === 'international') {
            window.location.href = base_url + 'transfers/international?to=' + encodeURIComponent(accountNumber);
        }
    }
    </script>

<?php $this->load->view('layouts/footer'); ?>
