@extends('layouts.admin')
@section('content')

<!-- start page title -->
<!-- start page title -->
<div class="row">
    <div class="col-12">
        <div class="page-title-box d-sm-flex align-items-center justify-content-between bg-galaxy-transparent">
            <h4 class="mb-sm-0">Ads Statistics</h4>

            <div class="page-title-right">
                <ol class="breadcrumb m-0">
                    <li class="breadcrumb-item"><a href="javascript: void(0);">Reports</a></li>
                    <li class="breadcrumb-item active">Ads Statistics</li>
                </ol>
            </div>
        </div>
    </div>
</div>
<!-- end page title -->

<div class="row">
    <div class="col-lg-12">
        <div class="card" id="orderList">
            <div class="card-header border-0">
                <div class="row align-items-center gy-3">
                    <div class="col-sm">
                        <h5 class="card-title mb-0">Ads Statistics</h5>
                    </div>
                    <div class="col-sm-auto">
                        <div class="d-flex gap-1 flex-wrap">
                            <button type="button" class="btn btn-info" id="export-excel"><i class="ri-file-download-line align-bottom me-1"></i> Export to Excel</button>
                            <button type="button" class="btn btn-info" id="export-pdf"><i class="ri-file-download-line align-bottom me-1"></i> Export to PDF</button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="card-body border border-dashed border-end-0 border-start-0">
                <form method="GET" action="{{ route('admin.reports.adstatistics.list') }}" id="filterForm">
                    <div class="row g-3 align-items-end">
                        <div class="col-lg-4 mb-3">
                            <label for="userId" class="form-label">Customer Name</label>
                            <select name="user_id[]" class="form-select customer-dropdown-field" multiple>

                            </select>
                        </div>
                        <div class="col-lg-4 mb-3">
                            <label for="userEmail" class="form-label">Email</label>
                            <select name="user_email_id" id="userEmail" class="form-select customer-email-field">

                            </select>
                        </div>
                        <div class="col-lg-4 mb-3">
                            <label for="category" class="form-label">Category</label>
                            <select class="form-select js-example-basic-single" id="category" name="category_id">
                                <option value="all">All Sub Categories</option>
                                @foreach($categories as $category)
                                    <option value="{{ $category->id }}">
                                        {{ $category->name_with_parent_category_name }}
                                    </option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-lg-4 mb-3">
                            <label for="city_id" class="form-label">City</label>
                            <select class="form-select js-example-basic-single" id="city_id" name="city_id">
                                <option value="all">All Cities</option>
                                @foreach($cities as $city)
                                    <option value="{{ $city->id }}">
                                        {{ $city->name }}
                                    </option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-lg-4 mb-3">
                            <label for="idStatus">Status</label>
                            <select class="form-select" data-choices data-choices-search-false name="status" id="idStatus">
                                <option value="all" selected>All status</option>
                                <option value="Draft">Draft</option>
                                <option value="Payment Pending">Payment Pending</option>
                                <option value="Rejected">Rejected</option>
                                <option value="Expired">Expired</option>
                                <option value="Live">Live</option>
                                <option value="Under Review">Under Review</option>
                            </select>
                        </div>
                        <div class="col-lg-4 mb-3">
                            <label for="start_date">Starts From</label>
                            <input type="date" name="start_date" id="start_date" class="form-control" max="{{ $today }}" placeholder="Start Date From">

                        </div>
                        <div class="col-lg-4 mb-3">

                            <label for="end_date">End Date</label>
                            <input type="date" id="end_date" name="end_date" class="form-control" placeholder="End Date" max="{{ $today }}">

                        </div>
                        <div class="col-lg-4 mb-3">
                            <button type="submit" class="btn btn-primary">Filter</button>
                            <button type="submit" class="btn btn-soft-dark" id="clearButton">Clear</button>
                        </div>
                    </div>
                    <!--end row-->
                </form>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table id="UserReportTable" class="table table-bordered nowrap align-middle" style="width: 100%;">
                        <thead class="">
                            <tr class="text-uppercase">
                                <th>Sl No</th>
                                <th>Ad ID</th>
                                <th>Customer Name</th>
                                <th>Customer Email</th>
                                <th>Category</th>
                                <th>City</th>
                                <th>Plan</th>
                                <th>Is Featured</th>
                                <th>Status</th>
                                <th>Created On</th>
                            </tr>
                        </thead>
                        <tbody class="list form-check-all">
                            
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    <!--end col-->
</div>
<!--end row-->
<!--end row-->
@endsection
@section('script')
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.5/dist/jquery.validate.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.5/dist/additional-methods.min.js"></script>
  
