@extends('frontend.layouts.app')

@section('content')

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" type="text/css">

    <div id="showM">
        <div class="overlap g8mmenu-close"></div>
        @include('frontend.partials.mobile.header')
        @include('frontend.partials.mobile.sidebar-menu')

        <div class="content">
            <div class="funds">
                <div class="funds__header">
                    <div class="funds__header-left">
                        <span>Saldo</span>
                        <div class="header-balance" style="display: flex; align-items: center; gap: 8px;">
                            <strong class="g8-bal-total">IDR {{ number_format(Auth::user()->balance ?? 0, 0, ',', '.') }}</strong>
                            <a href="javascript:void(0);" class="btn-refresh-balance" style="color: #f99c2a; cursor: pointer; font-size: 14px;" title="Refresh Saldo">
                                <i class="fas fa-sync-alt"></i>
                            </a>
                        </div>
                    </div>
                    <div class="funds__header-right"></div>
                </div>
                <div class="funds__rebate-detail funds__container">
                    <ul>
                        <li class="active"><a href="{{ route('secure.history') }}">History Transaksi</a></li>
                        <li><a href="/secure/admin/history-bet">History Bet</a></li>
                    </ul>
                    
                    <div class="rebate-item">
                        
                        <form class="filterForm" action="{{ url()->current() }}" method="GET">
                            <div class="drp-wrap mob" style="flex-wrap: wrap; gap: 10px;">
                                <div class="drp daterange-btn" style="flex: 1; min-width: 200px;">
                                    <i class="fa fa-calendar"></i>
                                    <span class="daterange-text" style="color: #fff;">{{ date('d-m-Y', strtotime($startDate)) }} &mdash; {{ date('d-m-Y', strtotime($endDate)) }}</span>
                                    <i class="fa fa-caret-down"></i>
                                    <input type="hidden" name="start_date" class="start_date" value="{{ $startDate }}">
                                    <input type="hidden" name="end_date" class="end_date" value="{{ $endDate }}">
                                </div>
                                <select name="tipe" style="background: #111; color: #fff; border: 1px solid #333; padding: 5px; height: 32px; border-radius: 3px;">
                                    <option value="0" {{ $tipe == '0' ? 'selected' : '' }}>Semua Tipe</option>
                                    <option value="1" {{ $tipe == '1' ? 'selected' : '' }}>Deposit</option>
                                    <option value="2" {{ $tipe == '2' ? 'selected' : '' }}>Withdraw</option>
                                </select>
                                <button type="submit" class="button button-sm button--yellow btn-submit-filter" style="width: 100%;">Submit</button>
                            </div>
                        </form>

                        <div id="ajax-container-m">
                            <div class="rebate-item__detail reqMob">
                                @forelse($history as $h)
                                    <div class="rebate-item__detail-box">
                                        <div class="box-header adt2" style="cursor: pointer;">
                                            <span style="flex: 1;">{{ date('d/m/Y H:i', strtotime($h->created_at)) }} - {{ $h->transaksi }}</span>
                                            <div class="chevron arrow"><i class="fas fa-chevron-down"></i></div>
                                        </div>
                                        <div class="box-content" style="display: none;">
                                            <ul>
                                                <li><span>Trans. ID</span>&nbsp;<span>{{ $h->trx_id }}</span></li>
                                                <li><span>Amount (IDR)</span>&nbsp;<span>{{ number_format($h->total, 0, ',', '.') }}</span></li>
                                            </ul>
                                            
                                            @php
                                                $statusColor = '#fbb11a'; // Pending (Kuning)
                                                if(strtolower($h->status) == 'sukses' || strtolower($h->status) == 'success') $statusColor = '#28a745';
                                                if(strtolower($h->status) == 'gagal' || strtolower($h->status) == 'reject') $statusColor = '#dc3545';
                                            @endphp

                                            <div class="box-content__cta" style="color: {{ $statusColor }}; font-weight: bold; text-align: center; padding-top: 10px;">
                                                {{ $h->status }} : {{ $h->keterangan ?? '-' }}
                                            </div>
                                        </div>
                                    </div>
                                @empty
                                    <div style="text-align: center; padding: 20px; color: #888;">Tidak ada data transaksi.</div>
                                @endforelse

                                @if($history instanceof \Illuminate\Contracts\Pagination\Paginator && $history->hasPages())
                                    <div class="pagination-wrapper" style="margin-top: 15px; display: flex; justify-content: center;">
                                        {{ $history->links('pagination::bootstrap-4') }}
                                    </div>
                                @endif
                            </div>
                        </div>

                    </div>
                </div>
            </div>
        </div>
        @include('frontend.partials.mobile.bottom-nav')
    </div>
    <div id="showD">
        @include('frontend.partials.desktop.header')

        <section class="profile">
            <div class="wrapper">
                <div class="profile__nav">
                    <ul>
                        <li><a href="/secure/admin/profile"><i class="far fa-user"></i><span>Profile</span></a></li>
                        <li><a href="/secure/admin/deposit"><i class="fas fa-wallet"></i><span>Deposit</span></a></li>
                        <li><a href="/secure/admin/withdrawal"><i class="fas fa-money-bill"></i><span>Withdrawal</span></a></li>
                        <li><a href="/secure/admin/bonus"><i class="fas fa-dollar-sign"></i><span>Bonus</span></a></li>
                        <li class="active"><a href="/secure/admin/history"><i class="fas fa-history"></i><span>History</span></a></li>
                        <li><a href="/secure/admin/referral"><i class="fas fa-users"></i><span>Referral</span></a></li>
                        <li>
                            <a href="/secure/admin/messages"><i class="fas fa-envelope"></i><span>Messages</span></a>
                            <div class="notif-wrapper hide"><div class="notif-info notanim"></div></div>
                        </li>
                    </ul>
                </div>
            </div>
        </section>

        <div class="wrapper">
            <section class="balance">
                <div class="g8-bal-top"><p>Saldo</p>
                    <div style="display: flex; align-items: center; justify-content: center; gap: 8px;">
                        <span class="g8-bal-total" style="color: #0b1a4a; font-weight: 800;">IDR {{ number_format(Auth::user()->balance ?? 0, 0, ',', '.') }}</span>
                        <a href="javascript:void(0);" class="btn-refresh-balance" style="color: #0b1a4a; cursor: pointer; font-size: 18px;" title="Refresh Saldo">
                            <i class="fas fa-sync-alt"></i>
                        </a>
                    </div>
                </div>
            </section>

            <section class="funds">
                <div class="funds__container">
                    <ul>
                        <li class="active"><a href="{{ route('secure.history') }}">History Transaksi</a></li>
                        <li><a href="/secure/admin/history-bet">History Bet</a></li>
                    </ul>
                    
                    <div class="funds__rebate">
                        <section class="funds__rebate-table">
                            
                            <form class="filterForm" action="{{ url()->current() }}" method="GET">
                                <div class="drp-wrap" style="display: flex; align-items: center; gap: 10px; margin-bottom: 15px;">
                                    <div class="drp daterange-btn">
                                        <i class="fa fa-calendar"></i>
                                        <span class="daterange-text">{{ date('d-m-Y', strtotime($startDate)) }} &mdash; {{ date('d-m-Y', strtotime($endDate)) }}</span>
                                        <i class="fa fa-caret-down"></i>
                                        <input type="hidden" name="start_date" class="start_date" value="{{ $startDate }}">
                                        <input type="hidden" name="end_date" class="end_date" value="{{ $endDate }}">
                                    </div>
                                    <select name="tipe" style="padding: 6px; border: 1px solid #ccc; border-radius: 3px; height: 34px;">
                                        <option value="0" {{ $tipe == '0' ? 'selected' : '' }}>Semua Tipe</option>
                                        <option value="1" {{ $tipe == '1' ? 'selected' : '' }}>Deposit</option>
                                        <option value="2" {{ $tipe == '2' ? 'selected' : '' }}>Withdraw</option>
                                    </select>
                                    <button type="submit" class="button button-sm button--yellow btn-submit-filter" style="margin: 0;">Submit</button>
                                </div>
                            </form>

                            <div id="ajax-container-d">
                                <table class="table table-condensed table-styled req-table" cellpadding="0" cellspacing="0" style="width: 100%;">
                                    <thead style="background-color: #545454; color: #fff;">
                                        <tr>
                                            <th>Date & Time</th>
                                            <th>Trans. ID</th>
                                            <th>Type</th>
                                            <th>Amount (IDR)</th>
                                            <th>Status</th>
                                            <th>Note</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @forelse($history as $h)
                                            @php
                                                $statusColor = '#fbb11a'; 
                                                if(strtolower($h->status) == 'sukses' || strtolower($h->status) == 'success') $statusColor = '#28a745';
                                                if(strtolower($h->status) == 'gagal' || strtolower($h->status) == 'reject') $statusColor = '#dc3545';
                                            @endphp
                                            <tr>
                                                <td>{{ date('Y-m-d H:i:s', strtotime($h->created_at)) }}</td>
                                                <td>{{ $h->trx_id }}</td>
                                                <td>{{ $h->transaksi }}</td>
                                                <td>{{ number_format($h->total, 0, ',', '.') }}</td>
                                                <td style="color: {{ $statusColor }}; font-weight: bold;">{{ $h->status }}</td>
                                                <td>{{ $h->keterangan ?? '-' }}</td>
                                            </tr>
                                        @empty
                                            <tr>
                                                <td colspan="6" style="text-align: center; padding: 20px; color: #888;">Tidak ada data transaksi.</td>
                                            </tr>
                                        @endforelse
                                    </tbody>
                                </table>

                                @if($history instanceof \Illuminate\Contracts\Pagination\Paginator && $history->hasPages())
                                    <div class="pagination-wrapper" style="margin-top: 15px; display: flex; justify-content: flex-end;">
                                        {{ $history->links('pagination::bootstrap-4') }}
                                    </div>
                                @endif
                            </div>

                        </section>
                    </div>
                </div>
            </section>
        </div>
        @include('frontend.partials.desktop.footer')
    </div>

