@extends('publisher.layout.dashboard')
@section('content')
    <!-- Datatables css -->
    <link
        href="{{ config('app.url') }}/public/public/assets/assets/vendor/datatables.net-bs5/css/dataTables.bootstrap5.min.css"
        rel="stylesheet" type="text/css" />
    <link
        href="{{ config('app.url') }}/public/public/assets/assets/vendor/datatables.net-responsive-bs5/css/responsive.bootstrap5.min.css"
        rel="stylesheet" type="text/css" />
    <link
        href="{{ config('app.url') }}/public/public/assets/assets/vendor/datatables.net-fixedcolumns-bs5/css/fixedColumns.bootstrap5.min.css"
        rel="stylesheet" type="text/css" />
    <link
        href="{{ config('app.url') }}/public/public/assets/assets/vendor/datatables.net-fixedheader-bs5/css/fixedHeader.bootstrap5.min.css"
        rel="stylesheet" type="text/css" />
    <link
        href="{{ config('app.url') }}/public/public/assets/assets/vendor/datatables.net-buttons-bs5/css/buttons.bootstrap5.min.css"
        rel="stylesheet" type="text/css" />
    <link
        href="{{ config('app.url') }}/public/public/assets/assets/vendor/datatables.net-select-bs5/css/select.bootstrap5.min.css"
        rel="stylesheet" type="text/css" />

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/3.5.0/css/flag-icon.min.css">

    <style>
        .daterange {
            display: flex;
            justify-content: center;
            align-items: center;
        }
    </style>

    <div class="page-content-wrapper">
    <div class="row">
            <div class="col-12">
                <div class="bg-flower">
                    <img src="{{ config('app.url') }}/public/public/assets/assets/images/flowers/img-3.png">
                </div>

                <div class="bg-flower-2">
                    <img src="{{ config('app.url') }}/public/public/assets/assets/images/flowers/img-1.png">
                </div>
                    <div class="card radius-10">
                        <div class="card-header">
                            <h4>Report Options</h4>
                        </div>
                        <div class="card-body">
                            <form method="post" id="performanceFilter">
                                {{ csrf_field() }}
                                <div class="row">
                                    <div class="col-lg-2 col-md-2">Indicator</div>
                                    <div class="col-lg-10 col-md-10">
                                        <div class="row">
                                            <input type="hidden" id="publisherId" name="publisher_id"
                                                value="{{ $publisherId }}" checked="checked">
                                            <div class="form-group-column col-lg-3 col-md-3 col-sm-4 col-xs-6">
                                                <input type="checkbox" id="offer_id" name="offer_id" value="offer_id"
                                                    checked='checked'>
                                                <label for="offer_id">Offer ID</label>
                                            </div>
                                            <div class="form-group-column col-lg-3 col-md-3 col-sm-4 col-xs-6">
                                                <input type="checkbox" id="offer" name="offer_name" value="offer_name"
                                                    checked='checked'>
                                                <label for="offer">Offer</label>
                                            </div>
                                            <div class="form-group-column col-lg-3 col-md-3 col-sm-4 col-xs-6">
                                                <input type="checkbox" id="country" name="country" value="country">
                                                <label for="country">Country</label>
                                            </div>
                                            <div class="form-group-column col-lg-3 col-md-3 col-sm-4 col-xs-6">
                                                <input type="checkbox" id="device" name="ua_target" value="ua_target">
                                                <label for="device">Device</label>
                                            </div>
                                            <div class="form-group-column col-lg-3 col-md-3 col-sm-4 col-xs-6">
                                                <input type="checkbox" id="browser" name="browser" value="browser">
                                                <label for="browser">Browser</label>
                                            </div>
                                            <div class="form-group-column col-lg-3 col-md-3 col-sm-4 col-xs-6">
                                                <input type="checkbox" id="sid" name="sid" value="sid">
                                                <label for="sid">Sid1</label>
                                            </div>
                                            <div class="form-group-column col-lg-3 col-md-3 col-sm-4 col-xs-6">
                                                <input type="checkbox" id="sid2" name="sid2" value="sid2">
                                                <label for="sid2">Sid2</label>
                                            </div>
                                            <div class="form-group-column col-lg-3 col-md-3 col-sm-4 col-xs-6">
                                                <input type="checkbox" id="sid3" name="sid3" value="sid3">
                                                <label for="sid3">Sid3</label>
                                            </div>
                                            <div class="form-group-column col-lg-3 col-md-3 col-sm-4 col-xs-6">
                                                <input type="checkbox" id="sid4" name="sid4" value="sid4">
                                                <label for="sid4">Sid4</label>
                                            </div>
                                            <div class="form-group-column col-lg-3 col-md-3 col-sm-4 col-xs-6">
                                                <input type="checkbox" id="sid5" name="sid5" value="sid5">
                                                <label for="sid5">Sid5</label>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="row mt-4">
                                    <div class="col-lg-2 col-md-2">Statistics</div>
                                    <div class="col-lg-10 col-md-10">
                                        <div class="row">
                                            <div class="form-group-column col-lg-3 col-md-3 col-sm-4 col-xs-6">
                                                <input type="checkbox" id="statistics_clicks" name="clicks"
                                                    value="clicks" checked='checked'>
                                                <label for="statistics_clicks">Clicks</label>
                                            </div>
                                            <div class="form-group-column col-lg-3 col-md-3 col-sm-4 col-xs-6">
                                                <input type="checkbox" id="statistics_uniclicks" name="unique_"
                                                    value="unique_" checked='checked'>
                                                <label for="statistics_uniclicks">Unique Clicks</label>
                                            </div>
                                            <div class="form-group-column col-lg-3 col-md-3 col-sm-4 col-xs-6">
                                                <input type="checkbox" id="statistics_conversions" name='conversion'
                                                    value="conversion" checked='checked'>
                                                <label for="statistics_conversions">Conversions</label>
                                            </div>
                                            <div class="form-group-column col-lg-3 col-md-3 col-sm-4 col-xs-6">
                                                <input type="checkbox" id="statistics_payout" name="publisher_earned"
                                                    value="publisher_earning" checked='checked'>
                                                <label for="statistics_payout">Payout</label>
                                            </div>
                                            <div class="form-group-column col-lg-3 col-md-3 col-sm-4 col-xs-6">
                                                <input type="checkbox" id="cr" name="crField" value="crField">
                                                <label for="cr">CR</label>
                                            </div>
                                            <div class="form-group-column col-lg-3 col-md-3 col-sm-4 col-xs-6">
                                                <input type="checkbox" id="cvr" name="cvrField" value="cvrField">
                                                <label for="cvr">CVR</label>
                                            </div>
                                        </div>
                                    </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: 3px 10px; border: 1px solid #ccc; border-radius: 10px">
                                                    <i class="fa fa-calendar"></i>&nbsp;
                                                    <input class="form-control date" 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>
                                    <div class="col-lg-2 col-md-2"></div>
                                </div>
                            </form>
                        </div>
                    </div>
                    <div class="card radius-10 mt-4">
                        <div class="table-container" style="overflow-y: auto;">
                            <table class="table" style="width: full">
                                <thead class="thead-dark" style="background-color: #292929; color: white;">
                                    <tr style="font-size: 15px">
                                        <th scope="col">Offer ID</th>
                                        <th scope="col">Offer</th>
                                        <th scope="col">Clicks</th>
                                        <th scope="col">Conversions</th>
                                        <th scope="col">Payout</th>
                                    </tr>
                                </thead>
                                <tbody id="table-body">
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection
@section('js')
    <!-- Datatables js -->
    <script src="{{ config('app.url') }}/public/public/assets/assets/vendor/datatables.net/js/jquery.dataTables.min.js">
    </script>
    <script
        src="{{ config('app.url') }}/public/public/assets/assets/vendor/datatables.net-bs5/js/dataTables.bootstrap5.min.js">
    </script>
    <script
        src="{{ config('app.url') }}/public/public/assets/assets/vendor/datatables.net-responsive/js/dataTables.responsive.min.js">
    </script>
    <script
        src="{{ config('app.url') }}/public/public/assets/assets/vendor/datatables.net-responsive-bs5/js/responsive.bootstrap5.min.js">
    </script>
    <script
        src="{{ config('app.url') }}/public/public/assets/assets/vendor/datatables.net-fixedcolumns-bs5/js/fixedColumns.bootstrap5.min.js">
    </script>
    <script
        src="{{ config('app.url') }}/public/public/assets/assets/vendor/datatables.net-fixedheader/js/dataTables.fixedHeader.min.js">
    </script>
    <script
        src="{{ config('app.url') }}/public/public/assets/assets/vendor/datatables.net-buttons/js/dataTables.buttons.min.js">
    </script>
    <script
        src="{{ config('app.url') }}/public/public/assets/assets/vendor/datatables.net-buttons-bs5/js/buttons.bootstrap5.min.js">
    </script>
    <script
        src="{{ config('app.url') }}/public/public/assets/assets/vendor/datatables.net-buttons/js/buttons.html5.min.js">
    </script>
    <script
        src="{{ config('app.url') }}/public/public/assets/assets/vendor/datatables.net-buttons/js/buttons.flash.min.js">
    </script>
    <script
        src="{{ config('app.url') }}/public/public/assets/assets/vendor/datatables.net-buttons/js/buttons.print.min.js">
    </script>
    <script
        src="{{ config('app.url') }}/public/public/assets/assets/vendor/datatables.net-keytable/js/dataTables.keyTable.min.js">
    </script>
    <script
        src="{{ config('app.url') }}/public/public/assets/assets/vendor/datatables.net-select/js/dataTables.select.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.name;
                }).get();
                selectedFields.push('status');
                
                const conversionIndex = selectedFields.indexOf('conversion');
                const clicksIndex = selectedFields.indexOf('clicks');
                const crIndex = selectedFields.indexOf('crField');
                const cvrIndex = selectedFields.indexOf('cvrField');
                const removeData1 = selectedFields.indexOf('data-bs-theme');
                const removeData2 = selectedFields.indexOf('data-menu-color');
                const removeData3 = selectedFields.indexOf('data-sidenav-size');
                const removeData4 = selectedFields.indexOf('sidebar-user');
                const removeData5 = selectedFields.indexOf('data-bs-theme');
                const removeData6 = selectedFields.indexOf('data-bs-theme');

                if (removeData1 !== -1) {

                    selectedFields.splice(removeData1, 1);
                }

                if (removeData2 !== -1) {

                    selectedFields.splice(removeData2, 1);
                }

                if (removeData3 !== -1) {

                    selectedFields.splice(removeData3, 1);
                }

                if (removeData4 !== -1) {

                    selectedFields.splice(removeData4, 1);
                }

                if (removeData5 !== -1) {

                    selectedFields.splice(removeData5, 1);
                }

                if (removeData6 !== -1) {

                    selectedFields.splice(removeData6, 1);
                }

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

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

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

                if (clicksIndex !== -1) {

                    selectedFields.splice(clicksIndex, 1);
                }

                const selectedDateRange = $('#reportrange input[name="dateRangeInput"]').val();
                const publisherId = $('#publisherId').val();
                const selectedConversions = $('#statistics_conversions').prop('checked');
                const selectedClicks = $('#statistics_clicks').prop('checked');
                const selectedOfferId = $('#offer_id').prop('checked');
                const selectedCountry = $('#country').prop('checked');
                const selectedDevice = $('#device').prop('checked');
                const selectedBrowser = $('#browser').prop('checked');
                const selectedCR = $('#cr').prop('checked');
                const selectedCVR = $('#cvr').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,
                    publisherId: publisherId,
                    dateRangeInput: startDate + ' - ' + endDate // Format the date range as 'YYYY-MM-DD - YYYY-MM-DD'
                };
        
                // Send the AJAX request
                $.ajax({
                    url: "{{ route('publisher.performance') }}",
                    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: 15px;"></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';
                                }
                                
                                tableHead.append('<th>' + fieldName + '</th>');
                            });

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

                            if(selectedCR){
                                tableHead.append('<th>CR</th>');
                            }

                            if (selectedCVR){
                                tableHead.append('<th>CVR</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) {

                                console.log(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 uniqueKey;

                                switch (true){
                                    case selectedOfferId && selectedCountry && selectedDevice && selectedBrowser:
                                        uniqueKey = offerId + '_' + 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 selectedCountry && selectedDevice && selectedBrowser:
                                        uniqueKey = country + '_' + device + '_' + 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 selectedOfferId && selectedDevice && selectedBrowser:
                                        uniqueKey = offerId +  '_' + device + '_' + browser;
                                        break;

                                    case selectedOfferId:
                                        uniqueKey = offerId;
                                        break;

                                    case selectedCountry:
                                        uniqueKey = country;
                                        break;

                                    case selectedDevice:
                                        uniqueKey = device;
                                        break;

                                    case selectedBrowser:
                                        uniqueKey = browser;
                                        break;
                                    
                                    default:
                                        break;
                                }
                                
                               const sid = row.sid ?? '-';
                               const sid2 = row.sid2 ?? '-';
                               const sid3 = row.sid3 ?? '-';
                               const sid4 = row.sid4 ?? '-';
                               const sid5 = row.sid5 ?? '-';

                                uniqueKey += `_${sid}_${sid2}_${sid3}_${sid4}_${sid5}`;
                                

                                if (clickCounts[uniqueKey]) {
                                    clickCounts[uniqueKey]++;
                                } else {
                                    clickCounts[uniqueKey] = 1;
                                }
                                
                                 uniqueData[uniqueKey] = {
                                        offer_id: offerId,
                                        offer_name: row.offer_name,
                                        country: country,
                                        sid: row.sid,
                                        sid2: row.sid2,
                                        sid3: row.sid3,
                                        sid4: row.sid4,
                                        sid5: row.sid5,
                                        ua_target: device,
                                        browser: browser,
                                        payout: row.publisher_earned,
                                        source: row.source,
                                    };
                                
                                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 totalPublisherEarned = 0.0;
                            let totalUniqueClicks = 0;
                            let totalConversion = 0;
                            let rowCount = 0;

                            let tableRow = $('<tr style="font-size: 15px;"></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: 15px;"></tr>');

                                newSelectedField.forEach(function (field) {

                                    let cellValue = data[field];

                                    if (field === 'publisher_earned') {
                                        cellValue = parseFloat(cellValue).toFixed(2);
                                        
                                        if (conversion === null || conversion === 0) {
                                             cellValue = "00";
                                        } else {
                                            // Multiply "payout" by "conversion" and display the result
                                            const publisherEarning = parseFloat(data.payout) * conversion;
                                            cellValue = publisherEarning;
                                            totalPublisherEarned += parseFloat(publisherEarning) || 0;
                                        }
                                    }else if (field === 'sid' || field === 'sid2' || field === 'sid3' || field === 'sid4' || field === 'sid5') {
                                        if (data[field] === null) {
                                            cellValue = "-";
                                        }
                                    }

                                    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(selectedCR){
                                    let conversionRate = (unique_click / conversion ? conversion : 1);
                                    const mainRate = (unique_click / conversionRate);
                                    if (conversionRate == 0){
                                        tableRow.append(`<td>${conversionRate.toFixed(0)}</td>`);
                                    }else{
                                        tableRow.append(`<td>1/${mainRate.toFixed(0)}</td>`);
                                    }
                                }

                                if(selectedCVR){
                                    const cvrParcentage = (conversion === 0) ? 0 : (conversion / click) * 100;
                                    tableRow.append(`<td>${cvrParcentage.toFixed(0)}%</td>`);
                                }

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

                                tableRows.push(tableRow);

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

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

                                    if(selectedCR){
                                        let conversionRate = (totalUniqueClicks / totalConversion);
                                        totalRowf.append(`<td>1/${conversionRate.toFixed(0)}</td>`);
                                    }

                                    if(selectedCVR){
                                        const cvrParcentage = (totalConversion === 0) ? 0 : (totalConversion / totalClicks) * 100;
                                        totalRowf.append(`<td>${cvrParcentage.toFixed(0)}%</td>`);
                                    }

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

                                    tableRows.push(totalRowf);
                                }
                            }

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

    });
</script>
@endsection