<script>
    var table = $('#UserReportTable').DataTable({
            responsive: true, 
            paging: true,     
            searching: true,  
            ordering: true,   
            lengthChange: true, 
            serverSide: true,
            ajax: {
                url: "{{ route('admin.reports.adstatistics.list') }}",
                type:'GET',
                data: function(d) {
                    d.status        = $('#idStatus').val();
                    d.user_id       = $('.customer-dropdown-field').val();
                    d.user_email_id        = $('#userEmail').val();
                    d.parent_category_id = $('#parent_category').val();
                    d.category_id   = $('#category').val();
                    d.city_id       = $('#city_id').val();
                    d.start_date    = $("#start_date").val();
                    d.end_date      = $("#end_date").val();
                },
            },
            columns: [
                { data: 'id', name: 'id' },
                { data: 'ad_number', name: 'ad_number' },
                { data: 'customer_name', name: 'customer_name' },
                { data: 'customer_email', name: 'customer_email' },
                { data: 'category_name', name: 'category_name' },
                { data: 'city_name', name: 'city_name' },
                { data: 'plan_name', name: 'plan_name' },
                { data: 'is_featured', name: 'is_featured' },
                { data: 'status', name: 'status' },
                { data: 'created_at', name: 'created_at' }
            ],
            columnDefs: [
                {
                    orderable: false,
                    targets: [0, 3]
                },
                {
                    "targets": 0, // Target the first column (index 0)
                    "render": function(data, type, row, meta) {
                        // Calculate the starting index of the current page
                        const pageInfo = $('#UserReportTable').DataTable().page.info();
                        const startIndex = pageInfo.start;
                        // Calculate the serial number
                        return startIndex + meta.row + 1;
                    }
                }
            ],
        });

    $(document).ready(function() {

        $('#filterForm').on('submit', function(e) {
            e.preventDefault(); 
            table.ajax.reload();
        });
        
        $('#clearButton').on('click', function(e) {
            e.preventDefault(); 
            $('#filterForm')[0].reset(); 
            window.location.href = window.location.pathname; 
        });

        $('#idStatus').change(function () {
            table.ajax.reload();
        });

        $('#userEmail').change(function () {
            table.ajax.reload();
        });
        
        $(".customer-dropdown-field").select2({
            minimumInputLength: 2,
            minimumResultsForSearch: 10,
            multiple: true,
            ajax: {
                url: "{{ route('admin.getMinimalUserList') }}",
                dataType: "json",
                type: "GET",
                data: function (params) {
                    return {
                        term: params.term,
                        page: params.page,
                        limit: 10,
                        type: 'name'
                    };
                },
                processResults: function (data) {
                    return {
                        results: $.map(data, function (item) {
                            return {
                                text: item.text,
                                id: item.id
                            }
                        })
                    };
                },
            },
        });

        $(".customer-email-field").select2({
            minimumInputLength: 2,
            minimumResultsForSearch: 10,
            ajax: {
                url: "{{ route('admin.getMinimalUserList') }}",
                dataType: "json",
                type: "GET",
                data: function (params) {
                    return {
                        term: params.term,
                        page: params.page,
                        limit: 10,
                        type: 'email'
                    };
                },
                processResults: function (data) {
                    return {
                        results: $.map(data, function (item) {
                            return {
                                text: item.text,
                                id: item.id
                            }
                        })
                    };
                },
            },
        });

        $(".customer-dropdown-field").on('change', function (e) {
            table.ajax.reload();
        });

        $('#parent_category').on('change', function() {
            var parentCategoryId = $(this).val();
            var url = "{{ route('admin.getCategoryMinimalList', 'parent_id=:id') }}".replace(':id', parentCategoryId);
            $('#category').select2('destroy');

            $.ajax({
                url: url,
                type: 'GET',
                success: function(response) {

                        var categoryOptions = '<option value="all">All Sub Categories</option>';
                        if (response.length > 0) {
                            $.each(response, function(index, category) {
                                categoryOptions += '<option value="' + category.id + '">' + category.name + '</option>';
                            });
                        }
                        $('#category').html(categoryOptions);
                        $('#category').select2();
                        $(".ad-select2-ajax-search").val(null).trigger('change');
                },
                error: function(xhr, status, error) {
                    Swal.fire({
                        title: "Error!",
                        text: "Something went wrong. Please try again later.",
                        icon: "error",
                        confirmButtonText: "OK"
                    });
                }
            });
            table.ajax.reload();
        });

        $('#category').on('change', function(){
            table.ajax.reload();
        });

        $('#city_id').on('change', function(){
            table.ajax.reload();
        });

        $('#start_date').change(function() {
            var startDate = $(this).val();
            var endDate = $('#end_date').val();
            if (startDate) {
            $('#end_date').attr('min', startDate);
            if (endDate && new Date(endDate) < new Date(startDate)) {
                $('#end_date').val('');
            }
            } else {
            $('#end_date').removeAttr('min');
            $('#end_date').attr('max', '{{ $today }}');
            }
            table.ajax.reload();
        });

        $('#end_date').change(function() {
            var endDate = $(this).val();
            var startDate = $('#start_date').val();
            if (endDate) {
            $('#start_date').attr('max', endDate);
            if (startDate && new Date(startDate) > new Date(endDate)) {
                $('#start_date').val('');
            }
            } else {
            $('#start_date').removeAttr('max');
            $('#start_date').attr('max', '{{ $today }}');
            }
            table.ajax.reload();
        });


        $('#export-excel').click(function () {
            var serializedData = $('#filterForm').serialize();
            var newValue = $('.dt-container input[type="search"]').val();
            var updatedData = serializedData + '&' + encodeURIComponent('search') + '=' + encodeURIComponent(newValue);
            window.location.href = '{{ route('admin.reports.adstatistics.exportExcel') }}?' + updatedData;
        });

        $('#export-pdf').click(function () {
            var serializedData = $('#filterForm').serialize();
            var newValue = $('.dt-container input[type="search"]').val();
            var updatedData = serializedData + '&' + encodeURIComponent('search') + '=' + encodeURIComponent(newValue);
            window.location.href = '{{ route('admin.reports.adstatistics.exportPdf') }}?' + updatedData;
        });

    });
</script>

@endsection
