@extends('layouts.site')

@section('meta_title', 'ACCOUNT')

@section('content_header')
@include('partials._components._heading', ['heading' => 'ACCOUNT'])
@endsection

@section('content')
@php
$transactionItems = collect($transactions ?? []);
$earnedTypes = ['EARNED', 'MANUAL-RECEIVE', 'RESET', 'RETURN', 'REFUND', 'EXPIRED', 'CANCELLED'];
$redeemedTypes = ['REDEEMED', 'MANUAL-REDEEM'];
@endphp

<section class="site-main-section">
    <div class="site-container">
        <div class="account-shell mx-auto max-w-6xl">
            <div class="account-shell__aside min-w-0">
                @include('partials._components._user-menu')
            </div>
            <div class="account-shell__content min-w-0">
                <header>
                    <h1 class="text-3xl font-bold text-slate-900">Transactions</h1>
                    <p class="mt-2 text-xl text-slate-500">View your earnings and redemptions</p>
                </header>
                <section class="mt-8 grid gap-5 lg:grid-cols-3">
                    @foreach($transactionSummaryCards as $card)
                    <article class="rounded-2xl border border-slate-200 bg-white px-6 py-7 shadow-[0_2px_10px_rgba(15,23,42,0.08)]">
                        <div class="flex items-center gap-4">
                            <span class="inline-flex h-14 w-14 shrink-0 items-center justify-center rounded-[12px] border-2 border-primary bg-white text-[1.6rem] text-primary">
                                <i class="fa-solid {{ $card['icon'] }}" aria-hidden="true"></i>
                            </span>
                            <div class="min-w-0">
                                <p class="text-sm font-semibold uppercase tracking-wide text-slate-500">{{ $card['label'] }}</p>
                                <p class="mt-2 text-xl font-semibold leading-none text-slate-900">{{ $card['value'] }}</p>
                            </div>
                        </div>
                    </article>
                    @endforeach
                </section>
                <div class="transactions-dashboard mt-8">
                    <section class="transactions-toolbar">
                        <label class="transactions-search" for="transactionsSearch">
                            <i class="fa-solid fa-magnifying-glass" aria-hidden="true"></i>
                            <input
                            type="search"
                            id="transactionsSearch"
                            placeholder="Search by ID, Referral, Description or Value"
                            >
                        </label>

                        <select id="transactionsLength" class="transactions-select" aria-label="Show records" data-native-select>
                            <option value="10">Show 10</option>
                            <option value="25">Show 25</option>
                            <option value="50">Show 50</option>
                        </select>

                        <button type="button" id="transactionsDownload" class="transactions-download">
                            <i class="fa-solid fa-download" aria-hidden="true"></i>
                            Download
                            <i class="fa-solid fa-chevron-down" aria-hidden="true"></i>
                        </button>
                    </section>

                    <section class="transactions-filters" aria-label="Transaction filters">
                        <button type="button" class="transaction-filter is-active" data-filter="all">All</button>
                        <button type="button" class="transaction-filter" data-filter="earned">Earned</button>
                        <button type="button" class="transaction-filter" data-filter="redeemed">Redeemed</button>
                    </section>

                    <section class="transactions-table-shell overflow-x-auto">
                        <table class="table mb-0 w-full" id="transactionsTable" style="width: 100%;">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Description</th>
                                    <th>{{ trans_choice('Core::core.common.points', 2) }}</th>
                                    <th>Date</th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse($transactionItems as $item)
                                @php
                                $value = (float) data_get($item, 'value', 0);
                                $type = strtoupper((string) data_get($item, 'type', ''));
                                $status = match (true) {
                                    in_array($type, $redeemedTypes, true) => 'redeemed',
                                    in_array($type, $earnedTypes, true) => 'earned',
                                    default => 'all',
                                };
                                @endphp
                                <tr data-status="{{ $status }}">
                                    <td class="transactions-id">{{ data_get($item, 'id') }}</td>
                                    <td>{!! str_replace("\n", "<br />\n", (string) data_get($item, 'description', '')) !!}</td>
                                    <td class="transactions-points {{ $status === 'redeemed' ? 'text-rose-600' : 'text-green-600' }}">{{ Format::amount($value) }}</td>
                                    <td data-order="{{ strtotime((string) data_get($item, 'created_at', '')) }}">
                                        {{ Format::datetime(data_get($item, 'created_at'), 'M j, Y') }}
                                    </td>
                                </tr>
                                @empty
                                <tr>
                                    <td colspan="4" class="py-8 text-center text-slate-500">No transactions found.</td>
                                </tr>
                                @endforelse
                            </tbody>
                        </table>
                    </section>
                </div>
            </div>
        </div>
    </div>
