<?php echo $this->extend('template/admin/main') ?>

<?php echo $this->section('content') ?>
    <?php echo $this->include('common/message') ?>

    <div class="card mb-4">
        <div class="card-body">

            <?php if ($add_agent == true) : ?>
                <div class="text-end">
                    
                    <?php if (true && false) : ?>
                        <?php if (!isset($trash_view)) : ?>
                            <a class="btn btn-warning me-1" href="<?php echo base_url(route_to('trash-index-agent')) ?>">
                                <i class="fas fa-trash-restore"></i>
                                <?php echo lang("Localize.view_deleted") ?>
                            </a>
                        <?php else : ?>
                            <a class="btn btn-info me-1" href="<?php echo base_url(route_to('index-agent')) ?>">
                                <i class="fas fa-list"></i>
                                <?php echo lang("Localize.view_all") ?>
                            </a>
                        <?php endif; ?>
                    <?php endif; ?>

                    <a class="btn btn-success" href="<?php echo base_url(route_to('new-agent')) ?>"><i class="fas fa-user-plus"></i> <?php echo lang("Localize.add_agent") ?></a>
                </div>
            <?php endif ?>

            <div class="table-responsive">
                <table class="table display table-bordered table-striped table-hover basic" id="agentlist">
                    <thead>
                        <tr>
                            <th scope="col">#</th>
                            <?php if($role_id == 1){ ?>
                            <th scope="col"><?php echo lang("Localize.company") ?></th>
                            <?php } ?>
                            <th scope="col"><?php echo lang("Localize.name") ?></th>
                            <th scope="col"><?php echo lang("Localize.email") ?></th>
                            <th scope="col"><?php echo lang("Localize.mobile") ?></th>
                            <th scope="col"><?php echo lang("Localize.commission") ?></th>
                            <th scope="col"><?php echo lang("wallet") ?></th>
                            <th scope="col"><?php echo lang("Localize.status") ?></th>

                            <?php if ($role_id == 1) : ?>
                                <th scope="col"><?php echo lang("Localize.action") ?></th>
                            <?php endif ?>
                        </tr>
                    </thead>
                    <tbody>
                        
                    </tbody>
                </table>
            </div>

        </div>
    </div>
    <?php echo $this->include('common/datatable_default_lang_change') ?>
    <?php echo $this->include('common/confirmation-modal') ?>
    
    <!-- CSRF Token for AJAX -->
    <input type="hidden" name="<?php echo csrf_token(); ?>" id="csrf_token" value="<?php echo csrf_hash(); ?>">
    
    <!--model for wallet-->
    <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Wallet Balance&Reacharge </h5>
                    <button type="button" class="close"  onclick='modelClose()' data-dismiss="exampleModal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form action="<?php echo base_url(route_to('update-payment')) ?>" method="post">
                    <?php echo $this->include('common/security') ?>
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6">
                                <input type="hidden" name="hdnid" id='hdnid' >
                                <h3>Balance : <span id='balSpan'></span> </h3>
                            </div>
                            <div class="col-md-6">
                                <label for="">Enter Amount</label>
                                <input type="text" class='form-group' name='recgAmt' id='recgAmt' placeholder='Enter Amount'>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" onclick='modelClose()' class="btn btn-secondary" data-dismiss="exampleModal">Close</button>
                        <button type="submit" value="submit" class="btn btn-primary">Submit</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <!--model end-->
<?php echo $this->endSection() ?>

