@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;
        }
    </style>
@endsection

@section('content')
    <div class="container-fluid">
        <div class="row mb-3">
            {{-- <div class="col-12 text-right">
                <a href="{{ route('new-line-request.create') }}" 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('new-line-request.index') }}" method="GET">
                    <div class="row">
                        <div class="col-md-3">
                            <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-3">
                            <div class="form-group">
                                <label>Status</label>
                                <select name="status" class="form-control select2">
                                    <option value="">Select Status</option>
                                    <option value="pending" {{ request('status') == 'pending' ? 'selected' : '' }}>Pending
                                    </option>

                                    <option value="cancelled" {{ request('status') == 'cancelled' ? 'selected' : '' }}>
                                        Cancelled</option>
                                    <option value="done" {{ request('status') == 'done' ? 'selected' : '' }}>Done</option>

                                </select>
                            </div>
                        </div>
                        <div class="col-md-12">
                            <div class="form-group">
                                <a href="{{ route('new-line-request.index') }}"
                                    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.result')

    </div>
@endsection

@section('ajax')
    <script>
        $(function() {
            if ($.fn.DataTable && $('#dataTable').length) {
                $('#dataTable').DataTable({
                    destroy: true,
                    pageLength: 100
                });
            }

            $(document).on('click', '.open-status-modal', function(e) {
                e.preventDefault();
                var id = $(this).data('id');
                var status = $(this).data('status');
                var url = '{{ route('new-line-request.status', 'ID_PLACEHOLDER') }}'.replace(
                    'ID_PLACEHOLDER', id);
                $('#statusForm').attr('action', url).attr('data-request-id', id);
                $('#statusSelect').val(status);
                $('#statusModal').modal('show');
            });

            // Open Delivery Date Modal
            $(document).on('click', '.open-delivery-date-modal', function(e) {
                e.preventDefault();
                var id = $(this).data('id');
                var deliveryDate = $(this).data('delivery-date') || '';

                $('#deliveryDateRequestId').val(id);
                $('#deliveryDateInput').val(deliveryDate);
                $('#deliveryDateModal').modal('show');
            });

            // Open Change Free Day Modal
            $(document).on('click', '.open-change-free-modal', function(e) {
                e.preventDefault();
                var id = $(this).data('id');
                var freeDays = $(this).data('free-days');

                $('#changeFreeDayRequestId').val(id);
                $('#previousFreeDayDisplay').text(freeDays !== '' && freeDays != null ? freeDays +
                    ' day(s)' : 'Not set');
                $('#freeDaysInput').val(freeDays !== '' && freeDays != null ? freeDays : '');
                $('#changeFreeDayModal').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');

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

                        // Build table header
                        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');
                        $tbody.empty();

                        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';
                                var createdAt = item.created_at || '';
                                var text = item.remarks || '';

                                var row = `
                                <tr>
                                    <td>${userName}</td>
                                    <td>${text}</td>
                                    <td>${createdAt}</td>
                                </tr>
                            `;
                                $tbody.append(row);
                            });
                        } 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 submitBtn = $(this).find('button[type="submit"]');
                var originalBtnText = submitBtn.html();

                // Disable submit button and show loading state
                submitBtn.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) {
                        $('#remarksListLoading').addClass('d-none');
                        // show a success toastr message
                        toastr.success(res.message);

                        // make click able submit button
                        submitBtn.prop('disabled', false).html(originalBtnText);

                        //also remover previous text from remark box
                        $('#newRemarkText').val('');

                        // Build table header
                        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');
                        $tbody.empty();

                        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';
                                var createdAt = item.created_at || '';
                                var text = item.remarks || '';

                                var row = `
                                <tr>
                                    <td>${userName}</td>
                                    <td>${text}</td>
                                    <td>${createdAt}</td>
                                </tr>
                            `;
                                $tbody.append(row);
                            });
                        } else {
                            $('#remarksListEmpty').removeClass('d-none');
                        }
                    },
                    error: function() {
                        $('#remarksListLoading').addClass('d-none');
                        $('#remarksListEmpty')
                            .removeClass('d-none')
                            .text('Failed to load remarks. Please try again.');
                    }
                });
            });

            // Submit Delivery Date
            $(document).on('submit', '#deliveryDateForm', function(e) {
                e.preventDefault();
                var requestId = $('#deliveryDateRequestId').val();
                var deliveryDate = $('#deliveryDateInput').val();
                var submitBtn = $(this).find('button[type="submit"]');
                var originalBtnText = submitBtn.html();

                // Disable submit button and show loading state
                submitBtn.prop('disabled', true).html(
                    '<i class="fas fa-spinner fa-spin"></i> Submitting...');

                $.ajax({
                    url: '{{ route('new-line-request-set-delivery-date') }}',
                    type: 'Get',
                    data: {
                        delivery_date: deliveryDate,
                        id: requestId
                    },
                    success: function(res) {
                        submitBtn.prop('disabled', false).html(originalBtnText);
                        if (res.error == false) {
                            $('#deliveryDateModal').modal('hide');
                            toastr.success(res.message);
                            // Update the row without reload
                            var $row = $('tr[data-request-id="' + requestId + '"]');
                            $row.find('.delivery-date-cell').text(res.delivery_date || 'N/A');
                        } else {
                            toastr.error(res.message);
                        }
                    },
                    error: function() {
                        submitBtn.prop('disabled', false).html(originalBtnText);
                        $('#deliveryDateModal').modal('hide');
                        toastr.error('Failed to set delivery date. Please try again.');
                    }
                });
            });

            // Submit Change Free Day
            $(document).on('submit', '#changeFreeDayForm', function(e) {
                e.preventDefault();
                var requestId = $('#changeFreeDayRequestId').val();
                var freeDays = $('#freeDaysInput').val();
                var submitBtn = $(this).find('button[type="submit"]');
                var originalBtnText = submitBtn.html();

                // Disable submit button and show loading state
                submitBtn.prop('disabled', true).html(
                    '<i class="fas fa-spinner fa-spin"></i> Submitting...');

                $.ajax({
                    url: '{{ route('new-line-request-set-free-days') }}',
                    type: 'Get',
                    data: {
                        free_days: freeDays,
                        id: requestId
                    },
                    success: function(res) {
                        submitBtn.prop('disabled', false).html(originalBtnText);
                        if (res.error == false) {
                            $('#changeFreeDayModal').modal('hide');
                            toastr.success(res.message);
                            // Update the row without reload
                            var $row = $('tr[data-request-id="' + requestId + '"]');
                            $row.find('.free-days-cell').text(res.free_days != null ? res
                                .free_days : '—');
                            $row.find('.open-change-free-modal').data('free-days', res
                                .free_days);
                        } else {
                            toastr.error(res.message);
                        }
                    },
                    error: function() {
                        submitBtn.prop('disabled', false).html(originalBtnText);
                        toastr.error('Something went wrong. Please try again.');
                    }
                });
            });
        });


        $(document).on('click', '.open-assign-line-man-modal', function(e) {
            e.preventDefault();
            var id = $(this).data('id');
            var lineManId = $(this).data('line-man-id');
            $('#assignLineManRequestId').val(id);
            $('#lineManagerSelect').val(lineManId !== '' && lineManId != null ? lineManId : '');
            $('#assignLineManModal').modal('show');
        });

        $('#assignLineManModal').on('shown.bs.modal', function() {
            if ($('#lineManagerSelect').hasClass('select2-hidden-accessible')) {
                $('#lineManagerSelect').select2('destroy');
            }
            $('#lineManagerSelect').select2({
                dropdownParent: $('#assignLineManModal'),
                width: '100%'
            });
        });

        $(document).on('submit', '#assignLineManForm', function(e) {
            e.preventDefault();
            var requestId = $('#assignLineManRequestId').val();
            var lineManagerId = $('#lineManagerSelect').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> Assigning...');

            $.ajax({
                url: '{{ route('new-line-request-assign-line-man') }}',
                type: 'POST',
                data: {
                    _token: '{{ csrf_token() }}',
                    id: requestId,
                    line_manager_id: lineManagerId
                },
                success: function(res) {
                    $btn.prop('disabled', false).html(origHtml);
                    if (res.error == false) {
                        $('#assignLineManModal').modal('hide');
                        toastr.success(res.message);
                        var $row = $('tr[data-request-id="' + requestId + '"]');
                        $row.find('.line-man-cell').text(res.line_manager_name || '—');
                        $row.find('.open-assign-line-man-modal').data('line-man-id', res
                            .line_manager_id);

                        // Update userid, cid, and ticket if provided
                        if (res.userid) {
                            $row.find('.userid-cell').html('<i class="fas fa-user"></i> ' + res.userid);
                        }
                        if (res.cid) {
                            $row.find('.cid-cell').html('<i class="fas fa-id-card"></i> ' + res.cid);
                        }
                        if (res.ticket) {
                            $row.find('.ticket-cell').html('<i class="fas fa-ticket"></i> ' + res
                                .ticket);
                        }
                    } else {
                        toastr.error(res.message || 'Failed to assign line man.');
                    }
                },
                error: function(xhr) {
                    $btn.prop('disabled', false).html(origHtml);
                    var msg = 'Something went wrong. Please try again.';
                    if (xhr.responseJSON && xhr.responseJSON.message) {
                        msg = xhr.responseJSON.message;
                    }
                    toastr.error(msg);
                }
            });
        });
    </script>
    <script>
        (function() {
            function toggleCancelRemarks() {
                var isCancelled = $('#statusSelect').val() === 'cancelled';
                var $wrapper = $('#cancelRemarksWrapper');
                var $textarea = $('#confirm_line_request_cancel_remarks');
                var $error = $('#cancelRemarksError');
                if (isCancelled) {
                    $wrapper.removeClass('d-none');
                    $textarea.prop('required', true);
                    $error.addClass('d-none');
                } else {
                    $wrapper.addClass('d-none');
                    $textarea.prop('required', false).val('');
                    $error.addClass('d-none');
                }
            }
            $(document).on('change', '#statusSelect', toggleCancelRemarks);
            $('#statusModal').on('show.bs.modal', toggleCancelRemarks);
            $('#statusForm').on('submit', function(e) {
                e.preventDefault();
                if ($('#statusSelect').val() === 'cancelled') {
                    var remarks = $.trim($('#confirm_line_request_cancel_remarks').val());
                    if (!remarks) {
                        $('#cancelRemarksError').removeClass('d-none');
                        return false;
                    }
                }
                $('#cancelRemarksError').addClass('d-none');

                var $form = $(this);
                var url = $form.attr('action');
                var $submitBtn = $form.find('button[type="submit"]');
                var originalText = $submitBtn.text();

                $submitBtn.prop('disabled', true).text('Updating...');

                $.ajax({
                    url: url,
                    type: 'POST',
                    data: $form.serialize(),
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                        'Accept': 'application/json'
                    },
                    success: function(response) {
                        if (typeof toastr !== 'undefined') {
                            toastr.success(response.message || 'Status updated');
                        }
                        $('#statusModal').modal('hide');
                        var requestId = $form.attr('data-request-id');
                        if (requestId) {
                            $('#dataTable').find('tr[data-request-id="' + requestId + '"]').remove();
                            var $totalEl = $('#dataTable').closest('.card').find('.card-header h5.text-right');
                            if ($totalEl.length) {
                                var n = parseInt($totalEl.text().replace(/\D/g, ''), 10) || 0;
                                if (n > 0) $totalEl.text('Total: ' + (n - 1));
                            }
                        }
                    },
                    error: function(xhr) {
                        var msg = 'Failed to update status.';
                        if (xhr.responseJSON && xhr.responseJSON.message) {
                            msg = xhr.responseJSON.message;
                        } else if (xhr.responseJSON && xhr.responseJSON.errors) {
                            msg = Object.values(xhr.responseJSON.errors).flat().join(' ');
                        }
                        if (typeof toastr !== 'undefined') {
                            toastr.error(msg);
                        } else {
                            alert(msg);
                        }
                    },
                    complete: function() {
                        $submitBtn.prop('disabled', false).text(originalText);
                    }
                });

                return false;
            });
        })();
    </script>
@endsection
