@extends('layouts.main')
@section('content')
    <!-- Main Content -->
    <div class="main-content">
        <section class="section">
            <div class="row">
                <div class="col-lg-4 col-md-12 col-sm-12">
                    <div class="card card-statistic-2">
                        <div class="card-stats">
                            <div class="card-stats-title">
                                <h4>Transaksi</h4>
                            </div>
                            <div class="card-stats-items mt-2">
                                <div class="card-stats-item">
                                    <div class="card-stats-item-count" id="countSuccess">{{ $countSuccess }}</div>
                                    <div class="card-stats-item-label">Selesai</div>
                                </div>
                                <div class="card-stats-item">
                                    <div class="card-stats-item-count" id="countCancelled">{{ $countCancelled }}</div>
                                    <div class="card-stats-item-label">Gagal</div>
                                </div>
                                <div class="card-stats-item">
                                    <div class="card-stats-item-count" id="countProcessed">{{ $countProcessed }}</div>
                                    <div class="card-stats-item-label">Diproses</div>
                                </div>
                            </div>
                            <div class="card-stats-items mt-2">
                                <div class="card-stats-item">
                                    <div class="card-stats-item-count" id="countIndicated">{{ $countIndicated }}</div>
                                    <div class="card-stats-item-label">Diterindikasi</div>
                                </div>
                                <div class="card-stats-item">
                                    <div class="card-stats-item-count" id="countWaiting">{{ $countWaiting }}</div>
                                    <div class="card-stats-item-label">Menunggu</div>
                                </div>
                            </div>
                        </div>
                        <div class="card-wrap">
                            <div class="card-header">
                                <h4>Total Transaksi</h4>
                            </div>
                            <div class="card-icon shadow-primary bg-primary">
                                <i class="fas fa-exchange-alt"></i>
                            </div>
                            <div class="card-body" id="totalTransaction">
                                {{ $totalTransaction }} Transaksi
                            </div>
                        </div>
                        <p class="mb-0 text-muted" id="rateTransaction">
                            <span
                                class="text-{{ $rateTransaction == 0 ? 'secondary text-black-50' : ($rateTransaction > 0 ? 'success' : 'danger') }} me-2"><span
                                    class="mdi {{ $rateTransaction == 0 ? 'mdi-equal' : ($rateTransaction > 0 ? 'mdi-arrow-up-bold' : 'mdi-arrow-down-bold') }}"></span>
                                {{ abs($rateTransaction) }}%</span>
                            <span class="text-nowrap">Dibandingkan sebelumnya</span>
                        </p>
                    </div>
                </div>
                <div class="col-lg-4 col-md-12 col-sm-12">
                    <div class="card card-statistic-2">
                        <div class="card-stats">
                            <div class="card-stats-title">
                                <h4>Refund</h4>
                            </div>
                            <div class="card-stats-items mt-2">
                                <div class="card-stats-item">
                                    <div class="card-stats-item-count" id="countPending">{{ $countPending }}</div>
                                    <div class="card-stats-item-label">Menunggu</div>
                                </div>
                                <div class="card-stats-item">
                                    <div class="card-stats-item-count" id="countApprove">{{ $countApprove }}</div>
                                    <div class="card-stats-item-label">Disetujui</div>
                                </div>
                                <div class="card-stats-item">
                                    <div class="card-stats-item-count" id="countDeny">{{ $countDeny }}</div>
                                    <div class="card-stats-item-label">Ditolak</div>
                                </div>
                            </div>
                        </div>
                        <div class="card-wrap">
                            <div class="card-header">
                                <h4>Total Refund</h4>
                            </div>
                            <div class="card-icon shadow-primary bg-primary">
                                <i class="fas fa-exchange-alt"></i>
                            </div>
                            <div class="card-body" id="totalRefund">
                                {{ $totalRefund }} Pengajuan
                            </div>
                        </div>
                        <p class="mb-0 text-muted" id="rateRefund">
                            <span
                                class="text-{{ $rateRefund == 0 ? 'secondary text-black-50' : ($rateRefund > 0 ? 'success' : 'danger') }} me-2"><span
                                    class="mdi {{ $rateRefund == 0 ? 'mdi-equal' : ($rateRefund > 0 ? 'mdi-arrow-up-bold' : 'mdi-arrow-down-bold') }}"></span>
                                {{ abs($rateRefund) }}%</span>
                            <span class="text-nowrap">Dibandingkan sebelumnya</span>
                        </p>
                    </div>
                </div>
                <div class="col-lg-4 col-md-12 col-sm-12">
                    <div class="card card-statistic-2">
                        <div class="card-stats">
                            <div class="card-stats-title">
                                <h4>Pengguna</h4>
                            </div>
                        </div>
                        <div class="card-chart">
                            <canvas id="users-chart" height="80"></canvas>
                        </div>
                        <div class="card-wrap">
                            <div class="card-header">
                                <h4>Total Pengguna</h4>
                            </div>
                            <div class="card-icon shadow-primary bg-primary">
                                <i class="fas fa-user"></i>
                            </div>
                            <div class="card-body" id="totalUser">
                                {{ $totalUser }} Pengguna
                            </div>
                        </div>
                        <p class="mb-0 text-muted" id="rateUser">
                            <span
                                class="text-{{ $rateUser == 0 ? 'secondary text-black-50' : ($rateUser > 0 ? 'success' : 'danger') }} me-2"><span
                                    class="mdi {{ $rateUser == 0 ? 'mdi-equal' : ($rateUser > 0 ? 'mdi-arrow-up-bold' : 'mdi-arrow-down-bold') }}"></span>
                                {{ abs($rateUser) }}%</span>
                            <span class="text-nowrap">Dibandingkan sebelumnya</span>
                        </p>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-lg-8">
                    <div class="card">
                        <div id="rateProfit">
                            <div class="alert alert-{{ $rateProfit == 0 ? 'secondary text-black-50' : ($rateProfit > 0 ? 'success' : 'error') }} alert-dismissible fade show mb-3"
                                role="alert">
                                Pendapatan {{ $rateProfit == 0 ? 'sama' : ($rateProfit > 0 ? 'meningkat' : 'menurun') }}
                                <span
                                    class="mdi {{ $rateProfit == 0 ? 'mdi-equal' : ($rateProfit > 0 ? 'mdi-arrow-up-bold' : 'mdi-arrow-down-bold') }}"></span>
                                {{ $rateProfit }}%
                            </div>
                        </div>
                        <div class="card-header">
                            <h4>Pendapatan</h4>
                        </div>
                        <div class="card-body">
                            <canvas id="myChart1" height="175"></canvas>
                        </div>
                    </div>
                </div>
                <div class="col-lg-4">
                    <div class="input-group mt-4">
                        <input type="text" name="from-to" class="form-control" id="date-range">
                        <span class="input-group-text bg-primary text-white align-items-center">
                            <i class="mdi mdi-calendar-range font-13"></i>
                        </span>
                    </div>
                    <div class="card gradient-bottom">
                        <div class="card-header">
                            <h4>Top 5 Users</h4>
                        </div>
                        <div class="card-body" id="top-5-scroll">
                            <ul class="list-unstyled list-unstyled-border" id="listTopUser">
                                @forelse ($dataTopUsers as $user)
                                    <li class="media">
                                        <img class="mr-3 rounded" width="55"
                                            src="{{ $user->foto_profile == null ? asset('storage/foto-profile/face1.jpg') : asset('storage/foto-profile/' . $user->foto_profile) }}"
                                            alt="product">
                                        <div class="media-body">
                                            <div class="float-right">
                                                <div class="font-weight-600 text-muted text-small">
                                                    {{ $user->jumlah_transaksi }} transaksi
                                                </div>
                                            </div>
                                            <div class="media-title">{{ $user->nama_lengkap }}</div>
                                            <div class="mt-1">
                                                <div class="budget-price">
                                                    <div class="budget-price-square bg-primary"
                                                        data-width="{{ (floatval($user->total_transaksi_berhasil) * 100) / (floatval($user->total_transaksi_berhasil) + floatval($user->total_refund_berhasil)) / 1.5 }}%">
                                                    </div>
                                                    <div class="budget-price-label">Rp
                                                        {{ number_format($user->total_transaksi_berhasil, 2, ',', '.') }}
                                                    </div>
                                                </div>
                                                <div class="budget-price">
                                                    <div class="budget-price-square bg-danger"
                                                        data-width="{{ (floatval($user->total_refund_berhasil) * 100) / (floatval($user->total_transaksi_berhasil) + floatval($user->total_refund_berhasil)) / 1.5 }}%">
                                                    </div>
                                                    <div class="budget-price-label">Rp
                                                        {{ number_format($user->total_refund_berhasil, 2, ',', '.') }}
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </li>
                                @empty
                                @endforelse
                            </ul>
                        </div>
                        <div class="pt-3 d-flex justify-content-center">
                            <div class="budget-price justify-content-center">
                                <div class="budget-price-square bg-primary" data-width="20"></div>
                                <div class="budget-price-label">Transaksi Selesai</div>
                            </div>
                            <div class="budget-price justify-content-center">
                                <div class="budget-price-square bg-danger" data-width="20"></div>
                                <div class="budget-price-label">Refund Selesai</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </div>
    @include('admin.transaction.modal-tracking')
