@extends('layout.app')
@section('content')
    <div class="card">
        <div class="card-body">
            @include('centeral.change_crm_status')

            <div class=" mb-1">

                <div class="col-lg-1" id="crm_pagination_link_top">
                    {{ $list->onEachSide(1)->links() }}
                </div>


                <input type="hidden" id="type" name="type" value="{{ $type }}">
                <div class="col-lg-10 d-flex justify-content-between counter">
                    @php($counter = crm_client_counter())
                    

                    <div
                        class="badge badge-success col-md-2 p-2 m-1 @if ($type == '') with-underline @endif ">
                        <div>
                            <a href="{{ route('crm-clients') }}">
                                <span class="text-white">Total: {{ $counter->sum('total') ?? 0 }}</span>
                            </a>
                        </div>
                    </div>
                    <div
                        class="badge badge-primary col-md-2 p-2  m-1 @if ($type == 'Marketing') with-underline @endif">
                        <a href="{{ route('crm-list', 'Marketing') }}">
                            <span class=" text-white"> Marketing:
                                {{ $counter->where('crm_status', 'Marketing')->first()->total ?? 0 }}</span>

                    </div>


                    <div
                        class="badge badge-secondary col-md-2 p-2  m-1 @if ($type == 'CRM') with-underline @endif">
                        <a href="{{ route('crm-list', 'CRM') }}">
                            <span class=" text-white">CRM:
                                {{ $counter->where('crm_status', 'CRM')->first()->total ?? 0 }}</span>

                    </div>

                    <div class="badge badge-info col-md-2 p-2  m-1 @if ($type == 'Support') with-underline @endif">
                        <a href="{{ route('crm-list', 'Support') }}">
                            <span class=" text-white">Support:
                                {{ $counter->where('crm_status', 'Support')->first()->total ?? 0 }}</span>

                    </div>

                    <div
                        class="badge badge-warning col-md-2 p-2  m-1 @if ($type == 'Account') with-underline @endif">
                        <a href="{{ route('crm-list', 'Account') }}">
                            <span class=" text-white">Account:
                                {{ $counter->where('crm_status', 'Account')->first()->total ?? 0 }}</span>

                    </div>

                    <div
                        class="badge badge-danger col-md-2 p-2  m-1 @if ($type == 'Fiber') with-underline @endif">
                        <a href="{{ route('crm-list', 'Fiber') }}">
                            <span class=" text-white">Fiber:
                                {{ $counter->where('crm_status', 'Fiber')->first()->total ?? 0 }}</span>

                    </div>

                    <div class="badge badge-dark col-md-2 p-2  m-1 @if ($type == 'Store') with-underline @endif">
                        <a href="{{ route('crm-list', 'Store') }}">
                            <span class=" text-white">Store:
                                {{ $counter->where('crm_status', 'Store')->first()->total ?? 0 }}</span>
                        </a>
                    </div>
                </div>

            </div>

            <div class="row mb-1" style="row-gap: 5px; margin-top:20px !important;padding-bottom:10px;">
                <div class="col-md-1">
                    <input type="text" id="id" placeholder="ID" name="id" class="form-control block">
                </div>
                <div class="col-md-2">
                    <input type="text" id="contact" placeholder="Contact" name="contact" class="form-control block">
                </div>
                <div class="col-md-2">
                    <input type="text" id="area" placeholder="Area" name="area" class="form-control block">
                </div>
                <div class="col-md-1">
                    <input type="text" id="box" placeholder="box" name="box" class="form-control block">
                </div>
                <div class="col-md-2">
                    <input type="text" id="customername" placeholder="Name/User Info" name="customername"
                        class="form-control block">
                </div>
                <div class="col-md-2">

                    <input type="text" id="customer_search" placeholder="Username" name="customer_search"
                        class="form-control block">
                </div>
                <div class="col-md-2">
                    <input type="date" name="crm_check_date" id="crm_check_date_new" class="form-control block">
                </div>
                <div class="col-md-2">
                    <select name="pop_id_crm" id="pop_id_crm" class="select2 form-control" required>
                        <option value="">Select Pop</option>
                        @foreach ($pop as $p)
                            <option class="p-5" data-billgenerate="{{ $p->bill_generate }}"
                                value="{{ $p->id }}">{{ $p->popname }}</option>
                        @endforeach

                    </select>
                </div>
                <div class="col-md-2">
                    <input type="date" name="crm_client_expire_date" id="crm_client_expire_date"
                        class="form-control block">
                </div>


                <a id="downloadCsvBtn" class="noprint btn btn-primary m-1" href="javascript:void(0)">
                    <i class="fa fa-print"></i> Download CSV
                </a>
            </div>


            <div id="processing">
                <div>Processing.....</div>
            </div>




            <div id="crm_customer_list_body">

                @include('clients.customer_search')
            </div>

        </div>







        <div class="card-footer" id="crm_pagination_link_bottom">

            {{ $list->onEachSide(1)->links() }}

        </div>


    </div>

    <style>
        div#processing {
            display: none;
        }

        .counter div {
            font-size: 15px;
        }

        .line-container::after {
            content: '';
            display: block;
            width: 100%;
            height: 1px;
            /* Adjust as needed */
            background-color: #333;
        }

        td {
            /* padding:5px!important; */
        }

        .with-underline {
            border-bottom: 5px solid #00FFFF;
            /* Adjust thickness and color as needed */
            padding-bottom: 5px;
            /* Adjust as needed to give some space between text and underline */
        }

        div#processing div {
            background: rgba(0, 0, 0, .5);
            position: fixed;
            width: 100vw;
            height: 100vh;
            color: #fff;
            text-align: center;
            vertical-align: middle;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        @media print {
            a {
                text-decoration: none !important;
                color: #222 !important;
            }

            th {
                font-size: 10px !important;
                padding: 2px !important;
                text-align: center;
            }

            tr {
                font-size: 10px !important;
                margin: 2px !important;
                padding: 2px !important;
            }

            td {
                font-size: 10px !important;
                margin: 2px !important;
                padding: 2px !important;
            }

            table {
                width: 100%;
            }

            .shadow {
                box-shadow: none;
            }

            tr th:last-child {
                display: none !important;
            }

            tr td:last-child {
                display: none !important;
            }

        }
    </style>
