@extends('layout.app')


@section('content')
    <div class="mt-2 card">
        <div class=" card-body">


            <div class="table-responsive token-detail-table-wrap">
                <h3 class="text-right mb-2"><span id="token-detail-total">Total Token: 0</span></h3>
                <table id="tokenDetailDataTable" class="table table-bordered">
                    <thead class="bg-dark text-white sticky-table-header">
                        <tr>
                            <th style="padding-left: 2px;padding-right: 2px;">ID</th>
                            <th style="padding-left: 2px;padding-right: 2px;max-width:150px">Token#</th>
                            <th style="padding-left: 2px;padding-right: 2px;max-width:90px">Category(Code)</th>
                            <th style="padding-left: 2px;padding-right: 2px;max-width:100px">Description</th>
                            <th style="padding-left: 2px;padding-right: 2px;max-width:100px">Source</th>
                            <th style="width:120px">Creator</th>
                            <th style="padding-left: 2px;padding-right: 2px;max-width:120px">Reseller</th>
                            <th style="padding-left: 2px;padding-right: 2px;max-width:120px">POP</th>
                            <th style="padding-left: 2px;padding-right: 2px;max-width:120px">Customer ID <br> UserName</th>
                            <th style="padding-left: 2px;padding-right: 2px;max-width:200px">Customer Info</th>
                            <th style="padding-left: 2px;padding-right: 2px;max-width:70px">Reporter <br> Contact</th>
                            <th style="padding-left: 2px;padding-right: 2px;max-width:70px">Assigned</th>
                            <th style="padding-left: 2px;padding-right: 2px;max-width:70px">Token Type</th>
                            <th style="padding-left: 2px;padding-right: 2px;max-width:70px"></th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>

        </div>
        <div class="modal fade" id="assignTokenModel" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
            aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabel">Assign Token</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <form action="{{ route('assignTokenFromModal') }}" method="POST" name="assign_token">
                            @csrf
                            <div class="form-group">
                                <label for="recipient-name" class="col-form-label">Empolyee:</label>
                                <select name="employee_modal" id="employee_modal" class="form-control bSelect select2"
                                    required>
                                    <option value="">Select Employee</option>
                                    @foreach ($employees as $employee)
                                        <option value="{{ $employee->id }}">{{ $employee->name }}</option>
                                    @endforeach

                                </select>
                            </div>
                            <input type="hidden" name="id_token_assign_model" id="id_token_assign_model">

                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                            <button type="submit" class="btn btn-primary">Save </button>
                        </form>
                    </div>
                    <div class="modal-footer">
                    </div>
                </div>
            </div>
        </div>

        <div class="modal fade" id="reAssignTokenModel" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
            aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabel">Re Assign Token</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <form action="{{ route('reAssignTokenFromModal') }}" method="POST" name="assign_token">
                            @csrf
                            <div class="form-group">
                                <label for="recipient-name" class="col-form-label">Empolyee:</label>
                                <select name="employee" id="employee_re" class="form-control bSelect select2" required>
                                    <option value="">Select Employee</option>
                                    @foreach ($employees as $employee)
                                        <option value="{{ $employee->id }}">{{ $employee->name }}</option>
                                    @endforeach

                                </select>
                            </div>
                            <input type="hidden" name="id_token_re_assign_model" id="id_token_re_assign_model">

                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                            <button type="submit" class="btn btn-primary">Save </button>
                        </form>
                    </div>
                    <div class="modal-footer">
                    </div>
                </div>
            </div>
        </div>


        <div class="modal fade" id="closeTokenModel" tabindex="-1" role="dialog" aria-labelledby="closeTokenModel"
            aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabel">Close Token</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <form action="{{ route('closeTokenModal') }}" method="POST" name="assign_token">
                            @csrf
                            <div class="form-group">
                                <label for="recipient-name" class="col-form-label">Remark*</label>
                                <input type="text" name="remark" id="remark" class="form-control" required>
                            </div>
                            @if (checkSettings('remote_autoreboot_info_required') == 'enable')
                                <div class="form-group">
                                    <label for="recipient-name"
                                        class="col-form-label">Remote{{ checkRequired('remote_autoreboot_info_required', '*') }}</label>
                                    <select name="remote" id="" class="form-control"
                                        {{ checkRequired('remote_autoreboot_info_required', 'required') }}>
                                        <option value="0">No</option>
                                        <option value="1">Yes</option>
                                    </select>
                                </div>
                            @endif
                            <div class="form-group">
                                <label for="ping_loss" class="col-form-label">Ping
                                    Loss{{ checkRequired('ping_optical_info_required', '*') }}</label>
                                <input type="text" name="ping_loss" id="ping_loss" class="form-control"
                                    {{ checkRequired('ping_optical_info_required', 'required') }}>
                            </div>
                            @if (checkSettings('remote_autoreboot_info_required') == 'enable')
                                <div class="form-group">
                                    <label for="recipient-name" class="col-form-label">Auto
                                        Reboot{{ checkRequired('remote_autoreboot_info_required', '*') }}</label>
                                    <select name="autoreboot" id="" class="form-control"
                                        {{ checkRequired('remote_autoreboot_info_required', 'required') }}>
                                        <option value="0">No</option>
                                        <option value="1">Yes</option>
                                    </select>
                                </div>
                            @endif
                            <div class="form-group">
                                <label for="optical_power" class="col-form-label">Optical
                                    Power{{ checkRequired('ping_optical_info_required', '*') }}</label>
                                <input type="text" name="optical_power" id="optical_power" class="form-control"
                                    {{ checkRequired('ping_optical_info_required', 'required') }}>
                            </div>

                            <div class="form-group">
                                <label for="issue_type">Issue Type*</label>
                                <div class="row">
                                    <div class="col-md-6">
                                        <input type="radio" id="physical" name="issue_type" value="Physical"
                                            required>
                                        <label for="physical">Physical</label><br>
                                    </div>
                                    <div class="col-md-6">
                                        <input type="radio" id="logical" name="issue_type" value="Logical" required>
                                        <label for="logical">Logical</label><br>
                                    </div>
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="client_feedback" class="col-form-label">Client Feedback*</label>
                                <textarea name="client_feedback" class="form-control" required></textarea>
                            </div>

                            <input type="hidden" name="id_token_close_model" id="id_token_close_model">

                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                            <button type="submit" class="btn btn-primary">Save </button>
                        </form>
                    </div>
                    <div class="modal-footer">
                    </div>
                </div>
            </div>
        </div>

        <div class="modal fade" id="addNoteModel" tabindex="-1" role="dialog" aria-labelledby="closeTokenModel"
            aria-hidden="true">
            <div class="modal-dialog modal-xl" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabel">Add Note</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <div class="table-responsive" style="height: 300px">
                            <table id="token_note_table" class="table table-bordered">
                                <thead class="bg-dark">
                                    <tr>
                                        <th style="max-width: 100px">Id</th>
                                        <th style="max-width: 100px">Note For</th>
                                        <th style="max-width: 100px">Created Time</th>
                                        <th>Remark</th>
                                        <th>Created By</th>
                                        @can('token-note-delete')
                                            <th style="max-width: 100px">Action</th>
                                        @endcan
                                    </tr>
                                </thead>
                                <tbody>

                                </tbody>
                            </table>
                        </div>
                        <form action="{{ route('add-note-token') }}" method="POST" name="assign_token">
                            @csrf
                            <div class="form-group">
                                <label for="recipient-name" class="col-form-label">Note For</label>
                                <select name="note_for" id="note_for" class="form-control">
                                    <option value="employee">Employee</option>
                                    <option value="customer">Customer</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label for="recipient-name" class="col-form-label">Remark</label>
                                <textarea type="text" name="note_remark" id="note_remark" class="form-control"></textarea>
                            </div>
                            <input type="hidden" name="add_modal_token_id" id="add_modal_token_id">

                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                            <button type="submit" class="btn btn-primary">Save </button>
                        </form>
                    </div>
                    <div class="modal-footer">
                    </div>
                </div>
            </div>
        </div>

        <div class="modal fade" id="showNoteModel" tabindex="-1" role="dialog" aria-labelledby="closeTokenModel"
            aria-hidden="true">
            <div class="modal-dialog modal-xl" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabelshow">Show Note</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <div class="table-responsive" style="height: 300px">
                            <table id="token_note_table_show" class="table table-bordered">
                                <thead class="bg-dark">
                                    <tr>
                                        <th style="max-width: 100px">Id</th>
                                        <th style="max-width: 100px">Note For</th>
                                        <th style="max-width: 100px">Created Time</th>
                                        <th>Remark</th>
                                        <th>Created By</th>
                                        <th style="max-width: 100px">Action</th>
                                    </tr>
                                </thead>
                                <tbody>

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

                    </div>
                    <div class="modal-footer">
                    </div>
                </div>
            </div>
        </div>
    </div>
    <style>
        /* Container with fixed height and scroll */
        .token-detail-table-wrap {
            max-height: calc(100vh - 200px);
            /* Adjust based on your header/footer height */
            overflow-y: auto;
            overflow-x: auto;
            position: relative;
            border: 1px solid #dee2e6;
            border-radius: 4px;
        }

        /* Sticky table header */
        .token-detail-table-wrap #tokenDetailDataTable thead th {
            position: sticky !important;
            top: 0 !important;
            z-index: 100 !important;
            background: #343a40 !important;
            color: #fff !important;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15) !important;
            border-bottom: 1px solid rgba(255, 255, 255, 0.2) !important;
        }

        /* Ensure table doesn't have conflicting styles */
        #tokenDetailDataTable {
            margin-bottom: 0 !important;
        }

        .sub-menu li {
            font-size: 1em;
            padding: .25em 1em;
            line-height: 1em;
        }

        .sub-menu {
            padding: 0;
            max-height: 200px;
            overflow-y: auto;
        }

        li.selected {
            background: #17A2B8 !important;
        }
    </style>
