@extends('layout.app')
@section('styles')
    <style>
        /* Fixed header styling */
        .table-responsive {
            max-height: calc(100vh - 400px);
            /* Adjust based on your layout */
            overflow-y: auto;
            position: relative;
        }

        #dataTable thead th {
            position: sticky;
            top: 0;
            background-color: #343a40 !important;
            /* Match thead-dark color */
            z-index: 10;
            border-top: 1px solid #454d55;
            border-bottom: 2px solid #454d55;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
        }

        /* Ensure text stays white on dark header */
        #dataTable thead th {
            color: #fff !important;
        }

        .follow-up-row {
            background-color: #fff3cd !important;
            border-left: 4px solid #ffc107 !important;
        }

        .follow-up-row td:first-child {
            font-weight: bold;
        }
    </style>

    <style>
        .dropdown-menu.action-dropdown-menu {
            max-height: 50vh;
            overflow-y: auto;
            overflow-x: hidden;
        }
    </style>
@endsection
@section('content')
    <div class="container-fluid">

        @if (session('error'))
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <strong>Wait!</strong> {{ session('error') }}
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
        @endif
        <div class="row mb-3">
            <div class="col-12 text-right">
                <a href="{{ route('newline.newCreate') }}" class="btn btn-info btn-sm">
                    <i class="fas fa-plus"></i> Create New Request
                </a>
            </div>
        </div>

        <div class="card">
            <div class="card-header">
                <h4 class="card-title">Search New Line Requests</h4>
            </div>

            <div class="card-body">
                <form action="{{ route('newline.newIndex') }}" method="GET">
                    <div class="row">
                        <div class="col-md-2">
                            <div class="form-group">
                                <label>ID</label>
                                <input type="text" name="id" class="form-control" placeholder="Enter ID"
                                    value="{{ request('id') }}">
                            </div>
                        </div>

                        <div class="col-md-2">
                            <div class="form-group">
                                <label>Name</label>
                                <input type="text" name="name" class="form-control" placeholder="Enter Name"
                                    value="{{ request('name') }}">
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="form-group">
                                <label>Father Name</label>
                                <input type="text" name="father_name" class="form-control"
                                    placeholder="Enter Father Name" value="{{ request('father_name') }}">
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="form-group">
                                <label>Mother Name</label>
                                <input type="text" name="mother_name" class="form-control"
                                    placeholder="Enter Mother Name" value="{{ request('mother_name') }}">
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="form-group">
                                <label>Address</label>
                                <input type="text" name="address" class="form-control" placeholder="Enter Address"
                                    value="{{ request('address') }}">
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="form-group">
                                <label>POP</label>
                                <select name="pop_id" class="form-control select2">
                                    <option value="">Select POP</option>
                                    @foreach ($pops as $pop)
                                        <option value="{{ $pop->id }}"
                                            {{ request('pop_id') == $pop->id ? 'selected' : '' }}> {{ $pop->popname }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="form-group">
                                <label>Package</label>
                                <select name="package_id" class="form-control select2">
                                    <option value="">Select Package</option>
                                    @foreach ($packages as $package)
                                        <option value="{{ $package->id }}"
                                            {{ request('package_id') == $package->id ? 'selected' : '' }}>
                                            {{ $package->package_name }} </option>
                                    @endforeach
                                </select>
                            </div>
                        </div>

                        <div class="col-md-2">
                            <div class="form-group">
                                <label>Otc Amount</label>
                                <input type="number" name="otc" class="form-control" placeholder="Enter Otc"
                                    value="{{ request('otc') }}">
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="form-group">
                                <label>Fiber Meter Length</label>
                                <input type="number" name="fiber_meter" class="form-control"
                                    placeholder="Enter Fiber Meter" value="{{ request('fiber_meter') }}">
                            </div>
                        </div>

                        <div class="col-md-2">
                            <div class="form-group">
                                <label>Mobile Number</label>
                                <input type="text" name="mobile_number" class="form-control"
                                    placeholder="Enter Mobile Number" value="{{ request('mobile_number') }}">
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="form-group">
                                <label>Alt Mobile Number</label>
                                <input type="text" name="alt_mobile_number" class="form-control"
                                    placeholder="Enter Alt Mobile Number" value="{{ request('alt_mobile_number') }}">
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="form-group">
                                <label>Latitude</label>
                                <input type="text" name="latitude" class="form-control" placeholder="Enter Latitude"
                                    value="{{ request('latitude') }}">
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="form-group">
                                <label>Longitude</label>
                                <input type="text" name="longitude" class="form-control"
                                    placeholder="Enter Longitude" value="{{ request('longitude') }}">
                            </div>
                        </div>

                        <div class="col-md-2">
                            <div class="form-group">
                                <label>Created By (Name)</label>
                                <select name="created_by" class="form-control select2">
                                    <option value="">Select Created By</option>
                                    <option value="Website" {{ request('created_by') == 'Website' ? 'selected' : '' }}>
                                        Website</option>
                                    @foreach ($users as $user)
                                        <option value="{{ $user->id }}"
                                            {{ request('created_by') == $user->id ? 'selected' : '' }}>
                                            {{ $user->name }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                        </div>

                        <div class="col-md-2">
                            <div class="form-group">
                                <label>Status</label>
                                <select name="status" class="form-control select2">
                                    <option value="">Select Status</option>
                                    <option value="cancelled" {{ request('status') == 'cancelled' ? 'selected' : '' }}>
                                        Cancelled</option>
                                    <option value="done" {{ request('status') == 'done' ? 'selected' : '' }}>Done
                                    </option>
                                    <option value="pending" {{ request('status') == 'pending' ? 'pending' : '' }}>Pending
                                    </option>
                                </select>
                            </div>
                        </div>

                        <div class="col-md-2">
                            <div class="form-group">
                                <label>NID</label>
                                <input type="text" name="nid" class="form-control" placeholder="Enter NID"
                                    value="{{ request('nid') }}">
                            </div>
                        </div>

                        <div class="col-md-2">
                            <div class="form-group">
                                <label>Billing Cycle</label>
                                <input type="text" name="billing_cycle" class="form-control"
                                    placeholder="Enter Billing Cycle" value="{{ request('billing_cycle') }}">
                            </div>
                        </div>

                        <div class="col-md-2">
                            <div class="form-group">
                                <label>Division</label>
                                <select name="division_id" id="division" class="form-control select2">
                                    <option value="">Select Division</option>
                                    @foreach ($divisions as $division)
                                        <option value="{{ $division->id }}"
                                            {{ request('division_id') == $division->id ? 'selected' : '' }}>
                                            {{ $division->name }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="form-group">
                                <label>District</label>
                                <select name="district_id" id="district" class="form-control select2">
                                    <option value="">Select District</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="form-group">
                                <label>Upazila</label>
                                <select name="upazila_id" id="upazilla" class="form-control select2">
                                    <option value="">Select Upazila</option>

                                </select>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="form-group">
                                <label>Thana</label>
                                <select name="thana_id" id="thana" class="form-control select2">
                                    <option value="">Select Thana</option>
                                </select>
                            </div>
                        </div>

                        <div class="col-md-2">
                            <div class="form-group">
                                <label>Customer Status</label>
                                <select name="customer_status" class="form-control select2">
                                    <option value="">Select Customer Status</option>
                                    <option value="Survey" {{ request('customer_status') == 'Survey' ? 'selected' : '' }}>
                                        Survey</option>
                                    <option value="Marketing"
                                        {{ request('customer_status') == 'Marketing' ? 'selected' : '' }}>Marketing
                                    </option>
                                    <option value="Tentative activation date"
                                        {{ request('customer_status') == 'Tentative activation date' ? 'selected' : '' }}>
                                        Tentative activation date</option>
                                    <option value="Confirm activation date"
                                        {{ request('customer_status') == 'Confirm activation date' ? 'selected' : '' }}>
                                        Confirm activation date</option>
                                </select>
                            </div>
                        </div>



                        <div class="col-md-2">
                            <div class="form-group">
                                <label>Email</label>
                                <input type="text" name="email" class="form-control" placeholder="Enter Email"
                                    value="{{ request('email') }}">
                            </div>
                        </div>


                        <div class="col-md-2">
                            <div class="form-group">
                                <label>Divice Uses</label>
                                <select name="divice_uses" class="form-control select2">
                                    <option value="">Select Device Uses</option>
                                    @foreach ($devices as $device)
                                        <option value="{{ $device->id }}"
                                            {{ request('divice_uses') == $device->id ? 'selected' : '' }}> {{ $device->name }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                        </div>



                        <div class="col-md-2">
                            <div class="form-group">
                                <label>Client Source</label>
                                <select name="client_source_id" class="form-control select2">
                                    <option value="">Select Client Source</option>
                                    @foreach ($client_source as $source)
                                        <option value="{{ $source->id }}"
                                            {{ request('client_source_id') == $source->id ? 'selected' : '' }}>
                                            {{ $source->name }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                        </div>

                        <div class="col-md-2">
                            <div class="form-group">
                                <label>Multi Router</label>
                                <select name="multi_router" class="form-control select2">
                                    <option value="">Select Multi Router</option>
                                    <option value="Yes" {{ request('multi_router') == 'Yes' ? 'selected' : '' }}>Yes
                                    </option>
                                    <option value="No(1)" {{ request('multi_router') == 'No(1)' ? 'selected' : '' }}>
                                        No(1)
                                    </option>
                                    <option value="Access Point"
                                        {{ request('multi_router') == 'Access Point' ? 'selected' : '' }}>Access Point
                                    </option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="form-group">
                                <label>Survey Status</label>
                                <select name="survey_status" class="form-control select2">
                                    <option value="">Select Survey Status</option>
                                    <option value="Coverage"
                                        {{ request('survey_status') == 'Coverage' ? 'selected' : '' }}>Coverage</option>
                                    <option value="Not Coverage"
                                        {{ request('survey_status') == 'Not Coverage' ? 'selected' : '' }}>Not Coverage
                                    </option>
                                </select>
                            </div>
                        </div>

                        <div class="col-md-2">
                            <div class="form-group">
                                <label>Marketing Done Status</label>
                                <select name="done_status" class="form-control select2">
                                    <option value="">Select Done Status</option>
                                    <option value="Yes" {{ request('done_status') == 'Yes' ? 'selected' : '' }}>Completed
                                    </option>
                                    <option value="No" {{ request('done_status') == 'No' || !request('done_status') ? 'selected' : '' }}>Not Completed</option>
                                    <option value="Pending" {{ request('done_status') == 'Pending' ? 'selected' : '' }}>
                                        Pending </option>
                                </select>
                            </div>
                        </div>

                        <div class="col-md-2">
                            <div class="form-group">
                                <label>Follow Up Date</label>
                                <input type="date" name="follow_up_date" class="form-control" placeholder="Enter Follow Up Date"
                                    value="{{ request('follow_up_date') }}">
                            </div>
                        </div>

                        <div class="col-md-2">
                            <div class="form-group">
                                <label>Confirm Activation Date</label>
                                <input type="date" name="confirm_activation_date" class="form-control" placeholder="Enter Confirm Activation Date"
                                    value="{{ request('confirm_activation_date') }}">
                            </div>
                        </div>

                        <div class="col-md-2">
                            <div class="form-group">
                                <label>Done By (Name)</label>
                                <select name="done_by" class="form-control select2">
                                    <option value="">Select Done By</option>
                                    @foreach ($users as $user)
                                        <option value="{{ $user->id }}" {{ request('done_by') == $user->id ? 'selected' : '' }}> {{ $user->name }} </option>
                                    @endforeach
                                </select>
                            </div>
                        </div>


                        <div class="col-md-2">
                            <div class="form-group">
                                <label>Assigned To Status</label>
                                <select name="assigned_status" class="form-control select2">
                                    <option value="">Select Assigned To Status</option>
                                    <option value="Yes" {{ request('assigned_status') == 'Yes' ? 'selected' : '' }}>Yes
                                    </option>
                                    <option value="No" {{ request('assigned_status') == 'No' ? 'selected' : '' }}>No
                                    </option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="form-group">
                                <label>Lock To Status</label>
                                <select name="lock_status" class="form-control select2">
                                    <option value="">Select Lock To Status</option>
                                    <option value="Yes" {{ request('lock_status') == 'Yes' ? 'selected' : '' }}>Yes
                                    </option>
                                    <option value="No" {{ request('lock_status') == 'No' ? 'selected' : '' }}>No
                                    </option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="form-group">
                                <label>Assigned To (Name)</label>
                                <select name="assigned_to" class="form-control select2">
                                    <option value="">Select Assigned To</option>
                                    @foreach ($users as $user)
                                        <option value="{{ $user->id }}"
                                            {{ request('assigned_to') == $user->id ? 'selected' : '' }}>
                                            {{ $user->name }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                        </div>

                     


                        <div class="col-md-2">
                            <div class="form-group">
                                <label>From Date</label>
                                <input type="date" name="from_date" class="form-control" placeholder="From Date"
                                    value="{{ request('from_date') }}">
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="form-group">
                                <label>To Date</label>
                                <input type="date" name="to_date" class="form-control" placeholder="To Date"
                                    value="{{ request('to_date') }}">
                            </div>
                        </div>
                        <div class="col-md-12">
                            <div class="form-group">
                                <a href="{{ route('newline.newIndex') }}"
                                    class="btn btn-secondary btn-sm float-right ml-1">Reset</a>
                                <button type="submit" class="btn btn-primary btn-sm float-right">Search</button>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        @include('clients.newclient.newLineRquestList')

    </div>
@endsection

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

            // Initialize DataTable
            if ($.fn.DataTable && $('#dataTable').length) {
                $('#dataTable').DataTable({
                    destroy: true,
                    pageLength: 100,
                    order: [
                        [0, 'asc']
                    ],
                    scrollY: '500px',
                    scrollCollapse: true,
                    paging: true,
                    drawCallback: function() {
                        $('[data-toggle="dropdown"]').dropdown();
                    }
                });
            }

            // Fix dropdown clipping inside table-responsive — detach menu to body
            $(document).on('show.bs.dropdown', '#dataTable .dropdown', function() {
                var $toggle = $(this).find('.dropdown-toggle');
                var $menu = $(this).find('.dropdown-menu');

                $('body').append($menu.detach());

                var offset = $toggle.offset();
                $menu.css({
                    display: 'block',
                    position: 'absolute',
                    top: offset.top + $toggle.outerHeight(),
                    left: offset.left,
                    zIndex: 9999
                });

                $(this).data('detached-menu', $menu);
            });

            $(document).on('hide.bs.dropdown', '#dataTable .dropdown', function() {
                var $menu = $(this).data('detached-menu');
                if ($menu) {
                    $(this).append($menu.detach());
                    $menu.removeAttr('style');
                }
            });

            // Open Support Done Modal
            $(document).on('click', '.open-support-done-modal', function(e) {
                e.preventDefault();
                var id = $(this).data('id');
                var url = '{{ route('newline.supportdone', 'ID_PLACEHOLDER') }}'.replace('ID_PLACEHOLDER',
                    id);
                $('#supportDoneForm').attr('action', url);
                $('#supportRemarks').val($(this).data('status'));
                $('#supportCancelStatusForMultiRouter').prop('checked', false);
                $('#open-support-done-modal').modal('show');
            });

            // Open Remarks Modal
            $(document).on('click', '.open-remarks-modal', function(e) {
                e.preventDefault();
                var id = $(this).data('id');
                $('#remarkRequestId').val(id);
                $('#newRemarkText').val('');
                $('#remarksList').empty();
                $('#remarksListEmpty').addClass('d-none');
                $('#remarksListLoading').removeClass('d-none');
                $('#remarksModal').modal('show');

                $.ajax({
                    type: 'GET',
                    url: '{{ route('new-line-request-remarks') }}',
                    data: {
                        id: id
                    },
                    success: function(res) {
                        $('#remarksListLoading').addClass('d-none');

                        var tableHtml = `
                        <table class="table table-sm table-bordered">
                            <thead class="thead-light">
                                <tr>
                                    <th>Created By</th>
                                    <th>Remark</th>
                                    <th>Time</th>
                                </tr>
                            </thead>
                            <tbody></tbody>
                        </table>`;
                        $('#remarksList').html(tableHtml);

                        var $tbody = $('#remarksList table tbody');

                        if (res.data && res.data.length > 0) {
                            $('#remarksListEmpty').addClass('d-none');
                            res.data.forEach(function(item) {
                                var userName = item.user && item.user.name ? item.user
                                    .name : 'Unknown User';
                                $tbody.append(`
                                <tr>
                                    <td>${userName}</td>
                                    <td>${item.remarks || ''}</td>
                                    <td>${item.created_at || ''}</td>
                                </tr>`);
                            });
                        } else {
                            $('#remarksListEmpty').removeClass('d-none');
                        }
                    },
                    error: function() {
                        $('#remarksListLoading').addClass('d-none');
                        $('#remarksListEmpty').removeClass('d-none').text(
                            'Failed to load remarks. Please try again.');
                    }
                });
            });

            // Submit New Remark
            $(document).on('submit', '#addRemarkForm', function(e) {
                e.preventDefault();

                var requestId = $('#remarkRequestId').val();
                var remarkText = $('#newRemarkText').val();
                var $btn = $(this).find('button[type="submit"]');
                var origHtml = $btn.html();

                $btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Submitting...');

                $.ajax({
                    url: '{{ route('new-line-request-remarks-add') }}',
                    type: 'GET',
                    data: {
                        _token: '{{ csrf_token() }}',
                        remarks: remarkText,
                        id: requestId
                    },
                    success: function(res) {
                        $btn.prop('disabled', false).html(origHtml);
                        $('#remarksListLoading').addClass('d-none');
                        toastr.success(res.message);
                        $('#newRemarkText').val('');

                        var tableHtml = `
                        <table class="table table-sm table-bordered">
                            <thead class="thead-light">
                                <tr>
                                    <th>Created By</th>
                                    <th>Remark</th>
                                    <th>Time</th>
                                </tr>
                            </thead>
                            <tbody></tbody>
                        </table>`;
                        $('#remarksList').html(tableHtml);

                        var $tbody = $('#remarksList table tbody');

                        if (res.data && res.data.length > 0) {
                            $('#remarksListEmpty').addClass('d-none');
                            res.data.forEach(function(item) {
                                var userName = item.user && item.user.name ? item.user
                                    .name : 'Unknown User';
                                $tbody.append(`
                                <tr>
                                    <td>${userName}</td>
                                    <td>${item.remarks || ''}</td>
                                    <td>${item.created_at || ''}</td>
                                </tr>`);
                            });
                        } else {
                            $('#remarksListEmpty').removeClass('d-none');
                        }
                    },
                    error: function() {
                        $btn.prop('disabled', false).html(origHtml);
                        $('#remarksListLoading').addClass('d-none');
                        $('#remarksListEmpty').removeClass('d-none').text(
                            'Failed to submit remark. Please try again.');
                    }
                });
            });

            // Survey cancel reason visibility
            function handleSurveyCancelReasonVisibility() {
                var surveyStatus = $('#surveySelectModal').val();
                if (surveyStatus === 'Not Coverage') {
                    $('#surveyCancelReasonSection').show();
                } else {
                    $('#surveyCancelReasonSection').hide();
                    $('.survey-cancel-reason-cb').prop('checked', false);
                }
            }

            $('#surveySelectModal').on('change', function() {
                handleSurveyCancelReasonVisibility();
            });

            // Open Survey Modal
            $(document).on('click', '.open-survey-modal', function(e) {
                e.preventDefault();
                var id = $(this).data('id');
                $('#surveyModalRequestId').text(id);
                $('#surveyHiddenRequestId').val(id);
                $('#surveySelectModal').val('');
                $('#surveyRemarksModal').val('');
                $('.survey-cancel-reason-cb').prop('checked', false);
                $('#surveyCancelReasonSection').hide();
                $('#surveyModal').modal('show');
            });

            // Submit Survey Status
            $(document).on('submit', '#surveyForm', function(e) {
                e.preventDefault();

                var requestId = $('#surveyHiddenRequestId').val();
                var surveyStatus = $('#surveySelectModal').val();
                var surveyRemarks = $('#surveyRemarksModal').val();
                var surveyCancelReasons = $('.survey-cancel-reason-cb:checked').map(function() {
                    return $(this).data('survey-cancel-reason-id');
                }).get();

                if (surveyStatus === '') {
                    toastr.error('Please select survey status');
                    return false;
                }
                if (surveyRemarks === '') {
                    toastr.error('Please enter survey remarks');
                    return false;
                }
                if (surveyStatus === 'Not Coverage' && surveyCancelReasons.length === 0) {
                    toastr.error('Please select at least one cancel reason');
                    return false;
                }

                $.ajax({
                    url: '{{ route('new-line-request-survey-update') }}',
                    type: 'GET',
                    data: {
                        _token: '{{ csrf_token() }}',
                        survey: surveyStatus,
                        survey_remarks: surveyRemarks,
                        id: requestId,
                        survey_cancel_reasons: surveyCancelReasons
                    },
                    success: function(res) {
                        if (res.error == false) {
                            toastr.success(res.message);
                            if (surveyStatus === 'Not Coverage') {
                                $('tr').find('td:first').filter(function() {
                                    return $(this).text().trim() == requestId;
                                }).closest('tr').fadeOut(400, function() {
                                    $(this).remove();
                                    var currentCount = parseInt($('.col-6 h5').text()
                                        .replace('Total: ', ''));
                                    $('.col-6 h5').text('Total: ' + (currentCount - 1));
                                });
                            }
                        } else {
                            toastr.error(res.message);
                        }
                        $('#surveyModal').modal('hide');
                    },
                    error: function() {
                        toastr.error('An error occurred. Please try again.');
                    }
                });
            });

            // Open Marketing Modal
            $(document).on('click', '.open-marketig-modal', function(e) {
                e.preventDefault();
                var id = $(this).data('id');
                var followUpDate = $(this).data('follow-up-date') || '';
                var confirmActivationDate = $(this).data('confirm-activation-date') || '';

                $('#marketingStatusHiddenRequestId').val(id);
                $('#marketingRemarks').val('');
                $('#follow_up_date_marketing').val(followUpDate);
                $('#confirm_activation_date_modal').val(confirmActivationDate);
                $('#marketinStatusModal').modal('show');
            });

            // Marketing cancel reason visibility
            function handleCancelReasonVisibility() {
                var status = $('#marketingModalStatus').val();

                if (status === '2') {
                    $('#followup_section').show();
                } else {
                    $('#followup_section').hide();
                    $('#follow_up_date_marketing').val('');
                }

                if (status === '1') {
                    $('#marketingUserSection').show();
                    $('#marketingUserSelect').prop('required', true);
                    $('#confirm_activation_date_section').show();
                } else {
                    $('#marketingUserSection').hide();
                    $('#marketingUserSelect').val('').trigger('change').prop('required', false);
                    $('#confirm_activation_date_section').hide();
                    $('#confirm_activation_date_modal').val('');
                }

                if (status === '1' || status === '2' || status === '') {
                    $('#cancelReasonSection').hide();
                    $('.cancel-reason-cb').prop('checked', false);
                } else {
                    $('#cancelReasonSection').show();
                }

                if (status === '1') {
                    var newLineRequestId = $('#marketingStatusHiddenRequestId').val();
                    $.ajax({
                        url: '{{ route('get-marketing-users') }}',
                        type: 'GET',
                        data: {
                            id: newLineRequestId
                        },
                        success: function(res) {
                            $('#marketingUserSelect').html(
                                '<option value="">Select Marketing User</option>');
                            res.data.forEach(function(item) {
                                $('#marketingUserSelect').append('<option value="' + item.id +
                                    '">' + item.name + '</option>');
                            });
                            if ($('#marketingUserSelect').hasClass('select2-hidden-accessible')) {
                                $('#marketingUserSelect').select2('destroy');
                            }
                            $('#marketingUserSelect').select2({
                                dropdownParent: $('#marketinStatusModal'),
                                placeholder: 'Select Marketing User',
                                allowClear: true
                            });
                        }
                    });
                }
            }

            $('#marketingModalStatus').on('change', function() {
                handleCancelReasonVisibility();
            });

            $('#marketinStatusModal').on('shown.bs.modal', function() {
                $('#marketingModalStatus').val('');
                $('.cancel-reason-cb').prop('checked', false);
                $('#cancelReasonSection').hide();
                $('#followup_section').hide();
                $('#marketingUserSection').hide();
                $('#marketingUserSelect').val('').trigger('change').prop('required', false);
                $('#confirm_activation_date_section').hide();
            });

            // Submit Marketing Status
            $(document).on('submit', '#marketingForm', function(e) {
                e.preventDefault();

                var requestId = $('#marketingStatusHiddenRequestId').val();
                var marketingStatus = $('#marketingModalStatus').val();
                var marketingRemarks = $('#marketingRemarks').val();
                var marketingUserId = $('#marketingUserSelect').val();
                var followUp = $('#follow_up_date_marketing').val();
                var confirmation = $('#confirm_activation_date_modal').val();
                var cancelReasons = $('.cancel-reason-cb:checked').map(function() {
                    return $(this).data('cancel-reason-id');
                }).get();

                if (marketingStatus === '') {
                    toastr.error('Please select status');
                    return false;
                }
                if (marketingRemarks === '') {
                    toastr.error('Please enter remarks');
                    return false;
                }
                if (marketingStatus != 1 && marketingStatus != 2 && cancelReasons.length === 0) {
                    toastr.error('Please select at least one cancel reason');
                    return false;
                }
                if (marketingStatus == 2 && followUp === '') {
                    toastr.error('Please select a follow-up date');
                    return false;
                }
                if (marketingStatus == 1 && marketingUserId === '') {
                    toastr.error('Please select a marketing user');
                    return false;
                }
                if (marketingStatus == 1 && confirmation === '') {
                    toastr.error('Please select a confirm activation date');
                    return false;
                }

                $.ajax({
                    url: '{{ route('change-marketing-status') }}',
                    type: 'GET',
                    data: {
                        _token: '{{ csrf_token() }}',
                        marketingStatus: marketingStatus,
                        marketingRemarks: marketingRemarks,
                        id: requestId,
                        cancelReasons: cancelReasons,
                        followUpDate: followUp,
                        marketingUserId: marketingUserId,
                        confirmation: confirmation
                    },
                    success: function(res) {
                        if (res.error == false) {
                            toastr.success(res.message);
                            $('tr').find('td:first').filter(function() {
                                return $(this).text().trim() == requestId;
                            }).closest('tr').fadeOut(400, function() {
                                $(this).remove();
                                var currentCount = parseInt($('.col-6 h5').text()
                                    .replace('Total: ', ''));
                                $('.col-6 h5').text('Total: ' + (currentCount - 1));
                            });
                        } else {
                            toastr.error(res.message);
                        }
                        $('#marketinStatusModal').modal('hide');
                    },
                    error: function() {
                        toastr.error('An error occurred. Please try again.');
                    }
                });
            });

            // Open Assign Modal
            $(document).on('click', '.open-assign-modal', function(e) {
                e.preventDefault();
                var id = $(this).data('id');
                $('#assignModalRequestId').text(id);
                $('#assignHiddenRequestId').val(id);
                $('#assignUserSelect').val('').trigger('change');
                $('#assignRemarks').val('');
                $('#assignModal').modal('show');
            });

            // Initialize select2 for assign modal on show
            $('#assignModal').on('shown.bs.modal', function() {
                if ($('#assignUserSelect').hasClass('select2-hidden-accessible')) {
                    $('#assignUserSelect').select2('destroy');
                }
                $('#assignUserSelect').select2({
                    dropdownParent: $('#assignModal'),
                    placeholder: 'Select User',
                    allowClear: true
                });
            });

            // Submit Assign Form
            $(document).on('submit', '#assignForm', function(e) {
                e.preventDefault();

                var requestId = $('#assignHiddenRequestId').val();
                var userId = $('#assignUserSelect').val();
                var assignRemarks = $('#assignRemarks').val();
                var $btn = $('#submitAssignBtn');
                var origHtml = $btn.html();

                if (userId === '') {
                    toastr.error('Please select a user');
                    return false;
                }

                $btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Assigning...');

                $.ajax({
                    url: '{{ route('new-line-request-assign') }}',
                    type: 'POST',
                    data: {
                        _token: '{{ csrf_token() }}',
                        id: requestId,
                        user_id: userId,
                        assign_remarks: assignRemarks
                    },
                    success: function(res) {
                        $btn.prop('disabled', false).html(origHtml);
                        if (res.error == false) {
                            toastr.success(res.message);
                            $('#assignModal').modal('hide');
                        } else {
                            toastr.error(res.message);
                        }
                    },
                    error: function(xhr) {
                        $btn.prop('disabled', false).html(origHtml);
                        var msg = xhr.responseJSON && xhr.responseJSON.message ?
                            xhr.responseJSON.message :
                            'An error occurred. Please try again.';
                        toastr.error(msg);
                    }
                });
            });

            // get district by division id
            $('#division').change(function() {
                var id = $('#division').val();
                $.ajax({
                    url: '{{ route('fetchDistrict') }}',
                    type: 'get',
                    data: {
                        id: id
                    },
                    dataType: 'json',
                    success: function(data) {
                        $('#district').html(data);
                    }
                });
            });

            $('#district').change(function() {
                var id = $('#district').val();


                $.ajax({
                    url: '{{ route('fetchUpazila') }}',
                    type: 'get',
                    data: {
                        id: id
                    },
                    dataType: 'json',
                    success: function(data) {
                        $('#upazilla').html(data);
                    }
                });
            });

            $('#upazilla').change(function() {
                var id = $('#upazilla').val();
                $.ajax({
                    url: '{{ route('fetchThana') }}',
                    type: 'get',
                    data: {
                        id: id
                    },
                    dataType: 'json',
                    success: function(data) {
                        $('#thana').html(data);
                    }
                });
            });

        });
    </script>
@endsection
