<button class="btn btn-primary mb-2" onclick="export2csv()">Download csv</button>
<div class="col-md-12">
    <div class="badge badge-info float-right m-1" style="text-align: ">Total Row: {{ $list->count() }}</div>
</div>
<div id="paymenthistory" class="mt-10">
    <div class="table-responsive">
        <table class="table table-bordered " id="tableDownload">
            <tr>
                <th>#id</th>
                <th>Date</th>
                <th>Username</th>
                <th>Name</th>
                <th>Paid</th>
                <th>Discount</th>
                @if (auth()->user()->id == 1)
                    <th>OTC</th>
                @endif
            </tr>
            @php($totalOtc = 0 )
            @php($totalOtcDiscount = 0 )
            @foreach ($list as $p)
                <tr>
                    <td>{{ $p->id }}</td>
                    <td>{{ date('d-M-Y h:i:s A', strtotime($p->created_at)) }}</td>
                    <td>{{ $p->clients->userid ?? '' }}</td>
                    <td>{{ $p->clientsinfo->clients_name ?? '' }}</td>
                    <td style="text-align: right;">{{ $p->paid_amount }}</td>
                    <td style="text-align: right;">{{ $p->discount_amount }}</td>
                    @if (auth()->user()->id == 1)
                        <td style="text-align: right;">{{ $p->clientsinfo->otc ?? '' }}</td>
                    @endif
                </tr>
                @php($totalOtc += $p->paid_amount)
                @php($totalOtcDiscount += $p->discount_amount)
            @endforeach
            <tr>
              <td colspan="4" style="text-align: right;">Total</td>
              <td style="text-align: right;"><strong>{{ number_format($totalOtc, 2, '.', '') }}</strong></td>
              <td style="text-align: right;"><strong>{{ number_format($totalOtcDiscount, 2, '.', '') }}</td>
            </tr>
        </table>
    </div>
</div>
<script>

    function export2csv() {
      let data = "";
      const tableData = [];
      const rows = document.querySelectorAll("table#tableDownload tr");
      for (const row of rows) {
        const rowData = [];
        for (const [index, column] of row.querySelectorAll("th, td").entries()) {
          // To retain the commas in the "Description" column, we can enclose those fields in quotation marks.
          if ((index + 1) % 3 === 0) {
            rowData.push('"' + column.innerText + '"');
          } else {
            rowData.push(column.innerText);
          }
        }
        tableData.push(rowData.join(","));
      }
      data += tableData.join("\n");
      const a = document.createElement("a");
      a.href = URL.createObjectURL(new Blob([data], { type: "text/csv" }));
      a.setAttribute("download", "data.csv");
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    }

    </script>
