@extends('layouts.app')

@section('content')
    <style type="text/css">
        .section-title a {
            font-size: 30px;
            margin: 0 10px;
        }

        .section-title a.disabled{
            color: lightgrey;
            pointer-events: none;
        }
    </style>

    <section class="page-header row">
        <h2> Analytics Detailed Report </h2>
        <ol class="breadcrumb">
            <li><a href="{{ url('') }}"> Dashboard </a></li>
            <li class="active"> Analytics Detailed Report </li>
        </ol>
    </section>


    <div class="page-content row">
        <div class="page-content-wrapper no-margin">
            <div class="sbox">
                <div class="sbox-content">
                    <form id="reportForm" action="{{ route('analytics.detailed_report') }}" method="GET">
                        <div class="row">
                            <div class="col-md-2">
                                <label for="report_type"> Report Type </label>
                                <br>
                                <select name="report_type" id="report_type" class="select2" required>
                                    @foreach(\App\Utils\AnalyticsReportTypes::getTypesWithNames() as $reportType => $reportName)
                                        <option value="{{ $reportType }}" @if(isset($selectedReportType) && $selectedReportType == $reportType) selected @endif>
                                            {{ $reportName }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label for="range"> Range </label>
                                <br>
                                <input type="text" name="range" id="range" placeholder="Select Range" required>
                            </div>
                            <div class="col-md-2">
                                <label for="country"> Country </label>
                                <br>
                                <select name="country" id="country" class="select2">
                                    <option value="">Select Country</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label for="user_type"> User Type </label>
                                <br>
                                <select name="user_type" id="user_type" class="select2">
                                    @foreach(\App\Utils\AnalyticsReportUserTypes::getTypesWithNames() as $userType => $userTypeName)
                                        <option value="{{ $userType }}" @if(isset($selectedUserType) && $selectedUserType == $userType) selected @endif>
                                            {{ $userTypeName }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>

                            <button type="submit" class="btn btn-primary m">Submit</button>
                            @if($access['is_excel'] == 1)
                            <div style="display: inline-flex">
                                <button type="button" id="exportBtn" class="btn btn-success m" onclick="exportReport()" style="display: inline-flex;">Export CSV</button>
                                <div id="exportError" class="text-danger" style="margin: auto 0; display: none">Error while Exporting Data!</div>
                            </div>
                            @endif
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    @if($reportUsersPaginator)
        <div class="page-content row">
            <div class="page-content-wrapper no-margin">
                <div class="section-title">
                    <div class="font-large-3 text-left col-md-4">Records: (Total: {{ $reportUsersPaginator->total() }})</div>
                    <div class="text-center col-md-4">
                        <a href="{{ $reportUsersPaginator->url(1) }}"
                           class="{{ ($reportUsersPaginator->currentPage() == 1) ? 'disabled' : '' }}">
                            <i class="fa fa-bold fa-angle-double-left"></i>
                        </a>

                        <a href="{{ $reportUsersPaginator->previousPageUrl() ?? '#' }}"
                           class="{{ is_null($reportUsersPaginator->previousPageUrl()) ? 'disabled' : '' }}">
                            <i class="fa fa-bold fa-angle-left"></i>
                        </a>

                        <a href="{{ $reportUsersPaginator->nextPageUrl() ?? '#' }}"
                           class="{{ is_null($reportUsersPaginator->nextPageUrl()) ? 'disabled' : '' }}">
                            <i class="fa fa-bold fa-angle-right"></i>
                        </a>

                        <a href="{{ $reportUsersPaginator->url($reportUsersPaginator->lastPage()) }}"
                           class="{{ ($reportUsersPaginator->currentPage() == $reportUsersPaginator->lastPage()) ? 'disabled' : '' }}">
                            <i class="fa fa-bold fa-angle-double-right"></i>
                        </a>
                    </div>
                    <div class="font-large-3 text-right col-md-4">Pages: {{ $reportUsersPaginator->currentPage() }} / {{ $reportUsersPaginator->lastPage() }}</div>
                </div>
                <div class="sbox">
                    <div class="sbox-content">
                        @if($reportUsersPaginator->isNotEmpty())
                            <div class="table-responsive">
                                <table class="table table-striped table-hover" id="reportTable">
                                    <thead>
                                        <tr>
                                            <th>User ID</th>
                                            <th>First Name</th>
                                            <th>Last Name</th>
                                            <th>Email</th>
                                            <th>Mobile Number</th>
                                            <th>
                                                @switch($selectedReportType)
                                                    @case(\App\Utils\AnalyticsReportTypes::ACTIVE_USERS)
                                                    @case(\App\Utils\AnalyticsReportTypes::FREQUENT_ACTIVE_USERS)
                                                    # of Sessions
                                                    @break

                                                    @case(\App\Utils\AnalyticsReportTypes::LOYAL_USERS)
                                                    @case(\App\Utils\AnalyticsReportTypes::FREQUENT_LOYAL_USERS)
                                                    # of Orders
                                                    @break

                                                    @case(\App\Utils\AnalyticsReportTypes::REGISTERED_USERS)
                                                    Is Merchant?
                                                    @break

                                                    @default
                                                    -
                                                    @break
                                                @endswitch
                                            </th>
                                        </tr>
                                    </thead>

                                    <tbody>
                                        @foreach($reportUsersPaginator->items() as $item)
                                            <tr>
                                                <td>{{ $item->user_id }}</td>
                                                <td>{{ $item->first_name }}</td>
                                                <td>{{ $item->last_name }}</td>
                                                <td>{{ $item->email }}</td>
                                                <td>{{ $item->phone_number }}</td>
                                                <td>
                                                    @switch($selectedReportType)
                                                        @case(\App\Utils\AnalyticsReportTypes::ACTIVE_USERS)
                                                        @case(\App\Utils\AnalyticsReportTypes::FREQUENT_ACTIVE_USERS)
                                                        {{ $item->sessions_count }}
                                                        @break

                                                        @case(\App\Utils\AnalyticsReportTypes::LOYAL_USERS)
                                                        @case(\App\Utils\AnalyticsReportTypes::FREQUENT_LOYAL_USERS)
                                                        {{ $item->orders_count }}
                                                        @break

                                                        @case(\App\Utils\AnalyticsReportTypes::REGISTERED_USERS)
                                                        {{ $item->is_merchant }}
                                                        @break

                                                        @default
                                                        -
                                                        @break
                                                    @endswitch
                                                </td>
                                            </tr>
                                        @endforeach
                                    </tbody>
                                </table>
                            </div>
                        @else
                            <div class="h1 text-center">No Data</div>
                        @endif
                    </div>
                </div>
            </div>
        </div>
    @endif

    <script type="text/javascript">
        moment.updateLocale('en', {
            week: {
                dow : 6 // Make Start of Week Saturday
            }
        });

        $('#range').daterangepicker({
            @if(isset($selectedStartDate) && isset($selectedEndDate))
                    startDate: '{{ $selectedStartDate }}',
                    endDate: '{{ $selectedEndDate }}',
            @endif
            showDropdowns: true,
            showCustomRangeLabel: true,
            alwaysShowCalendars: true,
            ranges: {
                'Today': [moment(), moment()],
                'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                'Last Week': [moment().subtract(1, 'week').startOf('week'), moment().subtract(1, 'week').endOf('week')],
                'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
                'Last Year': [moment().subtract(1, 'year').startOf('year'), moment().subtract(1, 'year').endOf('year')]
            },
            locale: {
                format: 'YYYY/MM/DD'
            }
        });

        $('#country').select2({
            data: <?php echo json_encode($countries) ?>,
            allowClear: true,
            placeholder: 'Select Country'
        });

        @if (isset($selectedCountry) && $selectedCountry)
            $('#country').val('{{ $selectedCountry }}');
        @endif

        function exportReport() {
            let formSelector = $('#reportForm');
            let reportType = formSelector.find('#report_type').val();
            let range = formSelector.find('#range').val();

            $.ajax({
                type: 'GET',
                url: '{{ route('analytics.detailed_report') }}',
                data: {
                    report_type: reportType,
                    range: range,
                    export: 1
                },
                beforeSend: function() {
                    $('#exportError').hide();
                    $('#exportBtn').html("<div class='loader' style=\"margin-right: 5px\"></div>Exporting...");
                },
                success: function(result, status, xhr) {
                    let reportName = '{{ $selectedReportType ?? "analytics_report"}}';
                    let disposition = xhr.getResponseHeader('content-disposition');
                    let matches = /"([^"]*)"/.exec(disposition);
                    let filename = (matches != null && matches[1] ? matches[1] : reportName + '_' + moment().unix() + '.csv');
                    let blob = new Blob([result], {
                        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                    });

                    let link = document.createElement('a');
                    link.href = window.URL.createObjectURL(blob);
                    link.download = filename;
                    link.click();
                },
                error: function(error) {
                    // console.log(error);
                    $('#exportError').show();
                    notyMessageError(error.responseJSON.message);
                },
                complete: function() {
                    $('#exportBtn').html('Export CSV');
                }
            });
        }
    </script>
@stop
