@extends('admin.layouts.app')

@section('panel')
    <div class="row gy-4">

        <div class="col-xxl-3 col-sm-6">

            <x-widget
                      style="6"
                      link="{{ route('admin.users.all') }}"
                      icon="las la-users"
                      title="Total Users"
                      value="{{ $widget['total_users'] }}"
                      bg="primary" />
        </div><!-- dashboard-w1 end -->
        <div class="col-xxl-3 col-sm-6">
            <x-widget
                      style="6"
                      link="{{ route('admin.users.active') }}"
                      icon="las la-user-check"
                      title="Active Users"
                      value="{{ $widget['verified_users'] }}"
                      bg="success" />
        </div><!-- dashboard-w1 end -->
        <div class="col-xxl-3 col-sm-6">
            <x-widget
                      style="6"
                      link="{{ route('admin.users.email.unverified') }}"
                      icon="lar la-envelope"
                      title="Email Unverified Users"
                      value="{{ $widget['email_unverified_users'] }}"
                      bg="danger" />
        </div><!-- dashboard-w1 end -->
        <div class="col-xxl-3 col-sm-6">
            <x-widget
                      style="6"
                      link="{{ route('admin.users.mobile.unverified') }}"
                      icon="las la-comment-slash"
                      title="Mobile Unverified Users"
                      value="{{ $widget['mobile_unverified_users'] }}"
                      bg="warning" />
        </div><!-- dashboard-w1 end -->
    </div><!-- row end-->

    <div class="row mt-2 gy-4">
        <div class="col-xxl-6">
            <div class="card box-shadow3 h-100">
                <div class="card-body">
                    <h5 class="card-title">@lang('Payments')</h5>
                    <div class="widget-card-wrapper">
                        <div class="widget-card bg--success">
                            <a href="{{ route('admin.deposit.list') }}" class="widget-card-link"></a>
                            <div class="widget-card-left">
                                <div class="widget-card-icon">
                                    <i class="fas fa-hand-holding-usd"></i>
                                </div>
                                <div class="widget-card-content">
                                    <h6 class="widget-card-amount">{{ showAmount($deposit['total_deposit_amount']) }}</h6>
                                    <p class="widget-card-title">@lang('Total Payment')</p>
                                </div>
                            </div>
                            <span class="widget-card-arrow">
                                <i class="las la-angle-right"></i>
                            </span>
                        </div>

                        <div class="widget-card bg--warning">
                            <a href="{{ route('admin.deposit.pending') }}" class="widget-card-link"></a>
                            <div class="widget-card-left">
                                <div class="widget-card-icon">
                                    <i class="fas fa-spinner"></i>
                                </div>
                                <div class="widget-card-content">
                                    <h6 class="widget-card-amount">{{ $deposit['total_deposit_pending'] }}</h6>
                                    <p class="widget-card-title">@lang('Pending Payments')</p>
                                </div>
                            </div>
                            <span class="widget-card-arrow">
                                <i class="las la-angle-right"></i>
                            </span>
                        </div>

                        <div class="widget-card bg--danger">
                            <a href="{{ route('admin.deposit.rejected') }}" class="widget-card-link"></a>
                            <div class="widget-card-left">
                                <div class="widget-card-icon">
                                    <i class="fas fa-ban"></i>
                                </div>
                                <div class="widget-card-content">
                                    <h6 class="widget-card-amount">{{ $deposit['total_deposit_rejected'] }}</h6>
                                    <p class="widget-card-title">@lang('Rejected Payments')</p>
                                </div>
                            </div>
                            <span class="widget-card-arrow">
                                <i class="las la-angle-right"></i>
                            </span>
                        </div>

                        <div class="widget-card bg--primary">
                            <a href="{{ route('admin.deposit.list') }}" class="widget-card-link"></a>
                            <div class="widget-card-left">
                                <div class="widget-card-icon">
                                    <i class="fas fa-percentage"></i>
                                </div>
                                <div class="widget-card-content">
                                    <h6 class="widget-card-amount">{{ showAmount($deposit['total_deposit_charge']) }}</h6>
                                    <p class="widget-card-title">@lang('Payment Charge')</p>
                                </div>
                            </div>
                            <span class="widget-card-arrow">
                                <i class="las la-angle-right"></i>
                            </span>
                        </div>

                    </div>
                </div>
            </div>
        </div>
        <div class="col-xxl-6">
            <div class="card box-shadow3 h-100">
                <div class="card-body">
                    <h5 class="card-title">@lang('Creative Controls')</h5>
                    <div class="widget-card-wrapper">
                        <div class="widget-card bg--success">
                            <a href="{{ route('admin.plan.index') }}" class="widget-card-link"></a>
                            <div class="widget-card-left">
                                <div class="widget-card-icon">
                                    <i class="fas fa-list-alt"></i>
                                </div>
                                <div class="widget-card-content">
                                    <h6 class="widget-card-amount">{{ $widget['total_plan'] }}</h6>
                                    <p class="widget-card-title">@lang('Total Plan')</p>
                                </div>
                            </div>
                            <span class="widget-card-arrow">
                                <i class="las la-angle-right"></i>
                            </span>
                        </div>

                        <div class="widget-card bg--warning">
                            <a href="{{ route('admin.ticket.pending') }}" class="widget-card-link"></a>
                            <div class="widget-card-left">
                                <div class="widget-card-icon">
                                    <i class="fas fa-ticket-alt"></i>
                                </div>
                                <div class="widget-card-content">
                                    <h6 class="widget-card-amount">{{ $widget['pending_tickets'] }}</h6>
                                    <p class="widget-card-title">@lang('Pending Tickets')</p>
                                </div>
                            </div>
                            <span class="widget-card-arrow">
                                <i class="las la-angle-right"></i>
                            </span>
                        </div>

                        <div class="widget-card bg--primary">
                            <a href="{{ route('admin.notifications') }}" class="widget-card-link"></a>
                            <div class="widget-card-left">
                                <div class="widget-card-icon">
                                    <i class="fas fa-bell"></i>
                                </div>
                                <div class="widget-card-content">
                                    <h6 class="widget-card-amount">{{ $widget['pending_notification'] }}</h6>
                                    <p class="widget-card-title">@lang('Pending Notification')</p>
                                </div>
                            </div>
                            <span class="widget-card-arrow">
                                <i class="las la-angle-right"></i>
                            </span>
                        </div>

                        <div class="widget-card bg--danger">
                            <a href="{{ route('admin.users.banned') }}" class="widget-card-link"></a>
                            <div class="widget-card-left">
                                <div class="widget-card-icon">
                                    <i class="fas fa-ban"></i>
                                </div>
                                <div class="widget-card-content">
                                    <h6 class="widget-card-amount">{{ $widget['banned_user'] }}</h6>
                                    <p class="widget-card-title">@lang('Banned User')</p>
                                </div>
                            </div>
                            <span class="widget-card-arrow">
                                <i class="las la-angle-right"></i>
                            </span>
                        </div>

                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row mb-none-30 mt-30">
        <div class="col-xl-6 mb-30">
            <div class="card">
                <div class="card-body">
                    <div class="d-flex flex-wrap justify-content-between">
                        <h5 class="card-title">@lang('Payment Report')</h5>

                        <div id="dwDatePicker" class="border p-1 cursor-pointer rounded">
                            <i class="la la-calendar"></i>&nbsp;
                            <span></span> <i class="la la-caret-down"></i>
                        </div>
                    </div>
                    <div id="dwChartArea"> </div>
                </div>
            </div>
        </div>
        <div class="col-xl-6 mb-30">
            <div class="card">
                <div class="card-body">
                    <div class="d-flex flex-wrap justify-content-between">
                        <h5 class="card-title">@lang('Subscription Report')</h5>
                    </div>
                    <div id="paymentsChart"></div>
                </div>
            </div>
        </div>


        <div class="row mb-none-30 mt-5">
            <div class="col-xl-4 col-lg-6 mb-30">
                <div class="card overflow-hidden">
                    <div class="card-body">
                        <h5 class="card-title">@lang('Login By Browser') (@lang('Last 30 days'))</h5>
                        <canvas id="userBrowserChart"></canvas>
                    </div>
                </div>
            </div>
            <div class="col-xl-4 col-lg-6 mb-30">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">@lang('Login By OS') (@lang('Last 30 days'))</h5>
                        <canvas id="userOsChart"></canvas>
                    </div>
                </div>
            </div>
            <div class="col-xl-4 col-lg-6 mb-30">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">@lang('Login By Country') (@lang('Last 30 days'))</h5>
                        <canvas id="userCountryChart"></canvas>
                    </div>
                </div>
            </div>
        </div>



        @include('admin.partials.cron_modal')
    @endsection
    @push('breadcrumb-plugins')
        <button class="btn btn-outline--primary btn-sm" data-bs-toggle="modal" data-bs-target="#cronModal">
            <i class="las la-server"></i>@lang('Cron Setup')
        </button>
    @endpush


    @push('script-lib')
        <script src="{{ asset('assets/admin/js/vendor/apexcharts.min.js') }}"></script>
        <script src="{{ asset('assets/admin/js/vendor/chart.js.2.8.0.js') }}"></script>
        <script src="{{ asset('assets/admin/js/moment.min.js') }}"></script>
        <script src="{{ asset('assets/admin/js/daterangepicker.min.js') }}"></script>
        <script src="{{ asset('assets/admin/js/charts.js') }}"></script>
    @endpush

    @push('style-lib')
        <link rel="stylesheet" type="text/css" href="{{ asset('assets/admin/css/daterangepicker.css') }}">
    @endpush

    @push('script')
        <script>
            "use strict";

            const start = moment().subtract(14, 'days');
            const end = moment();

            const dateRangeOptions = {
                startDate: start,
                endDate: end,
                ranges: {
                    'Today': [moment(), moment()],
                    'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                    'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                    'Last 15 Days': [moment().subtract(14, 'days'), moment()],
                    'Last 30 Days': [moment().subtract(30, 'days'), moment()],
                    'This Month': [moment().startOf('month'), moment().endOf('month')],
                    'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
                    'Last 6 Months': [moment().subtract(6, 'months').startOf('month'), moment().endOf('month')],
                    'This Year': [moment().startOf('year'), moment().endOf('year')],
                },
                maxDate: moment()
            }

            const changeDatePickerText = (element, startDate, endDate) => {
                $(element).html(startDate.format('MMMM D, YYYY') + ' - ' + endDate.format('MMMM D, YYYY'));
            }

            let dwChart = barChart(
                document.querySelector("#dwChartArea"),
                `{{ __(gs('cur_text')) }}`,
                [{
                    name: 'Payments',
                    data: []
                }],
                [],
            );


            const depositWithdrawChart = (startDate, endDate) => {

                const data = {
                    start_date: startDate.format('YYYY-MM-DD'),
                    end_date: endDate.format('YYYY-MM-DD')
                }

                const url = `{{ route('admin.chart.deposit.withdraw') }}`;

                $.get(url, data,
                    function(data, status) {
                        if (status == 'success') {
                            dwChart.updateSeries(data.data);
                            dwChart.updateOptions({
                                xaxis: {
                                    categories: data.created_on,
                                }
                            });
                        }
                    }
                );
            }


            $('#dwDatePicker').daterangepicker(dateRangeOptions, (start, end) => changeDatePickerText('#dwDatePicker span', start, end));
            $('#trxDatePicker').daterangepicker(dateRangeOptions, (start, end) => changeDatePickerText('#trxDatePicker span', start, end));

            changeDatePickerText('#dwDatePicker span', start, end);
            changeDatePickerText('#trxDatePicker span', start, end);

            depositWithdrawChart(start, end);

            $('#dwDatePicker').on('apply.daterangepicker', (event, picker) => depositWithdrawChart(picker.startDate, picker.endDate));

            piChart(
                document.getElementById('userBrowserChart'),
                JSON.parse(`@php echo json_encode($chart['user_browser_counter']->keys()); @endphp`),
                JSON.parse(`@php echo json_encode($chart['user_browser_counter']->flatten()); @endphp`)
            );

            piChart(
                document.getElementById('userOsChart'),
                JSON.parse(`@php echo json_encode($chart['user_os_counter']->keys()); @endphp`),
                JSON.parse(`@php echo json_encode($chart['user_os_counter']->flatten()); @endphp`)
            );

            piChart(
                document.getElementById('userCountryChart'),
                JSON.parse(`@php echo json_encode($chart['user_country_counter']->keys()); @endphp`),
                JSON.parse(`@php echo json_encode($chart['user_country_counter']->flatten()); @endphp`)
            );


            const chartData = JSON.parse(`@php echo json_encode($chartData) @endphp`);

            const series = chartData.map(item => Number(item.total_subscribed) || 0);
            const labels = chartData.map(item => item.plan || 'Unknown');
            const tooltipData = chartData;
            const colorList = ['#1ab7ea', '#0084ff', '#39539E', '#0077B5', '#FF6B6B', '#4ECDC4', '#45B7D1'];

            var options = {
                series: series,
                chart: {
                    height: 390,
                    type: 'radialBar',
                },
                plotOptions: {
                    radialBar: {
                        offsetY: 0,
                        startAngle: 0,
                        endAngle: 270,
                        hollow: {
                            margin: 5,
                            size: '30%',
                            background: 'transparent',
                        },
                        dataLabels: {
                            name: {
                                show: true,
                            },
                            value: {
                                show: true,
                                formatter: function(val) {
                                    return Math.round(val);
                                }
                            }
                        },
                    }
                },
                colors: colorList.slice(0, series.length),
                labels: labels,
                legend: {
                    show: true,
                    floating: true,
                    fontSize: '14px',
                    position: 'left',
                    offsetX: 50,
                    offsetY: 10,
                    labels: {
                        useSeriesColors: true,
                    },
                    markers: {
                        size: 0
                    },
                    formatter: function(seriesName, opts) {
                        return seriesName + ":  " + opts.w.globals.series[opts.seriesIndex];
                    },
                    itemMargin: {
                        vertical: 3
                    }
                },
                tooltip: {
                    enabled: true,
                    custom: function({
                        series,
                        seriesIndex,
                        dataPointIndex,
                        w
                    }) {
                        const plan = tooltipData[seriesIndex];
                        if (!plan) return '';

                        return `<div class="arrow_box p-3">
                        <span><strong>${plan.plan}</strong></span><br/>
                        <span>Subscribers: ${series[seriesIndex]}</span><br/>
                        <span>Paid: $${plan.total_paid || 0}</span>
                    </div>`;
                    }
                },
                responsive: [{
                    breakpoint: 480,
                    options: {
                        legend: {
                            show: false
                        },
                        chart: {
                            height: 300
                        }
                    }
                }]
            };

            const chartElement = document.querySelector("#paymentsChart");
            if (chartElement) {
                var chart = new ApexCharts(chartElement, options);
                chart.render().catch(err => {
                    console.error('Chart rendering failed:', err);
                });
            } else {
                console.error('Chart container element #paymentsChart not found');
            }
        </script>
    @endpush
    @push('style')
        <style>
            .apexcharts-menu {
                min-width: 120px !important;
            }
        </style>
    @endpush