@endsection
@section('tambahan-js')
    <script>
        let dataChartTransaction = {{ json_encode($dataChartTransaction) }};
        let dataChartRefund = {{ json_encode($dataChartRefund) }};
        let dataChartUser = {{ json_encode($dataChartUser) }};
        let dataLabel = {!! json_encode($dataLabel) !!};
    </script>
    <script>
        Chart.defaults.global.defaultFontFamily = 'Nunito',
            '-apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif';
        Chart.defaults.global.defaultFontColor = '#858796';

        var ctx = document.getElementById("myChart1").getContext('2d');
        var myChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: dataLabel,
                datasets: [{
                        label: 'Transaction',
                        data: dataChartTransaction,
                        borderWidth: 2,
                        backgroundColor: 'rgba(63,82,227,.8)',
                        borderWidth: 0,
                        borderColor: 'transparent',
                        pointBorderWidth: 0,
                        pointRadius: 3.5,
                        pointBackgroundColor: 'transparent',
                        pointHoverBackgroundColor: 'rgba(63,82,227,.8)',
                    },
                    {
                        label: 'Refund',
                        data: dataChartRefund,
                        borderWidth: 2,
                        backgroundColor: 'rgba(254,86,83,.7)',
                        borderWidth: 0,
                        borderColor: 'transparent',
                        pointBorderWidth: 0,
                        pointRadius: 3.5,
                        pointBackgroundColor: 'transparent',
                        pointHoverBackgroundColor: 'rgba(254,86,83,.8)',
                    }
                ]
            },
            options: {
                layout: {
                    padding: 10,
                },
                legend: {
                    display: true,
                    labels: {
                        padding: 10,
                        fontSize: 16
                    }
                },
                scales: {
                    yAxes: [{
                        gridLines: {
                            drawBorder: false,
                            color: '#f2f2f2',
                        },
                        ticks: {
                            beginAtZero: true,
                            // stepSize: 1000,
                            // callback: function(value, index, values) {
                            //     return value;
                            // },
                            fontSize: 14,
                            maxTicksLimit: 6,
                        },
                        scaleLabel: {
                            display: true,
                            labelString: 'Dalam Rupiah (Rp)',
                            fontSize: 16,
                        },
                    }],
                    xAxes: [{
                        gridLines: {
                            display: true,
                            tickMarkLength: 15,
                        },
                        ticks: {
                            display: false,
                            maxTicksLimit: 8,
                        },
                        offset: true,
                    }]
                },
            }
        });

        var users_chart = document.getElementById("users-chart").getContext('2d');

        var users_chart_bg_color = users_chart.createLinearGradient(0, 0, 0, 80);

        var myChartUser = new Chart(users_chart, {
            type: 'line',
            data: {
                labels: dataLabel,
                datasets: [{
                    label: 'Sales',
                    data: dataChartUser,
                    borderWidth: 2,
                    backgroundColor: users_chart_bg_color,
                    borderWidth: 3,
                    borderColor: 'rgba(63,82,227,1)',
                    pointBorderWidth: 0,
                    pointBorderColor: 'transparent',
                    pointRadius: 3,
                    pointBackgroundColor: 'transparent',
                    pointHoverBackgroundColor: 'rgba(63,82,227,1)',
                }]
            },
            options: {
                layout: {
                    padding: {
                        bottom: 0,
                        left: 0
                    }
                },
                legend: {
                    display: false
                },
                scales: {
                    yAxes: [{
                        gridLines: {
                            display: false,
                            drawBorder: false,
                            color: '#f2f2f2',
                        },
                        ticks: {
                            beginAtZero: true,
                            display: false,
                            maxTicksLimit: 6,
                        }
                    }],
                    xAxes: [{
                        gridLines: {
                            drawBorder: false,
                            display: true,
                        },
                        ticks: {
                            display: false,
                            maxTicksLimit: 8,
                        },
                        offset: true,
                    }]
                },
            }
        });
    </script>
    <script>
        $(document).ready(function() {
            const csrfToken = $('meta[name="csrf-token"]').attr('content');
            let searchParams = new URLSearchParams(window.location.search);
            let dateInterval = searchParams.get('from-to');
            let start = moment().subtract(29, 'days');
            let end = moment();

            if (dateInterval) {
                dateInterval = dateInterval.split(' - ');
                start = moment(dateInterval[0]);
                end = moment(dateInterval[1]);
            }

            $('#date-range').daterangepicker({
                "showDropdowns": true,
                "showWeekNumbers": true,
                "alwaysShowCalendars": true,
                startDate: start,
                endDate: end,
                locale: {
                    format: 'YYYY-MM-DD',
                    firstDay: 1,
                },
                minDate: "2023-01-01",
                maxDate: "2025-12-31",
                ranges: {
                    'Today': [moment(), moment()],
                    'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                    'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                    'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                    'This Month': [moment().startOf('month'), moment().endOf('month')],
                    'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1,
                        'month').endOf(
                        'month')],
                    'This Year': [moment().startOf('year'), moment().endOf('year')],
                    'Last Year': [moment().subtract(1, 'year').startOf('year'), moment().subtract(1, 'year')
                        .endOf(
                            'year')
                    ]
                }
            }).on('apply.daterangepicker', function(ev, picker) {
                var startDate = picker.startDate.format('YYYY-MM-DD');
                var endDate = picker.endDate.format('YYYY-MM-DD');
                console.log('Rentang tanggal dipilih:', startDate, 'sampai',
                    endDate);

                Swal.fire({
                    html: '<div class="mt-3"><lord-icon src="https://cdn.lordicon.com/etwtznjn.json" trigger="loop" colors="primary:#0ab39c,secondary:#405189" style="width:120px;height:120px"></lord-icon><div class="mt-4 pt-2 fs-15"><h4>Form Anda sedang diproses!</h4><p class="text-muted mx-4 mb-0">Mohon tunggu...</p></div></div>',
                    allowEscapeKey: false,
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });

                $.ajaxSetup({
                    headers: {
                        'X-CSRF-TOKEN': csrfToken
                    }
                });

                $.ajax({
                    url: "{{ route('admin.get-data-dashboard') }}",
                    type: 'GET',
                    data: {
                        startDate: startDate,
                        endDate: endDate
                    },
                    success: function(response) {
                        Swal.close();
                        myChart.data.datasets[0].data = response.dataChartTransaction;
                        myChart.data.datasets[1].data = response.dataChartRefund;
                        myChart.data.labels = response.dataLabel;
                        myChart.update();

                        myChartUser.data.datasets[0].data = response.dataChartUser;
                        myChartUser.data.labels = response.dataLabel;
                        myChartUser.update();

                        $('#countSuccess').html(response.countSuccess);
                        $('#countCancelled').html(response.countCancelled);
                        $('#countProcessed').html(response.countProcessed);
                        $('#countIndicated').html(response.countIndicated);
                        $('#countWaiting').html(response.countWaiting);
                        $('#totalTransaction').html(response.totalTransaction);

                        var activitiesRateTransaction = '';
                        var rateTransactionClass = response.rateTransaction == 0 ?
                            "secondary text-black-50" : (response.rateTransaction > 0 ?
                                "success" : "danger");
                        var rateTransactionClassIcon = response.rateTransaction == 0 ?
                            "mdi-equal" : (response.rateTransaction > 0 ?
                                "mdi-arrow-up-bold" : "mdi-arrow-down-bold");

                        activitiesRateTransaction = `
                        <span class="text-${rateTransactionClass} me-2"><span
                                class="mdi ${rateTransactionClassIcon}"></span>
                            ${Math.abs(response.rateTransaction)}%</span>
                        <span class="text-nowrap">Dibandingkan sebelumnya</span>
                    `;

                        $('#rateTransaction').html(activitiesRateTransaction);

                        $('#countPending').html(response.countPending);
                        $('#countApprove').html(response.countApprove);
                        $('#countDeny').html(response.countDeny);
                        $('#totalRefund').html(response.totalRefund);

                        var activitiesRateRefund = '';
                        var rateRefundClass = response.rateRefund == 0 ?
                            "secondary text-black-50" : (response.rateRefund > 0 ?
                                "success" : "danger");
                        var rateRefundClassIcon = response.rateRefund == 0 ?
                            "mdi-equal" : (response.rateRefund > 0 ?
                                "mdi-arrow-up-bold" : "mdi-arrow-down-bold");

                        activitiesRateRefund = `
                        <span class="text-${rateRefundClass} me-2"><span
                                class="mdi ${rateRefundClassIcon}"></span>
                            ${Math.abs(response.rateRefund)}%</span>
                        <span class="text-nowrap">Dibandingkan sebelumnya</span>
                    `;

                        $('#rateRefund').html(activitiesRateRefund);

                        $('#totalUser').html(response.totalUser);

                        var activitiesRateUser = '';
                        var rateUserClass = response.rateUser == 0 ?
                            "secondary text-black-50" : (response.rateUser > 0 ?
                                "success" : "danger");
                        var rateUserClassIcon = response.rateUser == 0 ?
                            "mdi-equal" : (response.rateUser > 0 ?
                                "mdi-arrow-up-bold" : "mdi-arrow-down-bold");

                        activitiesRateUser = `
                        <span class="text-${rateUserClass} me-2"><span
                                class="mdi ${rateUserClassIcon}"></span>
                            ${Math.abs(response.rateUser)}%</span>
                        <span class="text-nowrap">Dibandingkan sebelumnya</span>
                    `;

                        $('#rateUser').html(activitiesRateUser);

                        var activitiesRateProfit = '';
                        var rateProfitClass = response.rateProfit == 0 ?
                            "secondary text-black-50" : (response.rateProfit > 0 ?
                                "success" : "danger");
                        var rateProfitMention = response.rateProfit == 0 ? "sama" : (response
                            .rateProfit > 0 ? "meningkat" : "menurun");
                        var rateProfitClassIcon = response.rateProfit == 0 ?
                            "sama" : (response.rateProfit > 0 ?
                                "meningkat" : "menurun");

                        activitiesRateProfit = `
                    <div class="alert alert-${rateProfitClass} alert-dismissible fade show mb-3"
                            role="alert">
                            Pendapatan ${rateProfitMention}
                            <span
                                class="mdi ${rateProfitClassIcon}"></span>
                            ${Math.abs(response.rateProfit)}%
                        </div>
                    `;

                        $('#rateProfit').html(activitiesRateProfit);

                        // ListTopUser
                        var activitiesHtml = '';

                        response.dataTopUser.forEach(user => {
                            let fotoProfile = user.foto_profile == null ?
                                "{{ asset('storage/foto-profile/face1.jpg') }}" :
                                "{{ asset('storage/foto-profile') }}/" + user
                                .foto_profile;
                            let totalTransaction = new Intl.NumberFormat('id-ID', {
                                style: 'currency',
                                currency: 'IDR'
                            }).format(user.total_transaksi_berhasil);
                            let totalRefund = new Intl.NumberFormat('id-ID', {
                                style: 'currency',
                                currency: 'IDR'
                            }).format(user.total_refund_berhasil);
                            let transactionWidth = ((parseFloat(user
                                    .total_transaksi_berhasil) *
                                100) / (parseFloat(user
                                    .total_transaksi_berhasil) +
                                parseFloat(user.total_refund_berhasil))) / 1.5;
                            let refundWidth = ((parseFloat(user.total_refund_berhasil) *
                                100) / (
                                parseFloat(user.total_transaksi_berhasil) +
                                parseFloat(user.total_refund_berhasil))) / 1.5;
                            activitiesHtml += `
                            <li class="media">
                                <img class="mr-3 rounded" width="55"
                                    src="${fotoProfile}"
                                    alt="product">
                                <div class="media-body">
                                    <div class="float-right">
                                        <div class="font-weight-600 text-muted text-small">
                                            ${user.jumlah_transaksi} transaksi
                                        </div>
                                    </div>
                                    <div class="media-title">${user.nama_lengkap}</div>
                                    <div class="mt-1">
                                        <div class="budget-price">
                                            <div class="budget-price-square bg-primary"
                                                data-width="${transactionWidth}%" style="width:${transactionWidth}%">
                                            </div>
                                            <div class="budget-price-label">
                                                ${totalTransaction}
                                            </div>
                                        </div>
                                        <div class="budget-price">
                                            <div class="budget-price-square bg-danger"
                                                data-width="${refundWidth}%" style="width:${refundWidth}%">
                                            </div>
                                            <div class="budget-price-label">
                                                ${totalRefund}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </li>
                        `;
                        });

                        $('#listTopUser').html(activitiesHtml);
                    },
                    error: function(error) {
                        Swal.close();
                        console.log(error);
                    }
                });
            });
        });
    </script>
@endsection