{include file="sections/header.tpl"}
            <div class="container-fluid">
                <div class="row">
                    <div class="col-sm-12 col-md-12">
                        <div class="card card-primary card-hovered card-stacked mb30">
                            <div class="card-header">
                                <h3 class="card-title">{Lang::T('Recharge Account')}</h3></div>
                            <div class="card-body">
                                <form class="form-horizontal" method="post" role="form" action="{$_url}plan/recharge-confirm">
                                    <div class="form-group row">
                                        <label class="col-md-2 control-label">{Lang::T('Select Account')}</label>
                                        <div class="col-md-6">
                                            <select {if $cust}{else}id="personSelect"{/if} class="form-select select2" style="height: 52px; background-color: white;"
                                                name="id_customer" style="width: 100%" data-placeholder="{Lang::T('Select a customer')}..." data-ajax="true">
                                                {if $cust}
                                                    <option value="{$cust['id']}">{$cust['username']} &bull; {$cust['fullname']} &bull; {$cust['email']}</option>
                                                {/if}
                                            </select>
                                            <span class="help-block" id="customer-help">
                                                {Lang::T('Start typing to search for customers')}
                                            </span>
                                        </div>
                                    </div>
                                    <div class="form-group row">
                                        <label class="col-md-2 control-label">{Lang::T('Type')}</label>
                                        <div class="col-md-6">
                                            <label><input type="radio" id="Hot" name="type" value="Hotspot"> {Lang::T('Hotspot Plans')}</label>
                                            <label><input type="radio" id="POE" name="type" value="PPPOE"> {Lang::T('PPPOE Plans')}</label>
                                        </div>
                                    </div>
                                    <div class="form-group row">
                                        <label class="col-md-2 control-label">{Lang::T('Routers')}</label>
                                        <div class="col-md-6">
                                            <select id="server" data-type="server" name="server" class="form-control" style="height: 52px; background-color: white; cursor: pointer; z-index: 1000;">
                                                <option value=''>{Lang::T('Select Routers')}</option>
                                            </select>
                                            <span class="help-block" id="server-help">
                                                {Lang::T('Select service type first to load available routers')}
                                            </span>
                                        </div>
                                    </div>
                
                                    <div class="form-group row">
                                        <label class="col-md-2 control-label">{Lang::T('Service Plan')}</label>
                                        <div class="col-md-6">
                                            <select id="plan" name="plan" class="form-control" style="height: 52px; background-color: white; cursor: pointer; z-index: 1000;">
                                                <option value=''>{Lang::T('Select Plans')}</option>
                                            </select>
                                            <span class="help-block" id="plan-help">
                                                {Lang::T('Select a router and type first to load available plans')}
                                            </span>
                                        </div>
                                    </div>
                                    <div class="form-group row">
                                        <label class="col-md-2 control-label">{Lang::T('Using')}</label>
                                        <div class="col-md-6">
                                            <select name="using" class="form-control" style="height: 52px; background-color: white; cursor: pointer; z-index: 1000;">
                                                <option value="cash">{Lang::T('Cash')}</option>
                                                {if $_c['enable_balance'] eq 'yes'}
                                                    <option value="balance">{Lang::T('Customer Balance')}</option>
                                                {/if}
                                                <option value="zero">{$_c['currency_code']} 0</option>
                                            </select>
                                        </div>
                                        <p class="help-block col-md-4">Postpaid Recharge for the first time use {$_c['currency_code']} 0</p>
                                    </div>
                                    <center>
                                        <div class="form-group row">
                                            <div class="col-lg-offset-2 col-lg-10">
                                                <button class="btn btn-success mb-3"
                                                    type="submit">{Lang::T('Recharge')}</button>
                                                Or <a class="btn btn-outline-primary href="{$_url}customers/list">{Lang::T('Cancel')}</a>
                                            </div>
                                        </div>
                                    </center>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
{include file="sections/footer.tpl"}

