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

<?php $session = \Config\Services::session(); ?>
<?php echo $this->section('content') ?>

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

    <div class="card mb-4">
        <div class="card-body">
            <?php if ($add_data == true) : ?>
                <div class="text-end">
                    <a class="btn btn-success" href="<?php echo base_url(route_to('new-account')) ?>"> <?php echo lang("Localize.add_transaction") ?></a>
                </div>
            <?php endif ?>

            <form action="<?php echo base_url(route_to('transaction-range')) ?>" id="transactionFilterForm" method="post" class="row g-3" accept-charset="utf-8" enctype="multipart/form-data">
                <?php echo $this->include('common/security') ?>

                <div class="col-12 col-md-6 col-lg-3">
                    <label for="start_date" class="form-label"><?php echo lang("Localize.from") ?></label>
                    <div class="input-append date datepicker" id="start_date" data-date-format="yyyy-mm-dd">
                        <input size="16" type="text" name="start_date" id="account_start_date" class="form-control" value="<?php echo esc($start_date ?? date('Y-m-01')); ?>" required readonly>
                        <span class="add-on"><i class="icon-th"></i></span>
                    </div>
                </div>
                <div class="col-12 col-md-6 col-lg-3">
                    <label for="end_date" class="form-label"><?php echo lang("Localize.to") ?></label>
                    <div class="input-append date datepicker" id="end_date" data-date-format="yyyy-mm-dd">
                        <input size="16" type="text" name="end_date" id="account_end_date" class="form-control" value="<?php echo esc($end_date ?? date('Y-m-d')); ?>" required readonly>
                        <span class="add-on"><i class="icon-th"></i></span>
                    </div>
                </div>
                <div class="col-12 col-md-6 col-lg-3 mt-4 mb-2">
                    <br>
                    <button type="submit" class="btn btn-success"><?php echo lang("Localize.submit") ?></button>
                </div>
            </form>

            <div class="table-responsive mt-3">
                <table class="table display table-bordered table-striped table-hover basic" id="accountTran" data-server="1">
                    <thead>
                        <tr>
                            <th scope="col">#</th>
                            <?php if ($session->get('role_id') == 1) { ?>
                            <th scope="col"><?php echo lang("Localize.company") ?></th>
                            <?php } ?>
                            <th scope="col"><?php echo lang("Localize.details") ?></th>
                            <th scope="col"><?php echo lang("Localize.tranjection_type") ?> </th>
                            <th scope="col"><?php echo lang("Localize.amount") ?> </th>
                            <th scope="col"><?php echo lang("Localize.payment_method") ?> </th>
                            <th scope="col"><?php echo lang("Localize.ticket") . " " . lang("Localize.type")?> </th>
                            <th scope="col"><?php echo lang("Localize.merchant_id") ?></th>
                            <th scope="col"><?php echo lang("Localize.tranjection") ?> <?php echo lang("Localize.create_by") ?></th>
                            <th scope="col"><?php echo lang("Localize.tranjection") ?> <?php echo lang("Localize.date") ?> </th>
                            <th scope="col"><?php echo lang("Localize.action") ?> </th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>

        </div>
    </div>
    <input type="hidden" name="<?php echo csrf_token(); ?>" id="csrf_token" value="<?php echo csrf_hash(); ?>">
    <?php echo $this->include('common/datatable_default_lang_change') ?>
<?php echo $this->endSection() ?>

<?php echo $this->section('js') ?>
<script>
$(document).ready(function () {
    if (typeof $.fn.DataTable === 'undefined' || !$('#accountTran').length) {
        return;
    }

    var showCompany = <?php echo ($session->get('role_id') == 1) ? 'true' : 'false'; ?>;
    var companyname = $("#logotext").val() || "Transactions";

    if ($.fn.DataTable.isDataTable('#accountTran')) {
        $('#accountTran').DataTable().destroy();
    }

    var columns = [{ data: 'index', orderable: false }];
    if (showCompany) {
        columns.push({ data: 'company_name', orderable: true });
    }
    columns = columns.concat([
        { data: 'detail', orderable: true },
        { data: 'type', orderable: true },
        { data: 'amount', orderable: true },
        { data: 'payment_method', orderable: true },
        { data: 'ticket_book_type', orderable: false, searchable: false },
        { data: 'merchant_id', orderable: false, searchable: false },
        { data: 'creator_name', orderable: true },
        { data: 'created_at', orderable: true },
        { data: 'action', orderable: false, searchable: false }
    ]);

    var orderCol = showCompany ? 9 : 8;
    var exportCols = showCompany ? [0,1,2,3,4,5,6,7,8] : [0,1,2,3,4,5,6,7];

    var table = $('#accountTran').DataTable({
        processing: true,
        serverSide: true,
        pageLength: 25,
        lengthMenu: [[10, 25, 50, 100], [10, 25, 50, 100]],
        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-account-list')); ?>",
            type: "POST",
            data: function (d) {
                var csrfToken = $('#csrf_token').val();
                if (csrfToken) {
                    d.<?php echo csrf_token(); ?> = csrfToken;
                }
                d.start_date = $('#account_start_date').val();
                d.end_date = $('#account_end_date').val();
                return d;
            },
            beforeSend: function (xhr) {
                var csrfToken = $('#csrf_token').val();
                if (csrfToken) {
                    xhr.setRequestHeader('X-CSRF-TOKEN', csrfToken);
                    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
                }
            },
            dataSrc: 'data',
            error: function (xhr) {
                if (xhr.status === 403) {
                    alert('Session expired or CSRF failed. Please refresh the page and try again.');
                    return;
                }
                if (xhr.status === 500) {
                    alert('Unable to load transactions. Please refresh and try again.');
                }
            }
        },
        buttons: [
            { extend: 'copy', title: companyname, messageTop: companyname, exportOptions: { columns: exportCols } },
            { extend: 'csv', title: companyname, messageTop: companyname, exportOptions: { columns: exportCols } },
            { extend: 'excel', title: companyname, messageTop: companyname, exportOptions: { columns: exportCols } },
            { extend: 'pdf', title: companyname, messageTop: companyname, exportOptions: { columns: exportCols } },
            { extend: 'print', title: companyname, messageTop: companyname, exportOptions: { columns: exportCols } }
        ],
        columns: columns,
        order: [[orderCol, 'desc']],
        responsive: true
    });

    $('#transactionFilterForm').on('submit', function (e) {
        e.preventDefault();
        table.ajax.reload();
    });
});
</script>
<?php echo $this->endSection() ?>
