<?php


$parentuserid  = isset($_SESSION['userid']) ? $_SESSION['userid'] : NULL;


$reseller = $obj->details_by_cond('_reseller_createuser', "UserId = '$parentuserid'");




$startdate = isset($_GET['start']) ? $_GET['start'] : date('Y-m-d', strtotime('01-' . date('m-Y')));
$enddate   = isset($_GET['end']) ? $_GET['end'] : date('Y-m-d');




$cusacc = $obj->raw_sql("
    SELECT tbAcc.*, ag.ag_name, ag.cus_id, ag.ip
    FROM re_tbl_account tbAcc
    LEFT JOIN re_tbl_agent ag ON ag.ag_id = tbAcc.agent_id
    WHERE agent_id!=''
      AND reseller_id = $parentuserid
      AND tbAcc.entry_date BETWEEN '$startdate' AND '$enddate'
");


// Date range
$startdate = $_GET['start'] ?? date('Y-m-d', strtotime('first day of this month'));
$enddate   = $_GET['end'] ?? date('Y-m-d');

// Current period transactions
$resacc = $obj->view_all_by_cond(
  're_tbl_reseller_account',
  "reseller_id = '$parentuserid'
     AND entry_date BETWEEN '$startdate' AND '$enddate'
     ORDER BY entry_date ASC"
);

// Opening balance calculation
$previousTransactions = $obj->view_all_by_cond(
  're_tbl_reseller_account',
  "reseller_id = '$parentuserid'
     AND entry_date < '$startdate'"
);

$openingBalance = 0;

foreach ($previousTransactions as $acc) {

  // ADD (Balance Add + Recharge)
  if (in_array($acc['type'], [1, 3])) {
    $openingBalance += $acc['amount'];
  }

  // DEDUCT
  if (in_array($acc['type'], [2, 5])) {
    $openingBalance -= $acc['amount'];
  }
}
?>

<div class="container-fluid">

  <!-- PAGE TITLE -->
  <div class="row mb-3">
    <div class="col-12">
      <h6 class="fw-bold text-primary"> Reseller Super Ledger</h6>
      <hr>
    </div>
  </div>

  <!-- DATE FILTER -->
  <div class="card mb-4 shadow-sm">
    <div class="card-body">
      <form>
        <input type="hidden" name="page" value="reseller-recharge">
        <input type="hidden" name="id" value="<?= $parentuserid ?>">

        <div class="row g-2">
          <div class="col-md-4 col-12">
            <input type="date" name="start" class="form-control" value="<?= $startdate ?>">
          </div>
          <div class="col-md-4 col-12">
            <input type="date" name="end" class="form-control" value="<?= $enddate ?>">
          </div>
          <div class="col-md-4 col-12">
            <button class="btn btn-success w-100">Search Ledger</button>
          </div>
        </div>
      </form>
    </div>
  </div>

  <!-- TABS -->
  <ul class="nav nav-tabs mb-3" role="tablist">
    <li class="nav-item">
      <button class="nav-link active fw-bold"
        data-bs-toggle="tab"
        data-bs-target="#resellerLedger"
        type="button">
        Reseller Recharge
      </button>
    </li>
    <li class="nav-item">
      <button class="nav-link fw-bold"
        data-bs-toggle="tab"
        data-bs-target="#customerLedger"
        type="button">
        Customer Recharge
      </button>
    </li>
  </ul>

  <div class="tab-content">

    <!-- TAB 1 : RESELLER LEDGER -->
<div class="tab-pane fade show active" id="resellerLedger">
  <div class="card shadow-sm">
    <div class="card-header bg-primary text-white fw-bold">
      Reseller Recharge Ledger
    </div>

    <div class="card-body table-responsive">
      <table id="resellerTable" class="table table-bordered table-striped table-hover align-middle nowrap" style="width:100%">

        <thead class="table-dark text-center">
          <tr>
            <th>Date</th>
            <th>Description</th>
            <th>Remark</th>
            <th>Payment Given</th>
            <th>Balance Add</th>
            <th>Payment Recv (Refund)</th>
            <th>Balance Adjust</th>
            <th>Recharge</th>
            <th>Running Balance</th>
          </tr>
        </thead>

        <tbody>
          <?php
          $runningBalance = $openingBalance;

          // Variables for totals
          $totalPaymentGiven = 0;
          $totalBalanceAdd   = 0;
          $totalPaymentRecv  = 0;
          $totalBalanceAdjust = 0;
          $totalRecharge     = 0;

          foreach ($resacc as $acc):

            // ADD (type 1)
            if (in_array($acc['type'], [1])) {
              $runningBalance += $acc['amount'];
              $totalBalanceAdd += $acc['amount'];
            }

            // DEDUCT (type 2,5)
            if (in_array($acc['type'], [2, 5])) {
              $runningBalance -= $acc['amount'];
            }

            // Type wise totals
            if ($acc['type'] == 3) $totalPaymentGiven += $acc['amount'];
            if ($acc['type'] == 4) $totalPaymentRecv  += $acc['amount'];
            if ($acc['type'] == 2) $totalBalanceAdjust += $acc['amount'];
            if ($acc['type'] == 5) $totalRecharge     += $acc['amount'];
          ?>
            <tr>
              <td class="text-center"><?= date('d-m-Y', strtotime($acc['entry_date'])) ?></td>
              <td class="text-center"><?= htmlspecialchars($acc['description']) ?></td>
              <td class="text-center"><?= htmlspecialchars($acc['remark'] ?? 'N/A') ?></td>
              <td class="text-end"><?= $acc['type'] == 3 ? number_format($acc['amount'], 2) : '-' ?></td>
              <td class="text-end"><?= $acc['type'] == 1 ? number_format($acc['amount'], 2) : '-' ?></td>
              <td class="text-end"><?= $acc['type'] == 4 ? number_format($acc['amount'], 2) : '-' ?></td>
              <td class="text-end"><?= $acc['type'] == 2 ? number_format($acc['amount'], 2) : '-' ?></td>
              <td class="text-end"><?= $acc['type'] == 5 ? number_format($acc['amount'], 2) : '-' ?></td>
              <td class="text-end fw-bold"><?= number_format($runningBalance, 2) ?></td>
            </tr>
          <?php endforeach; ?>
        </tbody>

        <!-- ✅ FOOTER WITH TOTALS -->
        <tfoot class="table-dark fw-bold text-end">
          <tr>
            <td colspan="3" class="text-center"><strong>Total</strong></td>
            <td><?= number_format($totalPaymentGiven, 2) ?></td>
            <td><?= number_format($totalBalanceAdd, 2) ?></td>
            <td><?= number_format($totalPaymentRecv, 2) ?></td>
            <td><?= number_format($totalBalanceAdjust, 2) ?></td>
            <td><?= number_format($totalRecharge, 2) ?></td>
            <td></td> <!-- Running Balance has no total -->
          </tr>
        </tfoot>

      </table>
    </div>
  </div>
</div>

    <!-- TAB 2 : CUSTOMER LEDGER -->
    <div class="tab-pane fade" id="customerLedger">
      <div class="card shadow-sm">
        <div class="card-header bg-secondary text-white fw-bold">
          Customer Recharge Ledger
        </div>

        <div class="card-body table-responsive">
          <table id="customerTable" class="table table-bordered table-striped table-hover align-middle display nowrap" style="width:100%">
            <thead class="table-dark text-center">
              <tr>
                <th>#</th>
                <th>Customer</th>
                <th>Customer ID</th>
                <th>IP</th>
                <th>Date</th>
                <th>Description</th>
                <th>Amount</th>
              </tr>
            </thead>

            <tbody>
              <?php $sl = 0;
              $totalAmount = 0;
              foreach ($cusacc as $acc): $sl++; ?>
                <?php if ($acc['acc_type'] == 3 || $acc['acc_type'] == 5) $totalAmount += $acc['acc_amount']; ?>
                <tr>
                  <td><?= $sl ?></td>
                  <td><?= $acc['ag_name'] ?></td>
                  <td><?= $acc['cus_id'] ?></td>
                  <td><?= $acc['ip'] ?></td>
                  <td><?= date('d-m-Y', strtotime($acc['entry_date'])) ?></td>
                  <td><?= $acc['acc_description'] ?></td>
                  <td><?= $acc['acc_amount'] ?></td>
                </tr>
              <?php endforeach; ?>
            </tbody>

            <tfoot class="fw-bold">
              <tr>
                <td colspan="6" class="text-end">Total</td>
                <td><?= $totalAmount ?></td>
              </tr>
            </tfoot>
          </table>
        </div>
      </div>
    </div>

  </div>
</div>

<?php $obj->start_script(); ?>


<script>
  $(document).ready(function() {

    $('#resellerTable').DataTable({
      scrollX: true,
      footer: true,
      pageLength: 25,
      order: [
        [0, 'asc']
      ],
      columnDefs: [{
          targets: [3, 4, 5, 6, 7, 8],
          className: 'text-end',
          type: 'num'
        },
        {
          targets: 0,
          type: 'date'
        }
      ],
      createdRow: function(row) {
        if ($(row).hasClass('opening-balance')) {
          $(row).addClass('bg-light fw-bold');
        }
      }
    });

    $('#customerTable').DataTable({
      scrollX: true,
      pageLength: 25,
      dom: 'Bfrtip',
      buttons: ['copy', 'excel', 'csv', 'pdf', 'print']
    });

    // Fix tab resize
    $('button[data-bs-toggle="tab"]').on('shown.bs.tab', function() {
      $($.fn.dataTable.tables(true)).DataTable().columns.adjust();
    });
  });
</script>



<?php $obj->end_script(); ?>