@endsection


@section('ajax')
    <script>
        $(function() {

            var timeout = null;


            $('#reset').click(function() {
                $('#result').html('');
                $('#pop').html('<option value="all">ALL POP</option>');
            });


            $('body').on('click', '.addOtc', function() {
                var id = $(this).attr('data-id');
                console.log(id, 'penidng');
                $('#addOtc .client_id').val(id);
            });


            $(document).on('click', '.clientBillCycleChange', function() {

                var id = $(this).attr('data-id');
                var billcycle = $(this).attr('data-curdate');

                // console.log(billcycle);
                $("select#allBillCycle option").each(function() {

                    if ($(this).val() == billcycle) { // EDITED THIS LINE
                        $(this).attr("selected", "selected");
                    }
                    $('.billingCycleChange').show();
                });


                $('#bill_client_id').val(id);

            });


        })




        // search section

        var typingTimer; //timer identifier
        var doneTypingInterval = 500; //time in ms (5 seconds)



        $('#customer_search').on('keyup', function() {
            clearTimeout(typingTimer);
            typingTimer = setTimeout(doneTyping, doneTypingInterval);

        });

        function doneTyping() {
            customersearch();
            clearTimeout(typingTimer);
        }

        $('#contact').on('keyup', function() {
            clearTimeout(typingTimer);
            typingTimer = setTimeout(doneTyping, doneTypingInterval);
        });

        $('#area').on('keyup', function() {
            clearTimeout(typingTimer);
            typingTimer = setTimeout(doneTyping, doneTypingInterval);
        });

        $('#box').on('keyup', function() {
            clearTimeout(typingTimer);
            typingTimer = setTimeout(doneTyping, doneTypingInterval);
        });

        $('#customername').on('keyup', function() {
            clearTimeout(typingTimer);
            typingTimer = setTimeout(doneTyping, doneTypingInterval);
        });

        $('#id').on('keyup', function() {
            // console.log('comes');
            clearTimeout(typingTimer);
            typingTimer = setTimeout(doneTyping, doneTypingInterval);
        });

        // $('#crm_check_date_new').on('change', function() {
        $(document).on("change", "#crm_check_date_new", function() {
            // console.log($this.val());
            // Log the value of the input field to the console
            clearTimeout(typingTimer);
            typingTimer = setTimeout(doneTyping, doneTypingInterval);
        });
        $(document).on("change", "#crm_client_expire_date", function() {
            console.log($('#crm_client_expire_date').val());
            // Log the value of the input field to the console
            clearTimeout(typingTimer);
            typingTimer = setTimeout(doneTyping, doneTypingInterval);
        });
        $(document).on("change", "#pop_id_crm", function() {
            // console.log($('#pop_id_crm').val());
            // Log the value of the input field to the console
            clearTimeout(typingTimer);
            typingTimer = setTimeout(doneTyping, doneTypingInterval);
        });



        function customersearch() {

            let name = $('#customer_search').val();
            let contact = $('#contact').val();
            let area = $('#area').val();
            let box = $('#box').val();
            let id = $('#id').val();
            let customername = $('#customername').val();
            let type = $('#type').val() ?? '';
            let crm_check_date = $('#crm_check_date_new').val() ?? '';
            let pop_id_crm = $('#pop_id_crm').val();
            let crm_client_expire_date = $('#crm_client_expire_date').val() ?? '';
            // console.log(crm_check_date);


            if (contact.length > 3 || area.length > 2 || box.length > 1 || customername.length > 2 || id.length > 1 || name
                .length > 0 || crm_check_date != null) {

                $.ajax({
                    type: 'get',
                    url: '{{ route('crm_customer_search') }}',
                    data: {
                        username: name,
                        contact: contact,
                        area: area,
                        box: box,
                        id: id,
                        customername: customername,
                        type: type,
                        crm_check_date: crm_check_date,
                        pop_id_crm: pop_id_crm,
                        crm_client_expire_date: crm_client_expire_date,

                    },
                    success: function(result) {
                        $('#result').html(result);
                        $('#crm_pagination_link_top').hide();
                        $('#crm_pagination_link_bottom').hide();
                        $('#processing').hide();
                    }
                });


            } else {
                // alert('Please tryp 3 character');
                $('#processing').hide();
            }
        }

        $(document).on("click", ".package_change_without_cost", function() {

            let client_id = $(this).data('clientid');

            $.ajax({
                type: 'get',
                url: '{{ route('getClientDetailsForPackageChange') }}',
                data: {
                    client_id: client_id
                },
                success: function(result) {
                    $('#package_change_without_cost_client_id').val(result.client.id);
                    $('#package_change_without_cost_client_name').val(result.client.clientsinfo
                        .clients_name);
                    $('#package_change_without_cost_package').empty();
                    $('#package_change_without_cost_package').append(
                        '<option value="">Select Package</option>');

                    if (result.client.pop.subreseller == 'yes') {
                        let client_packages = result.client.sub_package_id;
                        $.each(result.packages, function(key, value) {
                            if (client_packages == value.id) {
                                $('#package_change_without_cost_package').append(
                                    '<option value="' + value.id + '" selected>' + value
                                    .name + '</option>');
                            } else {

                                $('#package_change_without_cost_package').append(
                                    '<option value="' + value.id + '">' + value.name +
                                    '</option>');
                            }
                        });
                    } else {
                        let client_packages = result.client.package_id;
                        $.each(result.packages, function(key, value) {
                            if (client_packages == value.id) {
                                $('#package_change_without_cost_package').append(
                                    '<option value="' + value.id + '" selected>' + value
                                    .package_name + '</option>');
                            } else {

                                $('#package_change_without_cost_package').append(
                                    '<option value="' + value.id + '">' + value
                                    .package_name + '</option>');
                            }
                        });
                    }
                }
            });
        });


        $(document).on("click", ".package_change_action_btn", function() {

            let client_id = $(this).data('clientid');

            $.ajax({
                type: 'get',
                url: '{{ route('getClientDetailsForPackageChange') }}',
                data: {
                    client_id: client_id
                },
                success: function(result) {

                    $('#package_change_client_name').val(result.client.clientsinfo.clients_name);
                    $('#package_change_client_id').val(result.client.id);
                    $('#package_change_package').empty();
                    $('#package_change_package').append('<option value="">Select Package</option>');

                    if (result.client.pop.subreseller == 'yes') {
                        let client_packages = result.client.sub_package_id;
                        $.each(result.packages, function(key, value) {
                            if (client_packages == value.id) {
                                $('#package_change_package').append('<option value="' + value
                                    .id + '" selected>' + value.name + '</option>');
                            } else {

                                $('#package_change_package').append('<option value="' + value
                                    .id + '">' + value.name + '</option>');
                            }
                        });
                    } else {
                        let client_packages = result.client.package_id;
                        $.each(result.packages, function(key, value) {
                            if (client_packages == value.id) {
                                $('#package_change_package').append('<option value="' + value
                                    .id + '" selected>' + value.package_name + '</option>');
                            } else {

                                $('#package_change_package').append('<option value="' + value
                                    .id + '">' + value.package_name + '</option>');
                            }
                        });
                    }

                }
            });

        });



        $(document).ready(function() {
            $('#order-select').on('change', function() {
                updateTable();
            });

            function updateTable() {
                var selectedOption = $('#order-select').val();
                const $tbody = $('.product-table tbody');
                var rows = $tbody.find('tr').get();

                rows.sort(function(a, b) {
                    var aVal, bVal;

                    if (selectedOption === 'id_asc' || selectedOption === 'id_desc') {
                        aVal = $(a).find('td:first').text();
                        bVal = $(b).find('td:first').text();
                    } else {
                        aVal = $(a).find('td:nth-child(2)').text();
                        bVal = $(b).find('td:nth-child(2)').text();
                    }

                    if (selectedOption === 'id_asc' || selectedOption === 'name_asc') {
                        return (aVal > bVal) ? 1 : -1;
                    } else {
                        return (aVal < bVal) ? 1 : -1;
                    }
                });

                $.each(rows, function(index, row) {
                    $tbody.append(row);
                });
            }
        });

        $(document).on("click", ".crm_status_change", function() {
            let client_id = $(this).data('clientid');
            let crm_status = $(this).data('crmstatus'); // Corrected case

            $("#crm_status_current").val(crm_status);
            $("#crm_status_select").val(crm_status);
            $("#crm_status_change_client_id").val(client_id);

        });




        /*auto deactive date change start*/
        const autoDeactiveDateApply = function(cid) {
            const cidOfClient = document.getElementById(`autoDeactiveId-${cid}`);
            const autoDeactiveDate = cidOfClient.getAttribute('data-autodeactive');
            const deactiveModalPropertiesCid = document.getElementById("deactive_client_id");
            const deactiveModalPropertiesAutoDate = document.getElementById("deactiveDate");

            if (autoDeactiveDate !== '01-Jan-1970') {
                deactiveModalPropertiesAutoDate.setAttribute("value", autoDeactiveDate);
            }
            deactiveModalPropertiesCid.setAttribute("value", cid);

        }
        /*auto deactive date chnage end*/
    </script>
    <script>
        $(document).ready(function() {
            // Handle CSV download button click
            $('#downloadCsvBtn').on('click', function(e) {
                e.preventDefault();

                // Build query string from current filters
                var queryParams = [];

                // Add the type parameter - this is the key fix
                // Get it from the hidden input field that stores the current type
                var type = $('#type').val();
                if (type) {
                    queryParams.push('type=' + encodeURIComponent(type));
                }

                // Add all search parameters
                if ($('#id').val()) {
                    queryParams.push('id=' + encodeURIComponent($('#id').val()));
                }
                if ($('#customer_search').val()) {
                    queryParams.push('username=' + encodeURIComponent($('#customer_search').val()));
                }
                if ($('#pop_id_crm').val()) {
                    queryParams.push('pop_id_crm=' + encodeURIComponent($('#pop_id_crm').val()));
                }
                if ($('#contact').val()) {
                    queryParams.push('contact=' + encodeURIComponent($('#contact').val()));
                }
                if ($('#box').val()) {
                    queryParams.push('box=' + encodeURIComponent($('#box').val()));
                }
                if ($('#area').val()) {
                    queryParams.push('area=' + encodeURIComponent($('#area').val()));
                }
                if ($('#customername').val()) {
                    queryParams.push('customername=' + encodeURIComponent($('#customername').val()));
                }
                if ($('#crm_check_date_new').val()) {
                    queryParams.push('crm_check_date=' + encodeURIComponent($('#crm_check_date_new')
                .val()));
                }
                if ($('#crm_client_expire_date').val()) {
                    queryParams.push('crm_client_expire_date=' + encodeURIComponent($(
                        '#crm_client_expire_date').val()));
                }

                // Build final URL
                var csvUrl = '{{ route('crmClientListCsv') }}';
                if (queryParams.length > 0) {
                    csvUrl += '?' + queryParams.join('&');
                }

                // Redirect to download URL
                window.location.href = csvUrl;
            });
        });
    </script>
@endsection
