<?php
$id   = isset($_SESSION['userid']) ? (int)$_SESSION['userid'] : 0;
$date = date('Y-m-d');

if ($id <= 0) { echo '<div class="alert alert-danger">Session expired</div>'; exit; }

if (isset($_GET['payment'])) {
    $customers = $obj->view_all_by_cond('re_tbl_agent', "entry_by=$id AND mikrotik_disconnect='$date' ORDER BY ag_id DESC");
} else {
    $customers = $obj->view_all_by_cond('re_tbl_agent', "entry_by=$id AND mikrotik_disconnect='$date' ORDER BY ag_id DESC");
}

$allCus  = (int)$obj->Total_Count('re_tbl_agent',
    "entry_by=$id AND (payment_status=0 OR (payment_status=1 AND mikrotik_disconnect BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 5 DAY)))"
);

$paidCus = (int)$obj->Total_Count('re_tbl_agent', "entry_by=$id AND payment_status=1");
$rBalance = (float)$obj->get_sum_by_cond('balance', 're_vw_user_info', "UserType='RE' and UserId=$id");
?>

<style>
:root{
  --bg:#f6f8fb; --card:#fff; --text:#111827; --muted:#6b7280;
  --border:#e5e7eb; --shadow:0 12px 28px rgba(17,24,39,.08);
  --radius:14px; --primary:#2563eb; --success:#16a34a; --warning:#f59e0b;
}
.page-wrap{ padding: 12px 0; }
.headbar{
  display:flex; align-items:flex-start; justify-content:space-between; gap:12px; flex-wrap:wrap;
  margin-bottom: 12px;
}
.title{
  margin:0; font-weight:900; color:var(--text); font-size:18px; display:flex; gap:10px; align-items:center;
}
.subtitle{ margin-top:4px; color:var(--muted); font-size:12px; }

.badge-balance{
  display:inline-flex; align-items:center; gap:8px;
  padding: 8px 12px; border-radius:999px;
  border:1px solid var(--border); background:#fff; font-weight:900;
}
.badge-balance .dot{ width:10px; height:10px; border-radius:50%; background: var(--success); display:inline-block; }

.filters{ display:flex; gap:8px; flex-wrap:wrap; margin: 10px 0 0; }
.filters .btn{ border-radius:10px !important; font-weight:900; }
.filters .btn.active{ box-shadow:0 10px 22px rgba(17,24,39,.12); transform: translateY(-1px); }

