<?php $__env->startSection('content'); ?>
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet" />
    <link href="<?php echo e(config('app.url')); ?>/public/public/vendors/datatables/dataTables.bootstrap4.css" rel="stylesheet"
          type="text/css" />
    <link href="<?php echo e(config('app.url')); ?>/public/public/vendors/datatables/datatables.mark.css" rel="stylesheet"
          type="text/css" />
    <link href="<?php echo e(config('app.url')); ?>/public/public/vendors/datatables/buttons.bootstrap4.css" rel="stylesheet"
          type="text/css" />
    <link href="<?php echo e(config('app.url')); ?>/public/public/vendors/datatables/responsive.bootstrap4.css" rel="stylesheet"
          type="text/css" />
    <link href="<?php echo e(config('app.url')); ?>/public/public/vendors/datatables/select.bootstrap4.css" rel="stylesheet"
          type="text/css" />
    <link href="<?php echo e(config('app.url')); ?>/public/public/assets/css/date-range-picker.css" rel="stylesheet"
          type="text/css" />
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />
    <script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>

    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet" />
    <div class="page-content-wrapper">
         <!-- ============================================================== -->
            <!-- Start Page Content here -->
            <!-- ============================================================== -->

            <div class="content-page">
                <div class="content">

                    <!-- Start Content-->
                    <div class="container-fluid">

                        <!-- start page title -->
                        <div class="row">
                            <div class="col-12">
                                <div class="bg-flower">
                                    <img src="<?php echo e(config('app.url')); ?>/public/public/assets/assets/images/flowers/img-3.png">
                                </div>

                                <div class="bg-flower-2">
                                    <img src="<?php echo e(config('app.url')); ?>/public/public/assets/assets/images/flowers/img-1.png">
                                </div>
        
                                <div class="page-title-box">
                                    <div class="page-title-right">
                                    </div>
                                    <h4 class="page-title">Report Options</h4>
                                </div>
                            </div>
                        </div>
                        <form method="post" id="performanceFilter">
                            <?php echo e(csrf_field()); ?>

                        <!-- end page title -->
                        <div class="row g-4">
                        <div class="col-12">
                            <div class="mb-4">
                                <div class="table-responsive">
                                    <table class="table table-bordered table-striped mb-0">
                                        <tbody>
                                            
                                            <tr>
                                                <th class="text-nowrap" rowspan="2" scope="row">Indicator</th>
                                                <td>
                                                <div class="form-check mb-2">
                                    <input type="checkbox" class="form-check-input" id="publisher_id" name="publisher_id" value="publisher_id" checked>
                                    <label class="form-check-label" for="publisher_id">Publisher ID</label>
                                </div>
                                </td>
                                <td>
                                                <div class="form-check mb-2">
                                    <input type="checkbox" class="form-check-input" id="publisher_name" name="publisher" value="publisher" checked>
                                    <label class="form-check-label" for="publisher">Publisher</label>
                                </div>
                                </td>
                                <td>
                                <div class="form-check form-checkbox-success mb-2">
                                    <input type="checkbox" class="form-check-input" id="offer_id" name="offer_id" value="offer_id" checked>
                                    <label class="form-check-label" for="offer_id">Offer ID</label>
                                </div>
                                </td>
                                <td>
                                <div class="form-check form-checkbox-success mb-2">
                                    <input type="checkbox" class="form-check-input" id="offer" name="offer_name" value="offer_name" checked>
                                    <label class="form-check-label" for="offer">Offer Name</label>
                                </div>
                                </td>
                                            </tr>
                                            <tr>
                                                
                                                <td>
                                                <div class="form-check mb-2">
                                    <input type="checkbox" class="form-check-input" id="advertiser_id" name="advertiser_id" value="advertiser_id">
                                    <label class="form-check-label" for="advertiser_id">Advertiser ID</label>
                                </div>
                                </td>
                                <td>
                                                <div class="form-check form-checkbox-secondary mb-2">
                                    <input type="checkbox" class="form-check-input" id="country" name="country" value="country">
                                    <label class="form-check-label" for="country">Country</label>
                                </div>
                                </td>
                                <td>
                                <div class="form-check form-checkbox-secondary mb-2">
                                    <input type="checkbox" class="form-check-input" id="device" name="ua_target" value="ua_target">
                                    <label class="form-check-label" for="device">Device</label>
                                </div>
                                </td>
                                <td>
                                <div class="form-check form-checkbox-secondary mb-2">
                                    <input type="checkbox" class="form-check-input" id="browser" name="browser" value="browser">
                                    <label class="form-check-label" for="browser">Browser</label>
                                </div>
                                </td>
                                            <tr>
                                                <th class="text-nowrap" rowspan="2" scope="row">Statistics</th>
                                                <td>
                                                <div class="form-check form-checkbox-info mb-2">
                                                <input type="checkbox" class="form-check-input" id="statistics_clicks" name="clicks" value="clicks" checked>
                                                <label class="form-check-label" for="statistics_clicks">Clicks</label>
                                            </div>
                                            </td>
                                            <td>
                                                <div class="form-check form-checkbox-info mb-2">
                                                <input type="checkbox" class="form-check-input" id="statistics_uniclicks" name="unique_" value="unique_" checked>
                                                <label class="form-check-label" for="statistics_uniclicks">Unique Clicks</label>
                                            </div>
                                            </td>
                                            <td>
                                             <div class="form-check form-checkbox-danger mb-2">
                                            <input type="checkbox" class="form-check-input" id="statistics_conversions" name='conversion' value="conversion" checked>
                                             <label class="form-check-label" for="statistics_conversions">Conversions</label>
                                            </div>
                                            </td>
                                            <td>
                                            <div class="form-check form-checkbox-danger mb-2">
                                            <input type="checkbox" class="form-check-input" id="statistics_payout" name="payout" value="payout" checked>
                                            <label class="form-check-label" for="statistics_payout">Payout</label>
                                            </div>
                                            </td>
                                            </tr>
                                            <tr>
                                               
                                                <td>
                                                <div class="form-check  form-checkbox-warning mb-2">
                                    <input type="checkbox" class="form-check-input" id="source" name="source" value="source">
                                    <label class="form-check-label" for="source">Source</label>
                                          </div>
                                            </td>
                                            <td>
                                            <div class="form-check form-checkbox-dark">
                                                <input type="checkbox" class="form-check-input" id="admin_earned" name="admin_earned" value="admin_earned">
                                                <label class="form-check-label" for="admin_earned">Admin Earning</label>
                                            </div>
                                            </td>
                                            <td>
                                                        <div class="form-check form-checkbox-dark">
                                                <input type="checkbox" class="form-check-input" id="affliate_manager_earnings" name="affliate_manager_earnings" value="affliate_manager_earnings">
                                                <label class="form-check-label" for="affliate_manager_earnings">Manager Earning</label>
                                            </div>
                                            </td>
                                            <td>
                                                        <div class="form-check form-checkbox-dark">
                                                <input type="checkbox" class="form-check-input" id="publisher_earned" name="publisher_earned" value="publisher_earned" checked>
                                                <label class="form-check-label" for="publisher_earned">Publisher Earning</label>
                                                
                                            </div>
                                            </td>
                                            </tr>
                                            <tr>
                                                <th class="text-nowrap" rowspan="2" scope="row">Filter</th>
                                                <td colspan="2">
                                                <div class="mb-4">
                                <h4 class="fs-16" for="publisher-select"> Publisher </h4>
                                <div class="btn-group mb-2">
                                                <select id="publisher-select" class="btn btn-success dropdown-toggle">
                                                  <option value="" selected>Open this select publisher</option>>
                                                 <?php $__currentLoopData = $publisher; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $item): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                    <option value="<?php echo e($item->id); ?>"><?php echo e($item->name); ?></option>
                                                  <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                                </select>
                                    </div>
                                    
                                </div><!-- /btn-group -->
                                            </td>
                                            <td colspan="2">
                                                <div class="mb-4">
                                <h4 class="fs-16"> Offers</h4>
                                <div class="btn-group mb-2">
                                <select id="offer-select" class="btn btn-success dropdown-toggle">
                                                  <option value="" selected>Open This Select Offer</option>>
                                    
                                    <<?php $__currentLoopData = $offer; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $item): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                    <option value="<?php echo e($item->id); ?>"><?php echo e($item->offer_name); ?></option>
                                                  <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                                </select>
                                    </div>
                                </div><!-- /btn-group -->
                                            </td>
                                        </tbody>
                                    </table>
                                </div> <!-- end table-responsive-->
                            </div> <!-- end card-->
                        </div> <!-- end col-->
                    </div>
                    <!-- end row -->
             <!--       <div class="row mt-4">
                                    <div class="col-lg-2 col-md-2"></div>
                                    <div class="col-lg-10 col-md-10">
                                        <div class="row">
                                            <div class="form-group-column col-lg-6 col-md-6 col-sm-12">
                                                <div class="daterange" id="reportrange" style="background: #fff; cursor: pointer; padding: 2px 10px; border: 1px solid #ccc; width: 100%">
                                                    <i class="fa fa-calendar"></i>&nbsp;
                                                    <input type="text" name="dateRangeInput" value="" readonly />
                                                    <i class="fa fa-caret-down"></i>
                                                </div>
                                            </div>
                                            <div class="form-group-column col-lg-6 col-md-6 col-sm-12">
                                                <button id="generateReport" type="submit" class="btn btn-success">
                                                    <i class="fa fa-play" aria-hidden="true"></i> Generate Report
                                                </button>
                                            </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>-->
                    <div class="row mt-4">
                                    <div class="col-lg-2 col-md-2"></div>
                                    <div class="col-lg-8 col-md-8">
                                        <div class="row">
                                            <div class="form-group-column col-lg-6 col-md-6 col-sm-12">
                                                <div class="daterange" id="reportrange"
                                                style="background: #fff; cursor: pointer; padding: 1px 2px; border: 1px solid #ccc; border-radius: 2px" class="fa fa-calendar" &nbsp;>
                                                    <input class="form-control date" type="text" name="dateRangeInput"
                                                        value="" readonly />
                                                </div>
                                            </div>

                                            <div class="form-group-column col-lg-6 col-md-6 col-sm-12">
                                                <button id="generateReport" type="submit" class="btn btn-success">
                                                    <i class="fa fa-play" aria-hidden="true"></i> Generate Report
                                                </button>
                                            </div>
                                        </div>
                                    </div>


                    
                        
                    </div> <!-- container -->
                    <div class="row g-4">
                        <div class="col-12">
                            <div class="mb-4">

                                <table id="basic-datatable" class="table table-striped dt-responsive nowrap w-100">
                                <div class="table-container" style="overflow-y: auto;">
                            <table class="table" style="width: full">
                              <thead class="thead-dark" style="background-color: #7db180; color: #ffffff;">
                                <tr style="font-size: 12px">
                                  <th scope="col">Publisher ID</th>
                                  <th scope="col">Publisher</th>
                                  <th scope="col">Offer ID</th>
                                  <th scope="col">Clicks</th>
                                  <th scope="col">Conversions</th>
                                  <th scope="col">Payout</th>
                                  <th scope="col">Source</th>
                                </tr>
                              </thead>
                              <tbody id="table-body">
                              </tbody>
                            </table>
                        </div>
                        </div> <!-- end card -->
                        </div><!-- end col-->
                    </div> <!-- end row-->

                </div> <!-- content -->
    </div>