@endsection

@section('ajax')
    <script>
        $(document).ready(function() {
            $('#tokenCategory').change(function() {
                var tokenCategory = $(this).val();
                if (tokenCategory) {
                    $.ajax({
                        type: "GET",
                        url: '{{ route('get-token-code') }}',
                        data: {
                            tokenCategory: tokenCategory
                        },
                        success: function(res) {
                            if (res) {
                                $("#tokenCode").empty();
                                $("#tokenCode").append(
                                    '<option value="">Select One Code</option>');
                                res.forEach(element => {
                                    $("#tokenCode").append('<option value="' + element
                                        .id + '">' + element.tokenCode + '</option>'
                                    );
                                });


                            } else {
                                $("#tokenCode").empty();
                                $("#tokenCode").append(
                                    '<option value="">Select One Code</option>');
                            }
                        }
                    });
                } else {
                    $("#tokenCode").empty();
                    $("#tokenCode").append('<option value="">Select One Code</option>');
                }
            });

            function addCustomerInlist(id, customer_name, customer_mobile, userid) {
                if (customer_name == null) {
                    customer_name = '';
                }
                if (customer_mobile == null) {
                    customer_mobile = '';
                }
                $("#customer_list").append(
                    '<li class="list-group-item list-group-item-dark customer_li" style="background-color:skyblue;">' +
                    '<div class="row">' +
                    '<p><strong> ' + customer_name + '-(' + customer_mobile + ')</strong><br>' +
                    '<b >UserId: </b>' + userid + '<br>' +
                    '</p>' +
                    '<div class="col-md-6"><input type="hidden" class="customer_id" value="' + id +
                    '" name="reference_no" placeholder="Enter Name" ></div>' +
                    '<div class="col-md-6"><input type="hidden" class="customer_user_name" value="' + userid +
                    '" name="reference_no" placeholder="Enter Name" ></div>' +
                    '<div class="col-md-6"><input type="hidden" class="customer_name" value="' + customer_name +
                    '" name="reference_no" placeholder="Enter Name" ></div>' +
                    '<div class="col-md-6"><input type="hidden" class="customer_mobile" value="' +
                    customer_mobile + '" name="reference_no" placeholder="Enter Name" ></div>' +
                    '</div>' +
                    '</li>');
            }

            $("#search").keyup(function() {
                var search = $(this).val();
                if (search.length >= 2) {
                    // console.log(search.length);
                    $.ajax({
                        url: '{{ route('get-customer') }}',
                        method: "GET",
                        data: {
                            search: search
                        },
                        success: function(data) {
                            $("#customer_list").empty();
                            data.forEach(element => {
                                addCustomerInlist(element.id, element.clientsinfo
                                    .clients_name, element.clientsinfo.contact_no,
                                    element.userid);
                            });
                        }
                    });
                } else {
                    $("#customer_list").empty();

                }

            });

            $(document).on('click', '.customer_li', function() {
                var customer_cid = $(this).find('.customer_id').val();
                var customer_user_name = $(this).find('.customer_user_name').val();
                var customer_name = $(this).find('.customer_name').val();
                var customer_mobile = $(this).find('.customer_mobile').val();

                $("#clientId").val(customer_cid);
                $("#username").val(customer_user_name);
                $("#reportedBy").val(customer_name);
                $("#reporterContact").val(customer_mobile);
                $("#customer_list").empty();
                // $('#description').focus();
            });

            $('.assign_token_btn').click(function() {
                var token_id = $(this).parents("tr").find(".token_id_of_table").text();
                // console.log(token_id);
                $('#id_token_assign_model').val(token_id);
            });
            $('.close_token_btn').click(function() {
                var token_id = $(this).parents("tr").find(".token_id_of_table").text();
                // console.log(token_id);
                $('#id_token_close_model').val(token_id);
            });
            $('.re_assign_token_btn').click(function() {
                var token_id = $(this).parents("tr").find(".token_id_of_table").text();
                // console.log(token_id);
                $('#id_token_re_assign_model').val(token_id);
            });

            function addToTokenNoteTable(id, note, created_by, type, created_at, delete_permission) {
                let delete_btn = '';
                if (delete_permission == false) {
                    delete_btn = 'd-none'
                }
                let note_for = type;
                if (type == 'employee') {
                    note_for = 'Employee';
                } else {
                    note_for = 'Customer';
                }
                let d = moment(created_at).format('YYYY-MM-DD hh:mm:ss A');

                $('#token_note_table tbody').append(
                    '<tr>' +
                    '<td>' + id + '</td>' +
                    '<td><strong >' + note_for + '</strong></td>' +
                    '<td>' + d + '</td>' +
                    '<td>' + note + '</td>' +
                    '<td>' + created_by + '</td>' +
                    '<td class=' + delete_btn +
                    '><lable style="width: 40px" id="btnCancle" step=".01" class="btn btn-danger float-right">-</lable></td>' +
                    '</tr>'
                );
            }

            function addToTokenNoteShowTable(id, note, created_by, type, created_at, delete_permission) {
                let delete_btn = '';
                if (delete_permission == false) {
                    delete_btn = 'd-none'
                }
                let note_for = type;
                if (type == 'employee') {
                    note_for = 'Employee';
                } else {
                    note_for = 'Customer';
                }
                $('#token_note_table_show tbody').append(
                    '<tr>' +
                    '<td>' + id + '</td>' +
                    '<td><strong >' + note_for + '</strong></td>' +
                    '<td>' + created_at + '</td>' +
                    '<td>' + note + '</td>' +
                    '<td>' + created_by + '</td>' +
                    '<td class=' + delete_btn +
                    '><lable style="width: 40px" id="btnCancle" step=".01" class="btn btn-danger float-right">-</lable></td>' +
                    '</tr>'
                );
            }
            // Load notes when Add Note modal is shown (works for both static and DataTables-loaded rows)
            $('#addNoteModel').on('shown.bs.modal', function() {
                var token_id = $('#add_modal_token_id').val();
                if (!token_id) return;
                $.ajax({
                    type: "GET",
                    url: '{{ route('get-token-note') }}',
                    data: {
                        token_id: token_id
                    },
                    success: function(res) {
                        $('#token_note_table tbody').empty();
                        var list = res.token_notes || [];
                        var delete_permission = res.token_note_delete;
                        list.forEach(function(element) {
                            addToTokenNoteTable(element.id, element.note, element.user
                                .name, element.note_type, element.created_at,
                                delete_permission);
                        });
                    }
                });
            });

            $('.add_note').click(function() {
                var token_id = $(this).parents("tr").find(".token_id_of_table").text();
                $('#add_modal_token_id').val(token_id);
            });

            $(document).on("click", "#btnCancle", function() {
                let token_note_id = $(this).parents("tr").find("td").eq(0).text();
                $(this).closest("tr").remove();

                $.ajax({
                    type: "POST",
                    url: '{{ route('delete-token-note') }}',
                    data: {
                        token_note_id: token_note_id
                    },
                    success: function(res) {
                        if (res == 1) {
                            toastr.success('Note Deleted Successfully');
                        }
                    }
                });
            });

            $('.show_note').click(function() {
                var token_id = $(this).parents("tr").find(".token_id_of_table").text();
                // console.log(token_id);
                $('#add_modal_token_id').val(token_id);
                $.ajax({
                    type: "GET",
                    url: '{{ route('get-token-note') }}',
                    data: {
                        token_id: token_id
                    },
                    success: function(res) {
                        console.log(res);
                        $('#token_note_table_show tbody').empty();
                        let list = res.token_notes;
                        let delete_permission = res.token_note_delete;
                        list.forEach(element => {
                            addToTokenNoteShowTable(element.id, element.note, element
                                .user.name, element.note_type, element.created_at,
                                delete_permission);
                        });


                    }

                });
            });

            var tokenDetailTable = $('#tokenDetailDataTable');
            if (tokenDetailTable.length && !$.fn.DataTable.isDataTable('#tokenDetailDataTable')) {
                var dt = tokenDetailTable.DataTable({
                    processing: true,
                    serverSide: true,
                    ajax: {
                        url: "{{ route('token-detail-report-data', ['pop_id' => $pop_id, 'type' => $type]) }}",
                        type: 'GET'
                    },
                    columns: [{
                            data: 'id',
                            name: 'tokens.id',
                            orderable: true,
                            searchable: true
                        },
                        {
                            data: 'token_info',
                            name: 'tokens.token',
                            orderable: true,
                            searchable: false
                        },
                        {
                            data: 'category_code',
                            name: 'tokens.tokenCategory',
                            orderable: true,
                            searchable: false
                        },
                        {
                            data: 'description',
                            name: 'tokens.description',
                            orderable: true,
                            searchable: true
                        },
                        {
                            data: 'source',
                            name: 'tokens.token_source',
                            orderable: true,
                            searchable: false
                        },
                        {
                            data: 'creator',
                            name: 'creator',
                            orderable: false,
                            searchable: false
                        },
                        {
                            data: 'reseller',
                            name: 'reseller',
                            orderable: false,
                            searchable: false
                        },
                        {
                            data: 'pop',
                            name: 'pop',
                            orderable: false,
                            searchable: false
                        },
                        {
                            data: 'customer_id_username',
                            name: 'customer_id_username',
                            orderable: false,
                            searchable: false
                        },
                        {
                            data: 'customer_info',
                            name: 'customer_info',
                            orderable: false,
                            searchable: false
                        },
                        {
                            data: 'reporter_contact',
                            name: 'tokens.reportedBy',
                            orderable: false,
                            searchable: false
                        },
                        {
                            data: 'assigned',
                            name: 'tokens.assign_time',
                            orderable: true,
                            searchable: false
                        },
                        {
                            data: 'token_type',
                            name: 'tokens.token_type',
                            orderable: true,
                            searchable: false
                        },
                        {
                            data: 'actions',
                            name: 'actions',
                            orderable: false,
                            searchable: false
                        }
                    ],
                    order: [
                        [0, 'desc']
                    ],
                    pageLength: 25,
                    lengthMenu: [
                        [10, 25, 50, 100],
                        [10, 25, 50, 100]
                    ],
                    drawCallback: function(settings) {
                        $('#token-detail-total').text('Total Token: ' + settings.json.recordsFiltered);
                        // Re-bind modal/button handlers for rows loaded via AJAX
                        $('.close_token_btn, .assign_token_btn, .re_assign_token_btn, .add_note').off(
                            'click.tokenDetail').on('click.tokenDetail', function() {
                            var tr = $(this).closest('tr');
                            var tokenId = tr.find('.token_id_of_table').text() || tr.find(
                                'td:first').text().trim();
                            $('#id_token_close_model').val(tokenId);
                            $('#id_token_assign_model').val(tokenId);
                            $('#id_token_re_assign_model').val(tokenId);
                            $('#id_token_note_model').val(tokenId);
                            $('#add_modal_token_id').val(tokenId);
                        });
                    }
                });
            }

            $('#assignTokenModel').on('shown.bs.modal', function() {
                $('#employee_modal').select2({
                    dropdownParent: $('#assignTokenModel') // Fixes issues inside modals
                });
            });

            $('#reAssignTokenModel').on('shown.bs.modal', function() {
                $('#employee_re').select2({
                    dropdownParent: $('#reAssignTokenModel') // Fixes issues inside modals
                });
            });


        });
    </script>
@endsection
