@extends('layouts.app')
@section('title', 'Lead Lists')
@section('content')

    <style>
        /* .table > thead > tr > td, .table > thead > tr > th {
                                                                                                                                                                                                                                                                        padding: 0.4rem;
                                                                                                                                                                                                                                                                        vertical-align: middle;
                                                                                                                                                                                                                                                                    } */
        /* Custom style for pagination links */
        .pagination {
            margin: 0;
            /* Remove default margin */
            padding: 0;
            /* Remove default padding */
            list-style: none;
            /* Remove list bullet points */
            display: flex;
            /* Use flex layout for horizontal alignment */
        }

        .pagination li a {
            padding: 6px;
        }

        .pagination a {
            display: inline-block;
            padding: 0;
            /* Adjust the padding as needed */
            text-decoration: none;
            background-color: #f0f0f0;
            border: 1px solid #ccc;
            color: #333;
            transition: background-color 0.3s ease, color 0.3s ease;
        }

        .pagination a:hover {
            background-color: #ccc;
            color: #fff;
        }

        .pagination .active a {
            background-color: #007bff;
            color: #fff;
        }
 .text-ends .other-buttons {
        flex: 1 0 100%;
        display: flex;
        flex-wrap: wrap;
        justify-content: flex-end;
        margin-top: 10px;
    }
@media (max-width: 768px) {
    .text-ends {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        justify-content: space-between;
    }

    /* Heading aur Add Lead same row me */
    .text-ends h4 {
        flex: 1;
        margin: 0;
    }

    .text-ends a.btn[href*="/leads/add"] {
        flex-shrink: 0;
        margin-left: auto;
    }

    /* Baaki buttons neeche ek row me */
    .text-ends a.btn:not([href*="/leads/add"]) {
        flex: unset;
        width: auto;
        margin: 5px 3px;
    }

    /* Container for neeche buttons */
    .text-ends .other-buttons {
        flex: 1 0 100%;
        display: flex;
        flex-wrap: wrap;
        justify-content: flex-start;
        margin-top: 10px;
    }
}

    </style>
    <?php
    
    error_reporting(0);
    $startDate = request()->input('start_date') ?? '';
    $endDate = request()->input('end_date') ?? '';
    
    ?>
    <section class="content">
        <div class="row">

            <div class="col-lg-12 col-12">
                <div class="box">

                    <div class="box-body"><!--bg-lightest-->
                      <div class="text-ends">
    <h4 class="box-title text-info mb-0" style="float:left;" id="show">
        <i class="icon-Add-user"><span class="path1"></span><span class="path2"></span></i> Leads
    </h4>

   

    <!-- Baaki buttons ek wrapper ke andar -->
    <div class="other-buttons">
         <a href="{{ url('/leads/add') }}" type="button" 
        class="waves-effect waves-light btn btn-rounded btn-primary btn-sm">
        <i class="fa fa-plus fa-sx"></i> Add Lead
    </a>
        <a id="affiliateLink" style="margin-right:5px;"
            class="waves-effect waves-light btn btn-rounded btn-primary btn-sm"
            onclick="copyToClipboard('<?php echo $domainName; ?>/affiliate/customer/user/app/index{{ Session::get('affilaite_link_token') }}')">
            <i class="fa fa-user fa-lg" aria-hidden="true"></i> Affiliate Link
        </a>

        @if (Session::get('parentId') == 3 || Session::get('parentId') == 11)
            <a class="waves-effect waves-light btn btn-rounded btn-primary btn-sm"
                href="/pdf-reader-setting"> Pdf Setting </a>

            <a class="waves-effect waves-light btn btn-rounded btn-primary btn-sm" id="openExcelForm">
                Upload Pdf </a>
        @endif

        <a style="margin-right:5px;" class="waves-effect waves-light btn btn-rounded btn-primary btn-bitbucket btn-sm"
            aria-controls="answer-1" aria-expanded="false" data-bs-toggle="collapse" href="#answer-1"
            data-parent="#accordion2">
            <i class="fa fa-search fa-lg" aria-hidden="true"></i> Filter
        </a>
    </div>
    
