<?php

$sessiondata = \Config\Services::session();
?>

<?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_data == true) && ($userType == 2)) : ?>
            <div class="text-end">
                <a class="btn btn-success" href="<?php echo base_url(route_to('new-payagent')) ?>"><?php echo lang("Localize.wallet_recharge") ?></a>
            </div>
      <?php endif ?>

      <form action="<?php echo base_url(route_to('date-range')) ?>" id="payagentFilterForm" 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="payagent_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="payagent_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>
      <?php
      $userid = $sessiondata->get('user_id');

      if ($sessiondata->get('role_id') == 2) {
          $db = \Config\Database::connect();

          $builder = $db->table('agents');
          $builder->where('user_id', $userid);
          $result = $builder->get()->getRowArray();

          if ($result): ?>
              <div style="width: 30%; margin: 10px; border: 1px solid #ddd; border-radius: 5px; box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.1);">
                  <div style="padding: 15px;">
                      <h5 style="margin: 0 0 10px; font-size: 16px; font-weight: bold;">Wallet Balance</h5>
                      <p style="margin: 0; font-size: 14px; color: #555;">
                          <?= number_format($result['wallet'], 2); ?> EGP
                      </p>
                  </div>
              </div>
          <?php endif;
      }
      ?>
      <?php if (!empty($companyBalances) && is_array($companyBalances)): ?>
          <div class="row mt-4">
              <?php foreach ($companyBalances as $companyName => $balance): ?>
                  <div style="width: 30%; margin: 10px; border: 1px solid #ddd; border-radius: 5px; box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.1);">
                      <div style="padding: 15px;">
                          <h5 style="margin: 0 0 10px; font-size: 16px; font-weight: bold;"><?php echo $companyName; ?> Wallet Balance</h5>
                          <p style="margin: 0; font-size: 14px; color: #555;">
                              <?php echo number_format($balance, 2); ?> EGP
                          </p>
                      </div>
                  </div>
              <?php endforeach; ?>
          </div>
      <?php endif; ?>

        <div class="table-responsive mt-3">
        <table class="table display table-bordered table-striped table-hover basic" id="agentpay" data-server="1">
          <thead>
            <tr>
              <th scope="col">#</th>
              <?php if ($userType == 1 || $userType == 2): ?>
                  <th scope="col"><?php echo lang("Localize.company") ?></th>
              <?php endif; ?>
              <?php if ($userType == 7 || $userType == 1): ?>
                  <th scope="col"><?php echo lang("Localize.agent") ?></th>
              <?php endif; ?>
              <th scope="col"><?php echo lang("Localize.id") ?> </th>
              <th scope="col"><?php echo lang("Localize.payment_method") ?> </th>
              <th scope="col"><?php echo lang("Localize.id") ?> </th>
              <th scope="col"><?php echo lang("Localize.status") ?> </th>
              <th scope="col">Refund Amount</th>
              <th scope="col">Cancelation Fee</th>
              <th scope="col">Available Balance</th>
              <th scope="col">Detail</th>
              <th scope="col">Request Date</th>
              <th scope="col">Approve Date</th>
              <th scope="col">Approved by</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' || !$('#agentpay').length) {
        return;
    }

    var userType = <?php echo (int) $userType; ?>;
    var showCompany = (userType === 1 || userType === 2);
    var showAgent = (userType === 1 || userType === 7);
    var companyname = $("#logotext").val() || "Agent Payments";

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

    var columns = [{ data: 'index', orderable: false }];
    if (showCompany) {
        columns.push({ data: 'company_name', orderable: true });
    }
    if (showAgent) {
        columns.push({ data: 'agent_name', orderable: true });
    }
    columns = columns.concat([
        { data: 'payment_id', orderable: true },
        { data: 'payment_mode', orderable: true, searchable: false },
        { data: 'reference', orderable: true },
        { data: 'status', orderable: true, searchable: false },
        { data: 'amount', orderable: true },
        { data: 'cancel_amount', orderable: false, searchable: false },
        { data: 'total_balance', orderable: false, searchable: false },
        { data: 'detail', orderable: true },
        { data: 'created_at', orderable: true },
        { data: 'accepted_date', orderable: true },
        { data: 'approved_by', orderable: true },
        { data: 'action', orderable: false, searchable: false }
    ]);

    var orderCol = columns.length - 4;

    var table = $('#agentpay').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-payagent-list')); ?>",
            type: "POST",
            data: function (d) {
                var csrfToken = $('#csrf_token').val();
                if (csrfToken) {
                    d.<?php echo csrf_token(); ?> = csrfToken;
                }
                d.start_date = $('#payagent_start_date').val();
                d.end_date = $('#payagent_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 agent payments. Please refresh and try again.');
                }
            }
        },
        buttons: [
            { extend: 'copy', title: companyname, messageTop: companyname },
            { extend: 'csv', title: companyname, messageTop: companyname },
            { extend: 'excel', title: companyname, messageTop: companyname },
            { extend: 'pdf', title: companyname, messageTop: companyname },
            { extend: 'print', title: companyname, messageTop: companyname }
        ],
        columns: columns,
        order: [[orderCol, 'desc']],
        responsive: true,
        columnDefs: [
            { targets: -1, orderable: false }
        ]
    });

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