<div class="card">
    <div class="card-body">
        <button class="btn btn-primary mb-2" onclick="export2csv()">Download csv</button>
        <div class="table-responsive">
            <table id="dataTable" class="display table">
                <thead class="bg-gray-50">
                    <tr>
                        <th>Employee Id</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Remark</th>
                        <th>Salary</th>
                    </tr>
                </thead>
                <tbody>
                    @php
                        $totalSalary = 0;
                    @endphp
                    @foreach ($employeePayments as $item)
                        <tr>
                            <td>{{ $item->employee_id }}</td>
                            <td>{{ $item->employee->name }}</td>
                            <td>{{ $item->employee->email }}</td>
                            <td>{{ $item->remark }}</td>
                            <td>{{ $item->amount }}</td>
                            @php
                                $totalSalary += $item->amount;
                            @endphp
                        </tr>
                    @endforeach
                    <tr>
                        <td colspan="4" class="text-right">Total : </td>
                        <td>{{ $totalSalary }}</td>
                    </tr>

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

    </div>
</div>


<script>
    function export2csv() {
        let data = "";
        const tableData = [];
        const rows = document.querySelectorAll("table#dataTable 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.replace(',', ''));
                }
            }
            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", "Employee payment.csv");
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
    }
</script>