<?php echo $this->section('js') ?>
<script>
    function waletRec(id,bal){
        $("#hdnid").val(id);
        $("#balSpan").html(bal);
        $("#exampleModal").modal("show");
    }

    function modelClose(){
        $("#exampleModal").modal("hide");
    }

    $(document).ready(function () {
        // Check if DataTable is loaded
        if (typeof $.fn.DataTable === 'undefined') {
            console.error('DataTables is not loaded. Please check if datatables.min.js is included.');
            return;
        }
        
        // Get company name from hidden input or use default
        var companyname = $("#logotext").val() || "<?php echo lang('Localize.agent_list'); ?>";
        
        // Check if table exists
        if ($('#agentlist').length === 0) {
            console.error("Table #agentlist not found!");
            return;
        }
        
        // Destroy existing DataTable instance if it exists (from mydatatable.js client-side init)
        if ($.fn.DataTable.isDataTable('#agentlist')) {
            $('#agentlist').DataTable().destroy();
            console.log("Destroyed existing client-side DataTable instance for #agentlist");
        }
        
        console.log("Initializing server-side DataTable for #agentlist");
        console.log("Number of header columns:", $('#agentlist thead th').length);

        var table = $('#agentlist').DataTable({
            processing: true,
            serverSide: true,
            lengthMenu: [[10, 15, 20, 25, 30, 40, 50, -1], [10, 15, 20, 25, 30, 40, 50, "All"]],
            dom: 'lBfrtip',
            language: {
                search: search,
                lengthMenu: lengthMenu,
                zeroRecords: zeroRecords,
                info: info,
                infoEmpty: infoEmpty,
                infoFiltered: infoFiltered,
                paginate: {
                    first: first,
                    previous: previous,
                    next: next,
                    last: last
                }
            },

            ajax: {
                url: "<?= base_url(route_to('server-agent-list')); ?>",
                type: "POST",
                data: function(d) {
                    // Add CSRF token to the request data
                    var csrfToken = $('#csrf_token').val() || $('input[name="<?php echo csrf_token(); ?>"]').val();
                    if (csrfToken) {
                        d.<?php echo csrf_token(); ?> = csrfToken;
                    }
                    return d;
                },
                beforeSend: function(xhr) {
                    // Set CSRF token in header
                    var csrfToken = $('#csrf_token').val() || $('input[name="<?php echo csrf_token(); ?>"]').val();
                    if (csrfToken) {
                        xhr.setRequestHeader('X-CSRF-TOKEN', csrfToken);
                        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
                    }
                },
                dataSrc: 'data',
                error: function(xhr, error, code) {
                    console.error("DataTables AJAX Error:", error, code);
                    console.error("Response:", xhr.responseText);
                    if (xhr.status === 403) {
                        alert("CSRF token validation failed. Please refresh the page and try again.");
                    }
                }
            },

            buttons: [
                {
                    extend: 'copy',
                    title: companyname,
                    messageTop: companyname,
                    exportOptions: {columns: <?php echo $role_id == 1 ? '[0,1,2,3,4,5,6,7]' : '[0,1,2,3,4,5,6]'; ?>}
                },
                {
                    extend: 'csv',
                    title: companyname,
                    messageTop: companyname,
                    exportOptions: {columns: <?php echo $role_id == 1 ? '[0,1,2,3,4,5,6,7]' : '[0,1,2,3,4,5,6]'; ?>}
                },
                {
                    extend: 'excel',
                    title: companyname,
                    messageTop: companyname,
                    exportOptions: {columns: <?php echo $role_id == 1 ? '[0,1,2,3,4,5,6,7]' : '[0,1,2,3,4,5,6]'; ?>}
                },
                {
                    extend: 'pdf',
                    title: companyname,
                    messageTop: companyname,
                    exportOptions: {columns: <?php echo $role_id == 1 ? '[0,1,2,3,4,5,6,7]' : '[0,1,2,3,4,5,6]'; ?>}
                },
                {
                    extend: 'print',
                    title: companyname,
                    messageTop: companyname,
                    exportOptions: {columns: <?php echo $role_id == 1 ? '[0,1,2,3,4,5,6,7]' : '[0,1,2,3,4,5,6]'; ?>}
                }
            ],

            columns: [
                { data: "index", orderable: false }<?php if($role_id == 1): ?>,
                { data: "company" }<?php endif; ?>,
                { data: "name" },
                { data: "email" },
                { data: "mobile" },
                { data: "commission" },
                { data: "wallet", orderable: false },
                { data: "status", orderable: false }<?php if ($role_id == 1): ?>,
                { data: "action", orderable: false, searchable: false }<?php endif; ?>
            ],

            responsive: true,

            initComplete: function () {
                var api = this.api();
                console.log("DataTables initialized. Columns:", api.columns().count());
                console.log("DataTables data:", api.rows().data().toArray());

                $('.column-search').on('keyup', function () {
                    let colIndex = $(this).data('col');
                    api.column(colIndex).search(this.value).draw();
                });
                
            },
            
            drawCallback: function(settings) {
                console.log("DataTables draw callback fired");
                var api = this.api();
                console.log("Current page data:", api.rows({page: 'current'}).data().toArray());
            }
        });

    });
</script>
<?php echo $this->endSection() ?>