<script>
$(document).ready(function() {
    console.log('Recharge form loaded');
    console.log('jQuery version:', $.fn.jquery);
    console.log('Select2 available:', typeof $.fn.select2);
    
    // Initialize customer select2 with AJAX (if not pre-selected)
    if ($('#personSelect').length > 0) {
        console.log('Initializing customer select2 with AJAX');
        setTimeout(function() {
            try {
                // Destroy existing select2 if it exists
                if ($('#personSelect').hasClass('select2-hidden-accessible')) {
                    $('#personSelect').select2('destroy');
                    console.log('Destroyed existing customer select2');
                }
                
                $('#personSelect').select2({
                    theme: "bootstrap",
                    width: '100%',
                    ajax: {
                        url: function(params) {
                            var url = './index.php?_route=autoload/customer_select2';
                            if(params.term != undefined){
                                url += '&s=' + encodeURIComponent(params.term);
                            }
                            console.log('Customer AJAX URL:', url);
                            return url;
                        },
                        dataType: 'json',
                        delay: 250,
                        data: function (params) {
                            return {
                                s: params.term || '',
                                page: params.page || 1
                            };
                        },
                        processResults: function (data, params) {
                            console.log('Customer AJAX response:', data);
                            return {
                                results: data.results || []
                            };
                        },
                        cache: true,
                        error: function(xhr, status, error) {
                            console.error('Customer AJAX error:', error);
                            console.error('Response:', xhr.responseText);
                        }
                    },
                    minimumInputLength: 0,
                    placeholder: '{Lang::T('Select a customer')}...',
                    allowClear: true
                });
                
                console.log('Customer select2 initialized with AJAX');
            } catch (error) {
                console.error('Error initializing customer select2:', error);
            }
        }, 200);
        
        // Add customer dropdown event handlers
        $('#personSelect').on('select2:open', function() {
            console.log('Customer dropdown opened');
        });
        
        $('#personSelect').on('select2:select', function(e) {
            console.log('Customer selected:', e.params.data);
        });
    }
    
    // Load servers when type changes
    $('input[type=radio][name="type"]').change(function(){
        console.log('Type changed:', $('input[name="type"]:checked').val());
        $("#server").html('<option value="">{Lang::T('Select Routers')}</option>');
        $("#plan").html('<option value="">{Lang::T('Select Plans')}</option>');
        $("#server-help").text('Loading routers...');
        $("#plan-help").text('Select a router first to load available plans');
        
        if ($('#Hot').is(':checked')) {
            $.ajax({
                type: "POST",
                dataType: "html",
                url: "index.php?_route=autoload/server",
                success: function(msg){
                    console.log('Servers loaded successfully');
                    console.log('Servers HTML:', msg);
                    $("#server").html(msg);
                    $("#server").prop('disabled', false);
                    
                    // Update help text
                    var serverCount = $("#server option").length - 1;
                    if (serverCount > 0) {
                        $("#server-help").text('Found ' + serverCount + ' router(s) available');
                    } else {
                        $("#server-help").text('No routers found. Please add routers first.');
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error loading servers:', error);
                    $("#server-help").text('Error loading routers. Please check console for details.');
                    alert('Error loading servers. Please check console for details.');
                }
            });
        } else if ($('#POE').is(':checked')) {
            $.ajax({
                type: "POST",
                dataType: "html",
                url: "index.php?_route=autoload/server",
                success: function(msg){
                    console.log('Servers loaded successfully');
                    console.log('Servers HTML:', msg);
                    $("#server").html(msg);
                    $("#server").prop('disabled', false);
                    
                    // Update help text
                    var serverCount = $("#server option").length - 1;
                    if (serverCount > 0) {
                        $("#server-help").text('Found ' + serverCount + ' router(s) available');
                    } else {
                        $("#server-help").text('No routers found. Please add routers first.');
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error loading servers:', error);
                    $("#server-help").text('Error loading routers. Please check console for details.');
                    alert('Error loading servers. Please check console for details.');
                }
            });
        }
    });
    
    // Load plans when server changes
    $("#server").change(function(){
        var server = $("#server").val();
        var jenis = $('input[name="type"]:checked').val();
        
        console.log('Server changed:', server, 'Type:', jenis);
        
        if (server && jenis) {
            $("#plan-help").text('Loading plans...');
            $.ajax({
                type: "POST",
                dataType: "html",
                url: "index.php?_route=autoload/plan",
                data: "jenis=" + jenis + "&server=" + server,
                success: function(msg){
                    console.log('Plans loaded successfully');
                    console.log('Plans HTML:', msg);
                    $("#plan").html(msg);
                    
                    // Ensure the dropdown is enabled and clickable
                    $("#plan").prop('disabled', false);
                    $("#plan").removeClass('disabled');
                    
                    // Update help text
                    var planCount = $("#plan option").length - 1;
                    if (planCount > 0) {
                        $("#plan-help").text('Found ' + planCount + ' plan(s) available');
                    } else {
                        $("#plan-help").text('No plans found for this router and type. Please create plans first.');
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error loading plans:', error);
                    $("#plan-help").text('Error loading plans. Please check console for details.');
                    alert('Error loading plans. Please check console for details.');
                }
            });
        } else {
            $("#plan").html('<option value="">{Lang::T('Select Plans')}</option>');
            $("#plan-help").text('Select a router and type first to load available plans');
        }
    });
    
    // Add click handlers for debugging
    $("#server").click(function(){
        console.log('Server dropdown clicked');
        console.log('Server dropdown disabled:', $(this).prop('disabled'));
        console.log('Server dropdown options:', $(this).find('option').length);
    });
    
    $("#plan").click(function(){
        console.log('Plan dropdown clicked');
        console.log('Plan dropdown disabled:', $(this).prop('disabled'));
        console.log('Plan dropdown options:', $(this).find('option').length);
    });
    
    // Test AJAX endpoints directly
    $.ajax({
        url: './index.php?_route=autoload/customer_select2',
        dataType: 'json',
        success: function(data) {
            console.log('Customer AJAX test successful:', data);
        },
        error: function(xhr, status, error) {
            console.error('Customer AJAX test failed:', error);
            console.error('Response:', xhr.responseText);
        }
    });
    
    $.ajax({
        url: './index.php?_route=autoload/server',
        type: 'POST',
        dataType: 'html',
        success: function(data) {
            console.log('Server AJAX test successful:', data);
        },
        error: function(xhr, status, error) {
            console.error('Server AJAX test failed:', error);
            console.error('Response:', xhr.responseText);
        }
    });
});
</script>