</section>
@endsection

@section('js')
@parent
<script type="text/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script type="text/javascript">
    jQuery(function ($) {
        $.fn.dataTable.ext.search.push(function (settings, data, dataIndex) {
            if (settings.nTable.id !== 'transactionsTable') {
                return true;
            }

            var activeFilter = $('#transactionsTable').data('filter') || 'all';
            if (activeFilter === 'all') {
                return true;
            }

            var rowNode = settings.aoData[dataIndex] && settings.aoData[dataIndex].nTr;
            if (!rowNode) {
                return true;
            }

            return String($(rowNode).data('status') || '').toLowerCase() === activeFilter;
        });

        var transactionsTable = $('#transactionsTable').DataTable({
            paging: true,
            order: [[3, 'desc'], [0, 'desc']],
            ordering: true,
            info: false,
            searching: true,
            lengthChange: false,
            pageLength: 10,
            autoWidth: false,
            responsive: false,
            dom: 'tp'
        });

        $('#transactionsTable_filter').hide();

        var $wrapper = $('#transactionsTable_wrapper');
        var $paginate = $wrapper.find('.dataTables_paginate');
        var $footer = $('<div class="transactions-table-footer"></div>');
        var $summary = $('<div class="transactions-table-footer__summary"></div>');

        $paginate.before($summary);
        $paginate.addClass('transactions-table-footer__pagination');
        $paginate.add($summary).wrapAll($footer);

        $('#transactionsSearch').on('input', function () {
            transactionsTable.search(this.value).draw();
        });

        $('#transactionsLength').on('change', function () {
            transactionsTable.page.len(parseInt(this.value, 10)).draw();
        });

        $('.transaction-filter').on('click', function () {
            var $button = $(this);
            var filter = String($button.data('filter') || 'all').toLowerCase();

            $('.transaction-filter').removeClass('is-active');
            $button.addClass('is-active');

            $('#transactionsTable').data('filter', filter);
            transactionsTable.draw();
        });

        $('#transactionsDownload').on('click', function () {
            var rows = transactionsTable.rows({ search: 'applied' }).nodes().toArray();
            var csvRows = [
                ['ID', 'Description', '{{ trans_choice('Core::core.common.points', 2) }}', 'Date']
            ];

            rows.forEach(function (row) {
                var $cells = $(row).find('td');
                csvRows.push([
                    $cells.eq(0).text().trim(),
                    $cells.eq(1).text().trim(),
                    $cells.eq(2).text().trim(),
                    $cells.eq(3).text().trim()
                ]);
            });

            var csvContent = csvRows.map(function (columns) {
                return columns.map(function (value) {
                    return '"' + String(value).replace(/"/g, '""') + '"';
                }).join(',');
            }).join('\n');

            var blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
            var url = window.URL.createObjectURL(blob);
            var link = document.createElement('a');
            link.href = url;
            link.download = 'transactions.csv';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            window.URL.revokeObjectURL(url);
        });

        function updateTransactionsSummary() {
            var info = transactionsTable.page.info();
            $summary.text('Showing ' + info.recordsDisplay + ' of ' + info.recordsTotal + ' transactions');
        }

        $('#transactionsTable').data('filter', 'all');
        transactionsTable.on('draw', updateTransactionsSummary);
        transactionsTable.columns.adjust().draw(false);
        updateTransactionsSummary();
    });
</script>
@endsection