</div>

                        <div class="panel-group panel-group-simple panel-group-continuous mb-0" id="accordion2"
                            aria-multiselectable="true" role="tablist">
                            <!-- Question 1 -->
                            <div class="panel">
                                <div id="question-1" role="tab">

                                </div>
                                <div class="panel-collapse collapse  " id="answer-1" aria-labelledby="question-1"
                                    role="tabpanel" data-bs-parent="#category-1">
                                    <div class="panel-body">
                                        <form method="post">
                                            @csrf
                                            <div class="row">

                                           <div class="form-group col-md-3">
                                                <label class="form-label">MID</label>
                                                    <div class="input-group">
                                                    <span class="input-group-text @error('first_name') text-danger border-danger @enderror"><i class="ti-user"></i></span>

                                                        <input class="form-control " value="{{request()->input('lead_id')}}" name="lead_id" id="" placeholder="MID">
                                                    </div>
                                            </div>

                                                <div class="form-group col-md-3">
                                                    <label class="form-label">First Name</label>
                                                    <div class="input-group">
                                                        <span
                                                            class="input-group-text @error('first_name') text-danger border-danger @enderror"><i
                                                                class="ti-user"></i></span>

                                                        <input class="form-control "
                                                            value="{{ request()->input('first_name') }}" name="first_name"
                                                            id="" placeholder="First Name">
                                                    </div>
                                                </div>
                                                <div class="form-group col-md-3">
                                                    <label class="form-label">Last Name</label>
                                                    <div class="input-group">
                                                        <span
                                                            class="input-group-text @error('last_name') text-danger border-danger @enderror"><i
                                                                class="ti-user"></i></span>

                                                        <input class="form-control "
                                                            value="{{ request()->input('last_name') }}" name="last_name"
                                                            id="" placeholder="Last Name">
                                                    </div>
                                                </div>
                                                <div class="col-md-3">
                                                    <div class="form-group">
                                                        <label class="form-label">DBA</label>
                                                        <input type="text" class="form-control "
                                                            value="{{ request()->input('dba') }}" name="dba"
                                                            id="dba" placeholder="DBA">
                                                    </div>
                                                </div>

                                                <div class="form-group col-md-3">
                                                    <label class="form-label">Phone Number</label>
                                                    <div class="input-group">
                                                        <span
                                                            class="input-group-text @error('phone_number') text-danger border-danger @enderror"><i
                                                                class="ti-user"></i></span>

                                                        <input class="form-control "
                                                            value="{{ request()->input('phone_number') }}"
                                                            name="phone_number" id="phone_number"
                                                            placeholder="Phone Number">
                                                        <!-- <input class="form-control" data-inputmask="'mask':[ '(999) 999-9999']" data-mask  value="{{ request()->input('phone_number') }}" name="phone_number" id="phone_number" placeholder="Phone Number"> -->

                                                    </div>
                                                </div>
                                                <div class="form-group col-md-3">
                                                    <label class="form-label">Email</label>
                                                    <div class="input-group">
                                                        <span
                                                            class="input-group-text @error('email') text-danger border-danger @enderror"><i
                                                                class="ti-user"></i></span>

                                                        <input type="email"class="form-control "
                                                            value="{{ request()->input('email') }}" name="email"
                                                            id="email" placeholder="Email">
                                                    </div>
                                                </div>
                                                <div class="form-group col-md-3">
                                                    <label class="form-label">Company Name</label>
                                                    <div class="input-group">
                                                        <span
                                                            class="input-group-text @error('company_name') text-danger border-danger @enderror"><i
                                                                class="ti-user"></i></span>

                                                        <input class="form-control "
                                                            value="{{ request()->input('company_name') }}"
                                                            name="company_name" id="company_name"
                                                            placeholder="Company Name">
                                                    </div>
                                                </div>
                                                <div class="form-group col-md-3">
                                                    <label class="form-label">Lead Status</label>
                                                    <div class="input-group">
                                                        <select class="select2 form-control" name="lead_status[]"
                                                            id="lead_status" multiple="multiple" style="width:100%">
                                                            @if (!empty($lead_status))
                                                                @foreach ($lead_status as $status)
                                                                    <option
                                                                        @if (empty(request()->input('lead_status'))) @elseif(in_array($status->lead_title_url, request()->input('lead_status'))) selected @endif
                                                                        value="{{ $status->lead_title_url }}">
                                                                        {{ $status->title }}</option>
                                                                @endforeach
                                                            @endif
                                                        </select>
                                                    </div>
                                                </div>
                                                <div class="form-group col-md-3">
                                                    <label class="form-label">Assigned to</label>
                                                    <div class="input-group">
                                                        <select class="select2 form-control" name="assigned_to[]"
                                                            id="assigned_to" multiple="multiple" style="width:100%">
                                                            @if (Session::get('level') > 5)

                                                                @if (!empty($user))
                                                                    @foreach ($sortedUsers as $list)
                                                                        @if ($list->is_deleted == '0' && $list->user_level < 9)
                                                                            <option
                                                                                @if (empty(request()->input('assigned_to'))) @elseif(in_array($list->id, request()->input('assigned_to'))) selected @endif
                                                                                value="{{ $list->id }}">
                                                                                {{ ucwords($list->first_name) }}
                                                                                {{ ucwords($list->last_name) }}</option>
                                                                        @endif
                                                                    @endforeach
                                                                @endif
                                                            @else
                                                                <option value="{{ Session::get('id') }}">
                                                                    {{ Session::get('first_name') }}
                                                                    {{ Session::get('last_name') }}</option>

                                                            @endif
                                                        </select>
                                                    </div>
                                                </div>
                                                <div class="form-group col-md-3">
                                                    <label class="form-label">Lead Type</label>
                                                    <div class="input-group">
                                                        <select class="select2 form-control" name="lead_type[]"
                                                            id="lead_type" multiple="multiple" style="width:100%">
                                                            <option
                                                                @if (empty(request()->input('lead_type'))) @elseif(in_array('hot', request()->input('lead_type'))) selected @endif
                                                                value="hot">Hot</option>
                                                            <option
                                                                @if (empty(request()->input('lead_type'))) @elseif(in_array('warm', request()->input('lead_type'))) selected @endif
                                                                value="warm">Warm</option>
                                                            <option
                                                                @if (empty(request()->input('lead_type'))) @elseif(in_array('cold', request()->input('lead_type'))) selected @endif
                                                                value="cold">Cold</option>
                                                        </select>
                                                    </div>
                                                </div>
                                                <div class="form-group col-md-3">

                                                    <label class="form-label">Date Range</label>
                                                    <div class="input-group">
                                                        <div class="input-group-addon">
                                                            <i class="fa fa-calendar"></i>
                                                        </div>
                                                        <input type="text" class="form-control pull-right"
                                                            id="reservation">
                                                        <input type="hidden" id="start_date" name="start_date"
                                                            value="{{ $startDate }}">
                                                        <input type="hidden" id="end_date" name="end_date"
                                                            value="{{ $endDate }}">
                                                    </div>
                                                </div>
                                                <div class="box-footer text-end">


                                                    <a onclick="resetFilter();" class="btn btn-danger me-1">
                                                        <i class="ti-reload"></i> Reset
                                                    </a>

                                                    <button type="submit" name="submit" value="add"
                                                        class="btn btn-primary">
                                                        <i class="ti-save-alt"></i> Submit
                                                    </button>
                                                </div>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- End Question 1 -->
                    </div>


                    <div class="row">
                        <h4 class="box-title text-info mb-0"style="display:none;" id="hide"><i
                                class="icon-Add-user"><span class="path1"></span><span class="path2"></span></i> Leads
                        </h4>
                        <hr class="my-15">
                        <!-- <b>Total Rows :<?= $record_count ?></b> -->
                        {{-- <form method="GET" action="">
                            <div style="text-align:right;">
                                <label class="form-label"style="margin-top:5px;">Search:</label>
                                <input class="form-control form-control-sm"type="search" name="search"id="search"
                                    placeholder=""value="{{ $searchTerm }}"
                                    style="width:auto;float:right;margin-left:0.5em;display:inline-block;margin:0 10px;padding: 5px 30px 5px 15px;">
                                <!-- <button type="submit"><i class="fa fa-search"></i></button> -->
                            </div>
                            <label class="label-class" for="show">Show:</label>
                            <select class="form-select form-control-sm"name="show"
                                onchange="this.form.submit()"style="width:75px;display:inline-block;">
                                <option value="10" {{ request('show') == 10 ? 'selected' : '' }}selected>10</option>
                                <option value="25" {{ request('show') == 25 ? 'selected' : '' }}>25</option>
                                <option value="50" {{ request('show') == 50 ? 'selected' : '' }}>50</option>
                                <option value="100" {{ request('show') == 100 ? 'selected' : '' }}>100</option>
                            </select>
                            <label for="entries">entries</label>

                        </form> --}}
                        <div class="table-responsive">
                            <table class="table mt-0 table-hover" id="myTable">
                                <thead id="tableHeaderRow">

                                </thead>

                                <?php //echo "<pre>";print_r($leads);die;
                                ?>

                                <tbody>

                                </tbody>
                            </table>
                        </div>

                    </div>

                    {{-- <div style="float:right;">
                        {{ $paginator->appends(Request::all())->links() }}
                    </div> --}}
                </div>

            </div>
            <!-- /.box-body -->

            <!-- /.box -->

            <div class="modal fade" id="delete" tabindex="-1" aria-labelledby="deleteLabel" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="myModalLabel">Confirm Delete</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"
                                aria-label="Close"></button>
                        </div>


                        <div class="modal-body">
                            <p>You are about to delete <b><i class="title"></i></b> lead.</p>
                            <p>Do you want to proceed?</p>
                            <input type="hidden" class="form-control" name="lead_id" value="" id="lead_id">

                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary btn-sm"
                                data-bs-dismiss="modal">Close</button>
                            <button type="submit" class="btn btn-danger btn-ok btn-sm deleteLead">Delete</button>
                        </div>
                    </div>
                </div>
            </div>

        </div>

    </section>

    <div class="modal fade" id="myModalExcel" tabindex="-1" aria-labelledby="myModalExcelLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="upload-excel"></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>

                <form method="post" action="{{ url('pdf/uploadDid') }}" enctype="multipart/form-data">
                    <!-- <form id="uploadForm"method="post" action="{{ url('pdf/uploadDid') }}" enctype="multipart/form-data"> -->
                    @csrf
                    <div class="modal-body">
                        <div id="loader" style="display: none;">
                            <img src="{{ asset('assets/images/giphy.gif') }}"
                                alt="Loading..."style="height:100px;width:100px;">
                        </div>
                        <input type="hidden" class="form-control" name="did" value="">
                        <label for="inputEmail3" class="form-label closed">PDF</label>
                        <input type="file" accept=".pdf" class="form-control closed" required name="did_file"
                            id="did_file" placeholder="Select PDF File">
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Close</button>
                        <button type="submit"name="submit" class="btn btn-info btn-sm ">Upload</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    @push('styles')
        <link rel="stylesheet" type="text/css"
            href="{{ asset('assets/plugins/dashboard_date/bootstrap-datepicker.min.css') }}">
        <link rel="stylesheet" type="text/css" href="{{ asset('assets/plugins/dashboard_date/bootstrap-datepicker.css') }}">
    @endpush

    @push('scripts')
        <!-- Vendor JS -->

        <script src="{{ asset('assets/plugins/dashboard_date/moment.min.js') }}"></script>
        <script src="{{ asset('assets/plugins/dashboard_date/bootstrap-datepicker.min.js') }}"></script>
        <script src="{{ asset('assets/plugins/dashboard_date/daterangepicker.js') }}"></script>



        <script>
            document.addEventListener('DOMContentLoaded', function() {
                var searchButton = document.querySelector('.btn-bitbucket');
                var collapseElement = new bootstrap.Collapse(document.getElementById('answer-1'), {
                    toggle: false
                });
                var leadsHeading = document.getElementById('hide');
                var leadsHeadingShow = document.getElementById('show');

                // Function to check the conditions for opening the form
                function shouldOpenForm() {
                    // Check the specified conditions
                    return (
                        {!! json_encode(
                            !empty(request()->input('lead_status')) ||
                                !empty(request()->input('assigned_to')) ||
                                !empty(request()->input('first_name')) ||
                                !empty(request()->input('last_name')) ||
                                !empty(request()->input('email')) ||
                                !empty(request()->input('legal_company_name')) ||
                                !empty(request()->input('lead_type')) ||
                                !empty(request()->input('phone_number')) ||
                                !empty(request()->input('start_date')) ||
                                !empty(request()->input('end_date')),
                        ) !!}
                    );
                }

                // Check conditions when the page loads
                if (shouldOpenForm()) {
                    collapseElement.show();
                    leadsHeading.style.display = 'block';
                    leadsHeadingShow.style.display = 'none';
                }

                searchButton.addEventListener('click', function(event) {
                    event.preventDefault(); // Prevent the default behavior of the anchor link

                    var formFields = document.querySelectorAll(
                        '#answer-1 input, #answer-1 select, #answer-1 textarea');

                    // Check if any field in the form is not empty
                    var isAnyFieldNotEmpty = Array.from(formFields).some(function(field) {
                        return field.value.trim() !== '';
                    });

                    if (isAnyFieldNotEmpty || shouldOpenForm()) {
                        // If any field is not empty or specified conditions are met, keep the form open
                        collapseElement.show();
                        leadsHeading.style.display = 'block';
                        leadsHeadingShow.style.display = 'none';
                    } else {
                        // If all fields are empty and conditions are not met, toggle the form visibility
                        collapseElement.toggle();
                    }
                });

                // Add an event listener for Bootstrap Collapse events
                collapseElement._element.addEventListener('hidden.bs.collapse', function() {
                    leadsHeading.style.display = 'none'; // Hide the heading when the form is collapsed
                    leadsHeadingShow.style.display =
                        'block'; // Show the alternate heading when the form is collapsed
                });

                collapseElement._element.addEventListener('shown.bs.collapse', function() {
                    leadsHeading.style.display = 'block'; // Show the heading when the form is expanded
                    leadsHeadingShow.style.display =
                        'none'; // Hide the alternate heading when the form is expanded
                });
            });
        </script>


        <script>
            function copyToClipboard(textToCopy) {
                // Create a temporary textarea element
                var textarea = document.createElement('textarea');
                textarea.value = textToCopy;
                document.body.appendChild(textarea);

                // Select and copy the text
                textarea.select();
                document.execCommand('copy');

                // Remove the temporary textarea
                document.body.removeChild(textarea);

                // Show the message in the 'msg' element
                var msgElement = document.getElementById('msg');
                msgElement.style.display = 'inline'; // Make the element visible
                setTimeout(function() {
                    msgElement.style.display = 'none'; // Hide the element after a delay (e.g., 3 seconds)
                }, 3000); // Adjust the delay in milliseconds (3 seconds in this example)
            }
        </script>
        <script src="https://cdn.jsdelivr.net/npm/imask"></script>
        <script>
            document.addEventListener('DOMContentLoaded', function() {
                // Get the phone number input
                var phoneInput = document.getElementById('phone_number');

                // Create an IMask instance with the desired mask
                var phoneMask = new IMask(phoneInput, {
                    mask: '(000) 000-0000'
                });

                // Add a submit event listener to set the unmasked value before form submission
                document.querySelector('form').addEventListener('submit', function() {
                    // Get the unmasked value
                    var unmaskedValue = phoneMask.unmaskedValue;

                    // Set the unmasked value to the actual input field
                    phoneInput.value = unmaskedValue;
                });
            });
        </script>
        <script type="text/javascript">
            $(function() {
                var startDate = "{{ $startDate }}";
                var endDate = "{{ $endDate }}";

                // Log the startDate and endDate for debugging purposes
                console.log("Start Date: ", startDate);
                console.log("End Date: ", endDate);

                $('#reservation').daterangepicker({
                    locale: {
                        format: 'MM/DD/YYYY'
                    },
                    autoUpdateInput: false, // Prevent auto-filling the input field
                    opens: 'right'
                }, function(start, end) {
                    $('#start_date').val(start.format('MM/DD/YYYY'));
                    $('#end_date').val(end.format('MM/DD/YYYY'));
                    $('#reservation').val(start.format('MM/DD/YYYY') + ' - ' + end.format(
                        'MM/DD/YYYY')); // Update the input field with the selected date range
                });

                // If both start and end dates are provided, set them in the input field
                if (startDate && endDate) {
                    $('#reservation').data('daterangepicker').setStartDate(startDate);
                    $('#reservation').data('daterangepicker').setEndDate(endDate);
                    $('#reservation').val(startDate + ' - ' + endDate);
                } else {
                    $('#reservation').val(''); // Ensure the input field is empty initially
                }
            });
        </script>
        <script>
            $(document).ready(function() {
                $('#uploadForm').submit(function(e) {
                    e.preventDefault(); // Prevent the default form submission

                    // Show the loader
                    $('#loader').show();
                    var fileInput = $('#did_file')[0]; // Get the file input element
                    var file = fileInput.files[0]; // Get the selected file

                    // Check if a file was selected and if it's a PDF
                    if (file) {
                        var fileType = file.type; // Get the file MIME type

                        // Check if the file is a PDF (MIME type: application/pdf)
                        if (fileType !== 'application/pdf') {
                            toastr.error('Please upload a valid PDF file.');
                            // Close the modal
                            $('#uploadForm')[0].reset();
                            $('#loader').hide(); // Hide the loader
                            return; // Stop the form submission
                        }
                    } else {
                        toastr.error('Please select a file to upload.');
                        $('#loader').hide(); // Hide the loader
                        return; // Stop the form submission
                    }
                    var formData = new FormData(this); // Get form data (including the file)

                    $.ajax({
                        url: '{{ url('pdf/uploadDid') }}', // Form action URL
                        type: 'POST',
                        data: formData,
                        contentType: false, // Don't set content-type header
                        processData: false, // Don't process the data (it needs to be sent as FormData)
                        success: function(response) {
                            // Hide the loader
                            $('#loader').hide();
                            $('#myModalExcel').modal(
                                'hide'); // Assuming the modal has the id 'uploadModal'
                            // Handle success (you can display a success message or update the UI)
                            toastr.success('File uploaded successfully!');
                            console.log(
                                response
                            ); // Log the response (you can use it to show any additional message)
                            // Optionally, reset the form here
                            $('#uploadForm')[0].reset();
                        },
                        error: function(xhr, status, error) {
                            // Hide the loader
                            $('#loader').hide();

                            // Handle error (you can display an error message)
                            alert('An error occurred while uploading the file.');
                            console.log(xhr.responseText); // Log the error
                        }
                    });
                });
            });
        </script>
        <script>
            function resetFilter() {
                // Remove query parameters from the URL before refreshing
                history.replaceState(null, null, window.location.pathname);

                // Refresh the page
                location.reload();
            }
        </script>
        <script>
            document.addEventListener("DOMContentLoaded", function() {
                window.sortTable = function(columnIndex, header) {
                    const table = document.getElementById("myTable");
                    if (!table) {
                        console.error("Table with ID 'myTable' not found.");
                        return;
                    }

                    const rows = Array.from(table.tBodies[0].rows);
                    const isAsc = header.classList.contains("asc");

                    // Reset sort icons
                    document.querySelectorAll("th").forEach(th => {
                        th.classList.remove("asc", "desc");
                        const icon = th.querySelector("i");
                        const label = th.querySelector(".sort-label");
                        if (icon) icon.className = "fa fa-sort";
                        if (label) label.textContent = "Sort";
                    });

                    rows.sort((a, b) => {
                        const A = a.cells[columnIndex].innerText.toLowerCase();
                        const B = b.cells[columnIndex].innerText.toLowerCase();
                        return isAsc ? B.localeCompare(A) : A.localeCompare(B);
                    });

                    rows.forEach(row => table.tBodies[0].appendChild(row));

                    header.classList.toggle("asc", !isAsc);
                    header.classList.toggle("desc", isAsc);

                    const icon = header.querySelector("i");
                    const label = header.querySelector(".sort-label");
                    if (icon) icon.className = isAsc ? "fa fa-sort-desc" : "fa fa-sort-asc";
                    if (label) label.textContent = isAsc ? "Descending" : "Ascending";
                };
            });
        </script>

        <!-- <script>
            $(document).ready(function() {
                $.ajax({
                    url: '/leads', // your route here
                    type: 'GET',
                    dataType: 'json',
                    success: function(response) {
                        // Build table headers dynamically
                        // let headerHtml = '<th>#</th>'; // Index column

                        // response.lead_view.forEach(function(col) {
                        //     headerHtml += '<th>' + col.title + '</th>';
                        // });

                        // headerHtml +=
                        //     '<th>Status</th><th>Sub Lead</th><th>Created</th><th>Modified</th><th>Assigned To</th> <th>Action</th>'; // fixed columns



                        // $('#tableHeaderRow').html(headerHtml);

                        // Build DataTable columns dynamically
                        let columns = [];

                        // Index column with row number
                        // columns.push({
                        //     data: null,
                        //     title: '#',
                        //     orderable: false,
                        //     searchable: false,
                        //     render: function(data, type, row, meta) {
                        //         return meta.row + 1;
                        //     }
                        // });

                        columns.push({
                            data: 'id',
                            title: '#',
                            orderable: false,
                            searchable: false,
                            render: function(data) {
                                return data; // render raw HTML
                            }
                        });



                        // Add dynamic columns from lead_view
                        $.each(response.lead_view, function(i, col) {
                            console.log(col.title);
                            columns.push({
                                data: col.column_name,
                                title: col.title,
                                render: function(data, type, row) {
                                    if (col.data_type === 'currency' && data !== null) {
                                        return parseFloat(data).toLocaleString(
                                            undefined, {
                                                minimumFractionDigits: 2
                                            });
                                    } else if (col.data_type === 'date' && data) {
                                        let date = new Date(data);
                                        return date.toLocaleDateString() + ' ' + date
                                            .toLocaleTimeString();
                                    }  else if (col.data_type === 'phone_number' && data) {
                                            // Format phone number (US style: (999) 999-9999)
                                            let digits = data.replace(/\D/g, '');
                                            if (digits.length === 10) {
                                                return '(' + digits.substring(0, 3) + ') ' +
                                                    digits.substring(3, 6) + '-' +
                                                    digits.substring(6);
                                            }
                                            return data; // fallback if not 10 digits
                                        }

                                    return data !== null ? data : '';
                                }
                            });
                        });


                        // Status column (contains HTML badges)
                        columns.push({
                            data: 'lead_status',
                            title: 'Status',
                            orderable: false,
                            searchable: false,
                            render: function(data) {
                                return data; // render raw HTML
                            }
                        });

                        columns.push({
                            data: 'lead_parent_id',
                            title: 'Sub Lead',
                            render: function(data, type, row) {
                                if (data !== '0' && data !== 0 && data !== null) {
                                    return 'Sub Lead of MID- <a href="/leads/view?id=' + data +
                                        '">' + data + '</a>';
                                }
                                return '';
                            }
                        });
                        columns.push({
                            data: 'created_at',
                            title: 'Created',
                            orderable: false,
                            searchable: false,
                            render: function(data) {
                                return data; // render raw HTML
                            }
                        });
                        columns.push({
                            data: 'updated_at',
                            title: 'Modified',
                            orderable: false,
                            searchable: false,
                            render: function(data) {
                                return data; // render raw HTML
                            }
                        });


                        columns.push({
                            data: 'assigned_to_user',
                            title: 'Assigned to',
                            orderable: false,
                            searchable: false,
                            render: function(data) {
                                return data; // render raw HTML
                            }
                        });

                        @if (Session::get('level') > 5)
                            columns.push({
                                data: 'created_by_user', // Adjust this to your actual data field
                                title: 'Created By',
                            });
                        @endif
                        // Action column (buttons)
                        columns.push({
                            data: 'action',
                            title: 'Action',
                            orderable: false,
                            searchable: false,
                            render: function(data) {
                                return data; // render raw HTML
                            }
                        });
                        $('#myTable').DataTable({
                            processing: true,
                            serverSide: false,
                            data: response.data,
                            columns: columns,
                            responsive: false, // 🔥 disable responsive behavior
                            autoWidth: false, // optional: don't automatically calculate column width
                            scrollX: true, // 🔥 allow horizontal scroll instead of collapsing
                            pageLength: 10
                        });

                        // Initialize DataTable
                        // $('#myTable').DataTable({
                        //     processing: true,
                        //     serverSide: false, // false because you send all data at once
                        //     data: response.data,
                        //     columns: columns,
                        //     order: [
                        //         [0, 'asc']
                        //     ],
                        //     pageLength: 10,
                        //     lengthChange: true,
                        //     responsive: true,


                        // });


                    },
                    error: function(xhr, status, error) {
                        console.error('Failed to load leads data:', error);
                    }
                });

                $('#myTable').on('click', '.openLeadDelete', function() {
                    var delete_id = $(this).data('id');
                    $("#delete").modal('show');
                    $("#lead_id").val(delete_id);
                });
            });
        </script> -->