@endsection

@push('scripts')
<script src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>

<script type="text/javascript">
// Gunakan loadMeIfReady agar sinkron dengan script bawaan template
window.loadMeIfReady = function() {

    // 1. REFRESH SALDO AJAX
    $('.btn-refresh-balance').on('click', function(e) {
        e.preventDefault();
        let $icons = $('.btn-refresh-balance i'); 
        let $balanceSpans = $('.g8-bal-total');

        $icons.addClass('fa-spin');
        
        $.ajax({
            url: "{{ route('api.balance') }}", 
            type: "GET",
            success: function(response) {
                $icons.removeClass('fa-spin');
                if (response && response.d) {
                    $balanceSpans.html(response.d);
                }
            },
            error: function() {
                $icons.removeClass('fa-spin');
            }
        });
    });

    // 2. OBAT BUG MOBILE: CEGAH TEMPLATE MENUTUP PAKSA DROPDOWN / KALENDER
    // Tambahkan 'touchstart' agar HP tidak bocor event-nya
    // Tambahkan '.daterangepicker' agar kalender yang melayang tidak ditutup paksa
    $(document).on('click touchstart', '.drp, select[name="tipe"], select[name="game_type"], .daterangepicker', function(e) {
        e.stopPropagation();
    });

    $(document).off('click', '.box-header.adt2').on('click', '.box-header.adt2', function(e) {
        e.preventDefault();
        
        // JURUS PAMUNGKAS: Blokir total script bawaan template agar tidak ikut mengeksekusi klik ini!
        e.stopImmediatePropagation(); 

        let $content = $(this).next('.box-content');
        let $icon = $(this).find('.fa-chevron-down, .fa-chevron-up');
        
        // Mencegah animasi menumpuk kalau diklik berulang-ulang dengan cepat
        if ($content.is(':animated')) return; 

        // Toggle animasi dengan durasi yang lebih smooth
        $content.slideToggle(250);
        
        if($icon.hasClass('fa-chevron-down')) {
            $icon.removeClass('fa-chevron-down').addClass('fa-chevron-up');
        } else {
            $icon.removeClass('fa-chevron-up').addClass('fa-chevron-down');
        }
    });

    // 4. INISIALISASI DATERANGEPICKER
    function initDaterange() {
        $('.daterange-btn').daterangepicker({
            ranges: {
               'Hari ini': [moment(), moment()],
               'Kemarin': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
               '7 Hari Terakhir': [moment().subtract(6, 'days'), moment()],
               'Bulan Ini': [moment().startOf('month'), moment().endOf('month')],
               'Bulan Lalu': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
            },
            locale: { format: 'DD-MM-YYYY' }
        }, function(start, end, label) {
            let $parent = this.element.closest('form');
            $parent.find('.daterange-text').html(start.format('DD-MM-YYYY') + ' &mdash; ' + end.format('DD-MM-YYYY'));
            $parent.find('.start_date').val(start.format('YYYY-MM-DD'));
            $parent.find('.end_date').val(end.format('YYYY-MM-DD'));
        });
    }

    // Jalankan init kalender
    initDaterange();

    // 5. AJAX FILTER & PAGINASI (Anti Reload)
    $(document).off('submit', '.filterForm').on('submit', '.filterForm', fetchHistoryData);
    $(document).off('click', '.pagination-wrapper a').on('click', '.pagination-wrapper a', function(e) {
        e.preventDefault();
        let url = $(this).attr('href');
        fetchHistoryData(e, url);
    });

    function fetchHistoryData(e, overrideUrl = null) {
        e.preventDefault();
        
        let isForm = $(e.target).is('form');
        let $form = isForm ? $(e.target) : $(e.target).closest('.funds__container').find('.filterForm');
        let $btn = $form.find('.btn-submit-filter');
        let originalText = $btn.html() || 'Submit';
        
        $btn.html('<i class="fa fa-spinner fa-spin"></i>').prop('disabled', true);

        let targetUrl = overrideUrl ? overrideUrl : $form.attr('action') + '?' + $form.serialize();

        $.ajax({
            url: targetUrl,
            type: 'GET',
            success: function(response) {
                let parser = new DOMParser();
                let doc = parser.parseFromString(response, "text/html");

                // Update Tabel Desktop & Mobile
                $('#ajax-container-d').html($(doc).find('#ajax-container-d').html());
                $('#ajax-container-m').html($(doc).find('#ajax-container-m').html());

                $btn.html(originalText).prop('disabled', false);

                // RE-INIT Kalender setelah DOM direplace oleh AJAX
                initDaterange();
            },
            error: function() {
                if(typeof jAlert !== 'undefined') {
                    jAlert('Gagal memuat data. Silakan coba lagi.', 'Error');
                } else {
                    alert('Gagal memuat data');
                }
                $btn.html(originalText).prop('disabled', false);
            }
        });
    }

}; // END OF loadMeIfReady
</script>
@endpush