<?php $__env->stopSection(); ?>
<?php $__env->startSection('js'); ?>
                           

                <!-- Footer Start -->
                <footer class="footer">
                    <div class="container-fluid">
                        <div class="row">
                            <div class="col-md-6">
                                <script>document.write(new Date().getFullYear())</script> © BDBSE - Bdbse.com
                            </div>
                            <div class="col-md-6">
                                <div class="text-md-end footer-links d-none d-md-block">
                                    <a href="javascript: void(0);">About</a>
                                    <a href="javascript: void(0);">Support</a>
                                    <a href="javascript: void(0);">Contact Us</a>
                                </div>
                            </div>
                        </div>
                    </div>
                </footer>
                <!-- end Footer -->


    <script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
            crossorigin="anonymous"></script>
    <script type="text/javascript" src="<?php echo e(config('app.url')); ?>/public/public/vendors/datatables/jquery.mark.min.js">
    </script>
    <script src="<?php echo e(config('app.url')); ?>/public/public/vendors/datatables/jquery.dataTables.min.js"></script>
    <script src="<?php echo e(config('app.url')); ?>/public/public/vendors/datatables/dataTables.bootstrap4.min.js"></script>
    <script src="<?php echo e(config('app.url')); ?>/public/public/vendors/datatables/dataTables.buttons.min.js"></script>
    <script src="<?php echo e(config('app.url')); ?>/public/public/vendors/datatables/buttons.bootstrap4.min.js"></script>
    <script src="<?php echo e(config('app.url')); ?>/public/public/vendors/datatables/dataTables.keyTable.min.js"></script>
    <script src="<?php echo e(config('app.url')); ?>/public/public/vendors/datatables/dataTables.select.min.js"></script>
    <script src="<?php echo e(config('app.url')); ?>/public/public/vendors/datatables/buttons.html5.min.js"></script>
    <script src="<?php echo e(config('app.url')); ?>/public/public/vendors/datatables/buttons.print.min.js"></script>
    <script src="<?php echo e(config('app.url')); ?>/public/public/vendors/datatables/dataTables.responsive.min.js"></script>
    <script src="<?php echo e(config('app.url')); ?>/public/public/vendors/datatables/responsive.bootstrap4.min.js"></script>
    <script src="<?php echo e(config('app.url')); ?>/public/public/vendors/datatables/datatables.mark.js"></script>
    <script src="<?php echo e(config('app.url')); ?>/public/public/assets/js/date-range-picker.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/js/select2.min.js"></script>
    
    <script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
    
    
    <script>
        $(document).ready(function () {
            
            $(function () {
                var start = moment().subtract(29, 'days');
                var end = moment();
    
                function cb(start, end) {
                    var dateRangeText = start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY');
                    $('#reportrange input[name="dateRangeInput"]').val(dateRangeText);
                }
    
                $('#reportrange').daterangepicker({
                    startDate: moment().subtract(29, 'days'),
                    endDate: moment(),
                    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')]
                    }
                }, cb);
    
                cb(moment().subtract(29, 'days'), moment());
                
                $('#performanceFilter').submit(function (e) {
                    e.preventDefault();
            
                    const selectedFields = $('input[type="checkbox"]:checked').map(function () {
                        return this.value;
                    }).get();
                    selectedFields.push('status');
                    
                    const conversionIndex = selectedFields.indexOf('conversion');
                    const clicksIndex = selectedFields.indexOf('clicks');
                    const publisherField = selectedFields.indexOf('publisher');
                    const advertiserField = selectedFields.indexOf('advertiser');

                    // console.log("Before splice:", selectedFields);

                    if (conversionIndex !== -1) {
                        selectedFields.splice(conversionIndex, 1);
                    }

                    if (clicksIndex !== -1) {
                        // Remove "clicks" from the selectedFields array
                        selectedFields.splice(clicksIndex, 1);
                    }

                    if (publisherField !== -1) {
                        selectedFields.splice(publisherField, 1);
                    }

                    if (advertiserField !== -1) {
                        selectedFields.splice(advertiserField, 1);
                    }

                    const selectedPublisher = $('#publisher-select').val();
                    const selectedOffer = $('#offer-select').val();
                    const selectedDateRange = $('#reportrange input[name="dateRangeInput"]').val();
                    const selectedConversions = $('#statistics_conversions').prop('checked');
                    const selectedClicks = $('#statistics_clicks').prop('checked');
                    const selectedPublisherNm = $('#publisher_name').prop('checked');
                    const selectedPublisherId = $('#publisher_id').prop('checked');
                    const selectedOfferId = $('#offer_id').prop('checked');
                    const selectedCountry = $('#country').prop('checked');
                    const selectedDevice = $('#device').prop('checked');
                    const selectedBrowser = $('#browser').prop('checked');
                    const selectedAdminEarn = $('#admin_earned').prop('checked');
                    const selectedManagerEarn = $('#affliate_manager_earnings').prop('checked');
                    const selectedPublisherEarn = $('#publisher_earned').prop('checked');
                    const selectedUniqueClick = $('#statistics_uniclicks').prop('checked');

                    let startDate, endDate;
            
                    // Check if the selected date range is 'Today' or 'Yesterday'
                    if (selectedDateRange === 'Today') {
                        startDate = moment().startOf('day').format('YYYY-MM-DD');
                        endDate = moment().endOf('day').format('YYYY-MM-DD');
                    } else if (selectedDateRange === 'Yesterday') {
                        startDate = moment().subtract(1, 'days').startOf('day').format('YYYY-MM-DD');
                        endDate = moment().subtract(1, 'days').endOf('day').format('YYYY-MM-DD');
                    } else {
                        // Otherwise, get the start and end dates from the date range picker
                        [startDate, endDate] = selectedDateRange.split(' - ').map(date => moment(date, 'MMMM D, YYYY').format('YYYY-MM-DD'));
                    }

                    const dataToSend = {
                        data: selectedFields,
                        selectedPublisher: selectedPublisher,
                        offer: selectedOffer,
                        dateRangeInput: startDate + ' - ' + endDate // Format the date range as 'YYYY-MM-DD - YYYY-MM-DD'
                    };
            
                    // Send the AJAX request
                    $.ajax({
                        url: "<?php echo e(route('admin.generateReport')); ?>",
                        type: "POST",
                        data: dataToSend,
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        success: function (data) {
                            // Update the content with the filtered data
                            const newSelectedField =  selectedFields.filter(field => field !== 'status' && field !== 'unique_');
                            if ($.isEmptyObject(data.offers)) {
                                // If no data found, display the message and clear the table body and header
                                $('#table-body').empty();
                                $('.thead-dark').empty();
                                const tableRow = $('<tr></tr>');
                                tableRow.append('<td colspan="' + newSelectedField.length + '" class="data-not-found text-center">Data Not Found</td>');
                                $('#table-body').append(tableRow);
                            } else {
                                // If data is found, update the table header and body
                                $('#table-body').empty();
                                $('.thead-dark').empty();
                                const tableHead = $('<tr style="font-size: 12px;"></tr>');
                                newSelectedField.forEach(function (field) {
                                    let fieldName = field.replace(/_/g, ' '); // Replace underscores with spaces
                                    fieldName = fieldName.replace(/\b\w/g, (l) => l.toUpperCase()); // Capitalize the first letter of each word
                                    
                                    if(fieldName === 'Id'){
                                        fieldName = 'ID'; // Change "id" to "ID"
                                    }

                                    if (fieldName === 'Ua Target'){
                                        fieldName = 'Device';
                                    }

                                    if (fieldName === 'Affliate Manager Earnings'){
                                        fieldName = 'Manager Earnings';
                                    }
                                    
                                    tableHead.append('<th>' + fieldName + '</th>');
                                });

                                if (selectedClicks){
                                    tableHead.append('<th>Click</th>');
                                }
                                
                                if (selectedConversions) {
                                    tableHead.append('<th>Conversions</th>');
                                }

                                if (selectedPublisherNm){
                                    tableHead.append('<th>Publisher</th>');
                                }

                                if (selectedUniqueClick){
                                    tableHead.append('<th>Unique Click</th>');
                                }
                                
                                $('.thead-dark').append(tableHead);

                                const tableRows = [];

                                const clickCounts = {};
                                const uniqueData = {};
                                const conversionCounts = {};
                                const uniqueClicks = {};

                                // Rest of the code remains unchanged
                                data.offers.forEach(function (row) {

                                    const publisherId = row.publisher_id;
                                    const offerId = row.offer_id;
                                    const country = row.country;
                                    const device = row.ua_target;
                                    const browser = row.browser;
                                    const conversions = row.status;
                                    const uniqueClick = row.unique_;

                                    let publisher_name;
                                    
                                    if (selectedPublisherNm && row.publisher_name){
                                        publisher_name = row.publisher_name.name;
                                    }else{
                                        publisher_name = 'Unknow';
                                    }
                                

                                    let uniqueKey;

                                    switch (true) {
                                        case selectedPublisherId && selectedOfferId && selectedCountry && selectedDevice && selectedBrowser:
                                            uniqueKey = publisherId + '_' + offerId + '_' + country + '_' + device + '_' + browser;
                                            break;
                                        case selectedPublisherId && selectedOfferId && selectedCountry && selectedDevice:
                                            uniqueKey = publisherId + '_' + offerId + '_' + country + '_' + device;
                                            break;
                                        
                                        case selectedPublisherId && selectedOfferId && selectedCountry && selectedBrowser:
                                            uniqueKey = publisherId + '_' + offerId + '_' + country + '_' + browser;
                                            break;

                                        case selectedPublisherId && selectedOfferId &&  selectedDevice && selectedBrowser:
                                            uniqueKey = publisherId + '_' + offerId + '_' + device + '_' + browser;
                                            break;
                                        
                                        case selectedPublisherId && selectedCountry && selectedDevice && selectedBrowser:
                                            uniqueKey = publisherId + '_' + country + '_' + device + '_' + browser;
                                            break;

                                        case selectedOfferId && selectedCountry && selectedDevice && selectedBrowser:
                                            uniqueKey = offerId + '_' + country + '_' + device + '_' + browser;
                                            break;

                                        case selectedPublisherId && selectedOfferId && selectedCountry:
                                            uniqueKey = publisherId + '_' + offerId + '_' + country;
                                            break;

                                        case selectedPublisherId && selectedOfferId && selectedDevice:
                                            uniqueKey = publisherId + '_' + offerId + '_' + device;
                                            break;

                                        case selectedPublisherId && selectedOfferId && selectedBrowser:
                                            uniqueKey = publisherId + '_' + offerId + '_' + browser;
                                            break;
                                        
                                        case selectedPublisherId && selectedCountry && selectedDevice:
                                            uniqueKey = publisherId + '_' + country + '_' + device;
                                            break;

                                        case selectedPublisherId && selectedCountry && selectedBrowser:
                                            uniqueKey = publisherId + '_' + country + '_' + browser;
                                            break;

                                        case selectedPublisherId && selectedDevice && selectedBrowser:
                                            uniqueKey = publisherId + '_' + device + '_' + browser;
                                            break;

                                        case selectedCountry && selectedDevice && selectedBrowser:
                                            uniqueKey = country + '_' + device + '_' + browser;
                                            break;

                                        case selectedOfferId && selectedCountry && selectedDevice:
                                            uniqueKey = offerId + '_' + country + '_' + device;
                                            break;

                                        case selectedOfferId && selectedCountry && selectedBrowser:
                                            uniqueKey = offerId + '_' + country + '_' + browser;
                                            break;

                                        case selectedOfferId && selectedDevice && selectedBrowser:
                                            uniqueKey = offerId +  '_' + device + '_' + browser;
                                            break;

                                        case selectedPublisherId && selectedOfferId:
                                            uniqueKey = publisherId + '_' + offerId;
                                            break;

                                        case selectedPublisherId && selectedCountry:
                                            uniqueKey = publisherId + '_' + country;
                                            break;

                                        case selectedPublisherId && selectedDevice:
                                            uniqueKey = publisherId + '_' + device;
                                            break;

                                        case selectedPublisherId && selectedBrowser:
                                            uniqueKey = publisherId + '_' + browser;
                                            break;

                                        case selectedOfferId && selectedCountry:
                                            uniqueKey = offerId + '_' + country;
                                            break;

                                        case selectedOfferId && selectedDevice:
                                            uniqueKey = offerId + '_' + device;
                                            break;

                                        case selectedOfferId && selectedBrowser:
                                            uniqueKey = offerId + '_' + browser;
                                            break;

                                        case selectedCountry && selectedDevice:
                                            uniqueKey = country + '_' + device;
                                            break;

                                        case selectedCountry&& selectedBrowser:
                                            uniqueKey = country + '_' + browser;
                                            break;

                                        case selectedDevice && selectedBrowser:
                                            uniqueKey = device + '_' + browser;
                                            break;

                                        case selectedPublisherId:
                                            uniqueKey = publisherId;
                                            break;

                                        case selectedOfferId:
                                            uniqueKey = offerId;
                                            break;
                                        

                                        default:
                                            break;
                                    }
                                    

                                    if (clickCounts[uniqueKey]) {
                                        clickCounts[uniqueKey]++;
                                    } else {
                                        clickCounts[uniqueKey] = 1;
                                        uniqueData[uniqueKey] = {
                                            publisher_id: publisherId,
                                            publisher_name: publisher_name,
                                            advertiser_id: row.advertiser_id,
                                            offer_id: offerId,
                                            offer_name: row.offer_name,
                                            country: country,
                                            ua_target: device,
                                            browser: browser,
                                            payout: row.payout,
                                            source: row.source,
                                            admin_earned : row.admin_earned,
                                            publisher_earned : row.publisher_earned,
                                            affliate_manager_earnings : row.affliate_manager_earnings,
                                        };

                                    }

                                    if(uniqueClick != 0 && uniqueClick != null){
                                        if (uniqueClicks[uniqueKey]) {
                                            uniqueClicks[uniqueKey]++;
                                        } else {
                                            uniqueClicks[uniqueKey] = 1;
                                        }
                                    }else{
                                        if (!uniqueClicks[uniqueKey]) { // Only initialize if it doesn't exist
                                            uniqueClicks[uniqueKey] = 0;
                                        }
                                    }
                                    
                                    if (conversions === 'Approved') {
                                        if (conversionCounts[uniqueKey]) {
                                            conversionCounts[uniqueKey]++;
                                        } else {
                                            conversionCounts[uniqueKey] = 1;
                                        }
                                    } else { // Move the else block outside
                                        if (!conversionCounts[uniqueKey]) { // Only initialize if it doesn't exist
                                            conversionCounts[uniqueKey] = 0;
                                        }
                                    }

                                });

                                let totalClicks = 0;
                                let totalAdminEarned = 0.0;
                                let totalPublisherEarned = 0.0;
                                let totalUniqueClicks = 0;
                                let totalManagerEarned = 0.0;
                                let totalConversion = 0;
                                let rowCount = 0;

                                
                                let tableRow = $('<tr style="font-size: 12px;"></tr>');
                                for (const uniqueKey in clickCounts) {
                                    const data = uniqueData[uniqueKey];
                                    const click = clickCounts[uniqueKey];
                                    const conversion = conversionCounts[uniqueKey];
                                    const unique_click = uniqueClicks[uniqueKey];

                                    totalClicks += click;
                                    totalUniqueClicks += unique_click;
                                    totalConversion += conversion;
                                    rowCount++;

                                    // Create a new table row and add cells for each selected field
                                    const tableRow = $('<tr style="font-size: 12px;"></tr>');

                                    newSelectedField.forEach(function (field) {

                                        let cellValue = data[field];

                                        if (field === 'payout') {
                                            cellValue = parseFloat(cellValue).toFixed(2);
                                            
                                            if (conversion === null || conversion === 0) {
                                                 cellValue = "00.00";
                                            } else {
                                                // Multiply "payout" by "conversion" and display the result
                                                const payoutValue = parseFloat(data.payout) * conversion;
                                                cellValue = payoutValue;
                                            }
                                        }

                                        if(field === 'admin_earned'){
                                            cellValue = parseFloat(cellValue).toFixed(2);

                                            if (conversion === null || conversion === 0) {
                                                 cellValue = "00.00";
                                                 totalAdminEarned += 0.0;
                                            } else {
                                                // Multiply "payout" by "conversion" and display the result
                                                const adminEarned = parseFloat(data.admin_earned) * conversion;
                                                cellValue = adminEarned;
                                                totalAdminEarned += parseFloat(adminEarned) || 0;
                                            }
                                        }

                                        if(field === 'affliate_manager_earnings'){
                                            cellValue = parseFloat(cellValue).toFixed(2);

                                            if (conversion === null || conversion === 0) {
                                                cellValue = "00.00";
                                            } else {
                                                if(data.affliate_manager_earnings === null){
                                                    cellValue = "00.00";
                                                }else{
                                                    // Multiply "payout" by "conversion" and display the result
                                                    const managerEarning = parseFloat(data.affliate_manager_earnings) * conversion;
                                                    cellValue = managerEarning;
                                                    totalManagerEarned += parseFloat(managerEarning) || 0;
                                                }
                                            }
                                        }

                                        if(field === 'publisher_earned'){
                                            cellValue = parseFloat(cellValue).toFixed(2);

                                            if (conversion === null || conversion === 0) {
                                                cellValue = "00.00";
                                            } else {
                                                // Multiply "payout" by "conversion" and display the result
                                                const publisherEarning = parseFloat(data.publisher_earned) * conversion;
                                                cellValue = publisherEarning;
                                                totalPublisherEarned += parseFloat(publisherEarning) || 0;
                                            }
                                        }

                                        tableRow.append('<td>' + cellValue + '</td>');
                                    });

                                    // Add additional cells based on selections
                                    if (selectedClicks) {
                                        tableRow.append(`<td>${click}</td>`);
                                    }

                                    if (selectedConversions) {
                                        tableRow.append(`<td>${conversion}</td>`);
                                    }

                                    if (selectedPublisherNm) {
                                        tableRow.append(`<td>${data.publisher_name}</td>`);
                                    }

                                    if(selectedUniqueClick){
                                        tableRow.append(`<td>${unique_click}</td>`);
                                    }

                                    tableRows.push(tableRow);

                                    // Check if this is the last iteration
                                    if (rowCount === Object.keys(clickCounts).length) {
                                        // This is the last iteration, append total values
                                        const totalRow = $('<tr style="font-size: 12px;"></tr>');
                                        // totalRow.append('<td>Total:</td>');
                                        newSelectedField.forEach(function (field) {
                                            if (field === 'admin_earned') {
                                                totalRow.append(`<td>${totalAdminEarned.toFixed(2)}</td>`);
                                            } else if (field === 'publisher_earned') {
                                                totalRow.append(`<td>${totalPublisherEarned.toFixed(2)}</td>`);
                                            } else if (field === 'affliate_manager_earnings') {
                                                totalRow.append(`<td>${totalManagerEarned.toFixed(2)}</td>`);
                                            } else {
                                                totalRow.append('<td></td>'); // Add empty cell for other fields
                                            }
                                        });
                                        if (selectedClicks) {
                                            totalRow.append(`<td>${totalClicks}</td>`);
                                        }else{
                                            totalRow.append(`<td> </td>`);
                                        }

                                        if (selectedConversions) {
                                            totalRow.append(`<td>${totalConversion}</td>`);
                                        }else{
                                            totalRow.append(`<td> </td>`);
                                        }

                                        if (selectedPublisherNm) {
                                            totalRow.append(`<td> </td>`);
                                        }

                                        if(selectedUniqueClick){
                                            totalRow.append(`<td>${totalUniqueClicks}</td>`);
                                        }else{
                                            totalRow.append(`<td> </td>`);
                                        }

                                        tableRows.push(totalRow);
                                    }

                                }

                                $('#table-body').append(tableRows);
                            }
                        },
                        error: function (error) {
                            console.error(error);
                        }
                    });
                });
            });

        });
    </script>
        
    
<?php $__env->stopSection(); ?>
<?php echo $__env->make('admin.layout.admin-dashboard', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH /home/admin/partner.cpalider.com/backend/resources/views/admin/offer/view_offer_performance.blade.php ENDPATH**/ ?>