.cardx{
  background: var(--card); border:1px solid var(--border); border-radius: var(--radius);
  box-shadow: var(--shadow); overflow:hidden;
}
.cardx-h{
  padding: 12px 14px;
  background: linear-gradient(135deg, #0b9444, #57606f);
  color:#fff;
  display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; gap:10px;
}
.cardx-h .h-title{ margin:0; font-weight:900; font-size:14px; display:flex; gap:10px; align-items:center; }
.controls{
  display:flex; align-items:center; gap:10px; flex-wrap:wrap;
}
.chk-pill{
  display:inline-flex; align-items:center; gap:10px;
  padding: 8px 12px; border-radius:999px;
  background: rgba(255,255,255,.18);
  border: 1px solid rgba(255,255,255,.35);
  cursor:pointer; user-select:none; font-weight:900;
}
.chk-pill input{ margin:0; }
.btn-pay{
  border-radius:10px !important; font-weight:900;
  background: #fff; color:#0b9444; border:0;
  padding: 8px 12px;
}
.btn-pay:hover{ opacity:.95; }

.table-soft thead th{
  background:#f3f4f6 !important; border-bottom:1px solid var(--border) !important;
  font-weight:900; font-size:12px; white-space:nowrap;
}
.table-soft tbody td{
  border-top:1px solid var(--border) !important;
  font-size:12px; vertical-align:middle !important;
}
.row-check{
  width: 18px; height: 18px; cursor:pointer;
}
.pill{
  display:inline-block; padding:6px 10px; border-radius:999px; font-weight:900; font-size:11px;
  border:1px solid var(--border); background:#fff;
}
.pill-speed{ background: rgba(37,99,235,.10); border-color: rgba(37,99,235,.25); color:#1d4ed8; }
.pill-due{ background: rgba(245,158,11,.12); border-color: rgba(245,158,11,.25); color:#92400e; }
.pill-danger{ background: rgba(239,68,68,.12); border-color: rgba(239,68,68,.25); color:#991b1b; }
.pill-adv{ background: rgba(16,185,129,.12); border-color: rgba(16,185,129,.25); color:#065f46; }

.summary{
  margin-top: 12px;
  background:#fff;
  border:1px solid var(--border);
  border-radius: var(--radius);
  box-shadow: 0 10px 24px rgba(17,24,39,.06);
  padding: 12px 14px;
  display:none;
}
.summary-grid{
  display:grid; gap:10px;
  grid-template-columns: repeat(4, minmax(0, 1fr));
}
.sum-box{
  border:1px dashed var(--border);
  border-radius: 12px;
  padding: 10px 12px;
}
.sum-k{ font-size:11px; color:var(--muted); font-weight:900; }
.sum-v{ font-size:16px; font-weight:900; color:var(--text); margin-top:4px; }
.sum-v small{ font-size:12px; color:var(--muted); font-weight:900; }
.sum-ips{ grid-column: 1 / -1; }

@media (max-width: 991px){
  .summary-grid{ grid-template-columns: repeat(2, minmax(0, 1fr)); }
}
@media (max-width: 767px){
  .summary-grid{ grid-template-columns: 1fr; }
  .controls{ width:100%; justify-content:flex-start; }
  .btn-pay{ width:100%; }
}

/* DataTables (if used) */
.dataTables_filter input{
  height:36px !important; border-radius:10px !important; border:1px solid var(--border) !important;
  padding:6px 10px !important;
}
.dataTables_length select{
  height:36px !important; border-radius:10px !important; border:1px solid var(--border) !important;
}
.pagination>li>a, .pagination>li>span{ border-radius:10px !important; margin:0 2px; }
</style>

<div class="container-fluid page-wrap">

  <div class="headbar">
    <div>
      <h6 class="title"><i class="fa fa-bolt"></i> Customer Bulk Payment</h6>
      <div class="subtitle">Select customers and recharge them in one click</div>

      <div class="filters">
        <a class="btn btn-info btn-sm <?php echo !isset($_GET['payment']) ? 'active' : ''; ?>"
           href="?page=reseller-customer-bulk-recharge">All (<?php echo $allCus; ?>)</a>

        <a class="btn btn-warning btn-sm <?php echo isset($_GET['payment']) ? 'active' : ''; ?>"
           href="?page=reseller-bill-collection&payment=1">Paid List (<?php echo $paidCus; ?>)</a>
      </div>
    </div>

    <div class="badge-balance">
      <span class="dot"></span>
      Available Balance: <span id="abBalanceText"><?php echo number_format($rBalance, 0); ?></span>
    </div>
  </div>

  <div class="cardx">
    <div class="cardx-h">
      <h6 class="h-title"><i class="fa fa-users"></i> Customers to Recharge Today (<?php echo htmlspecialchars($date); ?>)</h6>

      <div class="controls">
        <label class="chk-pill" for="all_bulrecharge">
          <input class="row-check" type="checkbox" id="all_bulrecharge">
          Select All
        </label>

        <form action="reseller/customer/bulk_recharge_ajax.php" method="POST" id="pay_bulk" style="margin:0;">
          <button type="submit" class="btn-pay" id="bulkPayBtn">
            <i class="fa fa-credit-card"></i> Pay Selected
          </button>
        </form>
      </div>
    </div>

    <div class="table-responsive">
      <table class="table table-hover table-soft" id="datatablee" style="margin:0; width:100%;">
        <thead>
          <tr>
            <th style="width:120px;">Select</th>
            <th>ID - Name</th>
            <th>IP/Secret</th>
            <th>Address</th>
            <th>Mobile</th>
            <th>Disconnected</th>
            <th>Package/Speed</th>
            <th>Bill</th>
            <th>DueAdvance</th>
          </tr>
        </thead>
        <tbody>
          <?php
          $totalbill = 0; $totalGeneratebill = 0;
          foreach ($customers as $customer) {
            $agId = (int)$customer['ag_id'];
            $dueav = (float)$customer['dueadvance'];
            $taka  = (float)$customer['taka'];
            $reTaka= (float)$customer['re_taka'];

            $totalbill += ($dueav > 0) ? $dueav : 0;
            $totalGeneratebill += $taka;
          ?>
          <tr>
            <td>
              <label class="chk-pill" style="background:#eef2ff; border-color:#dbeafe; color:#1d4ed8;">
                <input
                  class="row-check js-row-check"
                  type="checkbox"
                  name="bulk_recharge[]"
                  value="<?php echo $agId; ?>"
                  data-retaka="<?php echo $reTaka; ?>"
                  data-bill="<?php echo $taka; ?>"
                  data-ip="<?php echo htmlspecialchars($customer['ip']); ?>"
                >
                Select
              </label>
            </td>

            <td>
              <strong><?php echo htmlspecialchars($customer['cus_id']); ?></strong><br>
              <span style="font-weight:900;"><?php echo htmlspecialchars($customer['ag_name']); ?></span>
            </td>

            <td><?php echo htmlspecialchars($customer['ip']); ?></td>
            <td class="text-muted"><?php echo htmlspecialchars($customer['ag_office_address']); ?></td>
            <td><?php echo htmlspecialchars($customer['ag_mobile_no']); ?></td>

            <td><?php echo !empty($customer['mikrotik_disconnect']) ? date('d-m-Y', strtotime($customer['mikrotik_disconnect'])) : ''; ?></td>

            <td><span class="pill pill-speed"><?php echo htmlspecialchars($customer['mb']); ?></span></td>

            <td><strong>৳ <?php echo number_format($taka, 0); ?></strong></td>

            <td>
              <?php
                if ($dueav <= 0) {
                  echo '<span class="pill pill-adv">৳ '.number_format(abs($dueav),0).' (A)</span>';
                } else {
                  echo (($dueav - $taka) > 0)
                    ? '<span class="pill pill-danger">৳ '.number_format($dueav,0).'</span>'
                    : '<span class="pill pill-due">৳ '.number_format($dueav,0).'</span>';
                }
              ?>
            </td>
          </tr>
          <?php } ?>
        </tbody>
      </table>
    </div>
  </div>

  <div class="summary" id="bulk-summary">
    <div class="summary-grid">
      <div class="sum-box">
        <div class="sum-k">Selected Customers</div>
        <div class="sum-v"><span id="summary-count">0</span></div>
      </div>

      <div class="sum-box">
        <div class="sum-k">Total Customer Bill</div>
        <div class="sum-v">৳ <span id="summary-total">0</span></div>
      </div>

      <div class="sum-box">
        <div class="sum-k">Total Reseller Bill (Pay)</div>
        <div class="sum-v">৳ <span id="summary-reseller-total">0</span></div>
      </div>

      <div class="sum-box">
        <div class="sum-k">Balance Check</div>
        <div class="sum-v"><span id="summary-balance-status"><small>Select customers</small></span></div>
      </div>

      <div class="sum-box sum-ips">
        <div class="sum-k">IP/Secret</div>
        <div class="sum-v" style="font-size:12px; font-weight:900; line-height:1.4;">
          <span id="summary-ips">-</span>
        </div>
      </div>
    </div>
  </div>

  <div class="totals-bar" style="margin-top:12px; display:flex; gap:10px; flex-wrap:wrap;">
    <div class="total-chip">Total Bill Generate: <span style="color:#111827; font-weight:900;"><?php echo number_format($totalGeneratebill,0); ?></span></div>
    <div class="total-chip">Total Bill Due: <span style="color:#b45309; font-weight:900;"><?php echo number_format($totalbill,0); ?></span></div>
  </div>

  <input type="hidden" id="available-balance" value="<?php echo (float)$rBalance; ?>">
</div>

<?php $obj->start_script(); ?>
<script>
(function(){
  function num(v){
    v = (v === undefined || v === null) ? '0' : (''+v);
    v = v.replace(/[^0-9.]/g,'');
    var n = parseFloat(v);
    return isNaN(n) ? 0 : n;
  }

  function updateBulkSummary(){
    var $checked = $('input[name="bulk_recharge[]"]:checked');
    var count = $checked.length;

    var totalCus = 0;
    var totalRe  = 0;
    var ips = [];

    $checked.each(function(){
      totalCus += num($(this).data('bill'));
      totalRe  += num($(this).data('retaka'));
      ips.push($(this).data('ip'));
    });

    if (count > 0) {
      $('#bulk-summary').show();
      $('#summary-count').text(count);
      $('#summary-total').text(Math.round(totalCus));
      $('#summary-reseller-total').text(Math.round(totalRe));
      $('#summary-ips').text(ips.join(', '));
      var ab = num($('#available-balance').val());
      if (ab >= totalRe) {
        $('#summary-balance-status').html('<span class="pill pill-adv">Balance OK</span>');
      } else {
        $('#summary-balance-status').html('<span class="pill pill-danger">Insufficient</span>');
      }
    } else {
      $('#bulk-summary').hide();
    }
  }

  $(document).ready(function(){

    // optional DataTables (remove if already initialized globally)
    if ($.fn.DataTable && !$.fn.DataTable.isDataTable('#datatablee')) {
      $('#datatablee').DataTable({
        responsive: true,
        pageLength: 10,
        order: [],
        language: {
          search: "",
          searchPlaceholder: "Search customer...",
          lengthMenu: "Show _MENU_",
          info: "Showing _START_ to _END_ of _TOTAL_ customers",
          infoEmpty: "No customers found",
          zeroRecords: "No matching customers found",
          paginate: { previous: "«", next: "»" }
        }
      });
    }

    // select all
    $('#all_bulrecharge').on('change', function(){
      var checked = $(this).prop('checked');
      $('input[name="bulk_recharge[]"]').prop('checked', checked);
      updateBulkSummary();
    });

    // per row change
    $(document).on('change', 'input[name="bulk_recharge[]"]', function(){
      var total = $('input[name="bulk_recharge[]"]').length;
      var sel = $('input[name="bulk_recharge[]"]:checked').length;
      $('#all_bulrecharge').prop('checked', total > 0 && sel === total);
      updateBulkSummary();
    });

    // submit bulk pay
    $('#pay_bulk').on('submit', function(e){
      e.preventDefault();

      var selected = $('input[name="bulk_recharge[]"]:checked').map(function(){ return $(this).val(); }).get();
      if (selected.length === 0) {
        Swal.fire('Warning!', 'Please select at least one customer.', 'warning');
        return;
      }

      var totalRe = 0;
      $('input[name="bulk_recharge[]"]:checked').each(function(){
        totalRe += num($(this).data('retaka'));
      });

      var ab = num($('#available-balance').val());
      if (ab < totalRe) {
        Swal.fire('Error!', 'Insufficient balance for bulk recharge.', 'error');
        return;
      }

      Swal.fire({
        title: 'Confirm Bulk Recharge?',
        text: 'You are going to recharge ' + selected.length + ' customers.',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Yes, Recharge Now!',
        cancelButtonText: 'Cancel'
      }).then((result) => {
        if (!result.isConfirmed) return;

        $('#bulkPayBtn').prop('disabled', true).text('Processing...');

        $.ajax({
          url: $('#pay_bulk').attr('action'),
          type: "POST",
          data: { bulk_recharge: selected },
          success: function(res){
            Swal.fire('Success!', res, 'success');
            setTimeout(function(){ location.reload(); }, 1200);
          },
          error: function(xhr){
            var msg = (xhr && xhr.responseText) ? xhr.responseText : 'Request failed';
            Swal.fire('Error!', msg, 'error');
            $('#bulkPayBtn').prop('disabled', false).html('<i class="fa fa-credit-card"></i> Pay Selected');
          }
        });
      });
    });

    updateBulkSummary();
  });
})();
</script>
<?php $obj->end_script(); ?>