<script>
$(document).ready(function () {
    // First AJAX to build columns
    $.ajax({
        url: '/leads',
        type: 'GET',
        dataType: 'json',
        success: function (response) {

            let columns = [];

            // ID column
            columns.push({
                data: 'id',
                title: '#',
                orderable: false,
                searchable: false,
                render: function (data) {
                    return data;
                }
            });

            // Dynamic columns
            $.each(response.lead_view, function (i, col) {
                columns.push({
                    data: col.column_name,
                    title: col.title,
                    render: function (data, type, row) {
                        if (col.data_type === 'currency' && data !== null) {
                            return parseFloat(data).toLocaleString(undefined, { minimumFractionDigits: 2 });
                        } else if (col.data_type === 'date' && data) {
                            let date = new Date(data);
                            return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
                        } else if (col.data_type === 'phone_number' && data) {
                            let digits = data.replace(/\D/g, '');
                            if (digits.length === 10) {
                                return '(' + digits.substring(0, 3) + ') ' +
                                       digits.substring(3, 6) + '-' +
                                       digits.substring(6);
                            }
                            return data;
                        }
                        return data !== null ? data : '';
                    }
                });
            });

            // Status
            columns.push({
                data: 'lead_status',
                title: 'Status',
                orderable: false,
                searchable: false
            });

            // Sub Lead
            columns.push({
                data: 'lead_parent_id',
                title: 'Sub Lead',
                render: function (data, type, row) {
                    if (data !== '0' && data !== 0 && data !== null) {
                        return 'Sub Lead of MID- <a href="/leads/view?id=' + data + '">' + data + '</a>';
                    }
                    return '';
                }
            });

            // Created / Modified
            columns.push({ data: 'created_at', title: 'Created' });
            columns.push({ data: 'updated_at', title: 'Modified' });

            // Assigned
            columns.push({ data: 'assigned_to_user', title: 'Assigned to' });

            // Created By (if session level > 5)
            @if (Session::get('level') > 5)
            columns.push({ data: 'created_by_user', title: 'Created By' });
            @endif

            // Action
            columns.push({
                data: 'action',
                title: 'Action',
                orderable: false,
                searchable: false
            });

            // ✅ Initialize DataTable
            let table = $('#myTable').DataTable({
                processing: true,
                serverSide: false,
                ajax: {
                    url: '/leads',
                    type: 'GET',
                    data: function (d) {
                        // attach filter form inputs
                        d.lead_id      = $('input[name="lead_id"]').val();
                        d.first_name   = $('input[name="first_name"]').val();
                        d.last_name    = $('input[name="last_name"]').val();
                        d.dba          = $('input[name="dba"]').val();
                        d.phone_number = $('input[name="phone_number"]').val();
                        d.email        = $('input[name="email"]').val();
                        d.company_name = $('input[name="company_name"]').val();
                        d.lead_status  = $('#lead_status').val();
                        d.assigned_to  = $('#assigned_to').val();
                        d.lead_type    = $('#lead_type').val();
                        d.start_date   = $('#start_date').val();
                        d.end_date     = $('#end_date').val();
                    },
                    dataSrc: 'data'
                },
                columns: columns,
                scrollX: true,
                autoWidth: false,
                pageLength: 10,

language: {
    processing: `
        <span style="display:flex; align-items:center; justify-content:center; gap:8px;">
            <img src="https://i.gifer.com/ZZ5H.gif"
                 alt="Loading..." style="width:20px; height:20px;">
            Processing...
        </span>
    `
}
            });

            // Filter submit
            $('#filterForm').on('submit', function (e) {
                e.preventDefault();
                table.ajax.reload();
            });

            // Reset
            $('#resetFilters').on('click', function () {
                $('#filterForm')[0].reset();
                table.ajax.reload();
            });

            // Delete modal
            $('#myTable').on('click', '.openLeadDelete', function () {
                var delete_id = $(this).data('id');
                $("#delete").modal('show');
                $("#lead_id").val(delete_id);
            });

        },
        error: function (xhr, status, error) {
            console.error('Failed to load leads config:', error);
        }
    });
});
</script>


        <script>
            var parentId = "{{ Session::get('parentId') }}";

            $("#openExcelForm").click(function() {
                console.log('did_file');
                $("#myModalExcel").modal('show');
                $("#name").val('');
                $("#status").val('1');
                $("#id").val('');
                $(".closed").show();
                $("#upload-excel").html('Upload PDF');


            });
            $(".openLeadDelete").click(function() {
                var delete_id = $(this).data('id');
                $("#delete").modal('show');
                $("#lead_id").val(delete_id);
            });
            $(document).on("click", ".deleteLead", function() {
                var lead_id = $('#lead_id').val();
                $.ajax({
                    url: 'deleteLead/' + lead_id,
                    type: 'get',
                    success: function(response) {
                        window.location.reload(1);
                    }
                });
            });

            $(document).on("click", ".create-cred", function() {
                var email = $(this).data('email');
                var clientId = parentId;
                var leadId = $(this).data('id');

                $.ajax({
                    url: 'merchant-add',
                    type: 'POST',
                    data: {
                        "email": email,
                        "client_id": clientId,
                        "lead_id": leadId
                    },
                    success: function(response) {
                        if (response.success == false) {
                            $.each(response.errors, function(key, valueObj) {
                                toastr.error(valueObj[0]);
                            });
                        } else {
                            $("#create-cred-" + leadId).hide();
                            toastr.success(response.message)
                        }
                    }
                });
            });

            //  $(document).ready(function() {

            //     $('#reservation').daterangepicker({
            //     locale: { format: 'MM/DD/YYYY' },
            //     "startDate": "{{ \App\Helper\Helper::formatDateMMDDYYYY($startDate) }}",
            //     "endDate": "{{ \App\Helper\Helper::formatDateMMDDYYYY($endDate) }}",
            //     opens: 'right'
            // }, function(start, end, label) {
            //     console.log('New date range selected: ' + start.format('MM/DD/YYYY') + ' to ' + end.format('MM/DD/YYYY') + ' (predefined range: ' + label + ')');
            //     $("#start_date").val(start.format('MM/DD/YYYY'));
            //     $("#end_date").val(end.format('MM/DD/YYYY'));
            // });

            //     // Check if start date and end date are empty, if so, clear the input fields
            //     if ("{{ $startDate }}" === '') {
            //         $("#start_date").val('');
            //     }

            //     if ("{{ $endDate }}" === '') {
            //         $("#end_date").val('');
            //     }
            // });

            $(document).ready(function() {
                $('#tickets1').DataTable({
                    order: [
                        [0, 'desc']
                    ],

                    columnDefs: [{
                            targets: [2, 3, 4, 5, 7, 8, 9, 10], // Columns to disable sorting
                            orderable: false
                        },
                        {
                            targets: [1, 6], // Name column, enable sorting
                            orderable: true
                        }
                    ]
                });
            });
        </script>
    @endpush

@endsection
