@extends('layout.app')


@section('content')
    {{-- add mikrotik --}}
    <x-mikrotik.addMikrotik />



    <div class="card mx-auto">
        <div class="d-flex justify-content-between border p-2">
            <h1 class="card-title float-left">Mikrotiks information
            </h1>
            <div class="">

                @can('mikrotik_create')
                    <button type="button" class="btn" data-toggle="modal" data-target="#form"
                        style="background: #FF9F43; color:#FFFFFF;">
                        <span><i class="fa-solid fa-plus"></i></span> Add Mikrotik
                    </button>
                @endcan
            </div>
        </div>
        <div class="card-body">
            <div class="table-responsive ">
                <table id="dataTable" class=" table-bordered">
                    <thead style="background: #78716C !important;color:#FFFFFF;">
                        <tr class="table-head-info">
                            <th scope="col">
                                ID
                            </th>
                            <th scope="col" class="text-center">
                                Mikrotik IP
                            </th>
                            @if (!checkAPI())
                                <th scope="col">
                                    Secret
                                </th>
                            @endif
                            <th scope="col">
                                Mikrotik Name
                            </th>
                            {{-- <th scope="col">
                                Type
                            </th> --}}

                            <th scope="col">
                                Description
                            </th>

                            <th scope="col" class="text-center">
                                Action
                            </th>
                        </tr>
                    </thead>
                    <tbody>

                        @foreach ($nas as $item)
                            <tr>
                                <td class="text-center">
                                    {{ $item->id }}
                                </td>
                                <td class="text-start">

                                    @if (auth()->user()->email !== 'limitedyetfix@gmail.com' && $item->nasname == '103.126.151.206')
                                        <p>Not Available</p>
                                    @else
                                        {{ $item->nasname }}
                                    @endif
                                </td>
                                @if (!checkAPI())
                                    <td class="text-start">
                                        {{ $item->secret }}
                                    </td>
                                @endif
                                <td class="text-start">

                                    @if (auth()->user()->email !== 'limitedyetfix@gmail.com' && $item->nasname == '103.126.151.206')
                                        <p>Not Available</p>
                                    @else
                                        {{ $item->shortname }}
                                    @endif

                                </td>

                                <td>
                                    @if (auth()->user()->email !== 'limitedyetfix@gmail.com' && $item->nasname == '103.126.151.206')
                                        <p>Not Available</p>
                                    @else
                                        {{ $item->description }}
                                    @endif

                                </td>

                                @if (auth()->user()->email !== 'limitedyetfix@gmail.com' && $item->nasname == '103.126.151.206')
                                    <td>
                                        <p>Not Available</p>
                                    </td>
                                @else
                                    <td class="d-flex justify-content-center align-items-center" style="gap: 0.95px ">
                                        @if (checkAPI() || checkSettings('mikrotik_test_connection') == 'enable')
                                            @can('test-mikrotik')
                                                <a href="{{ route('test-mikrotik-connection', $item->id) }}"
                                                    class="btn border  " style="background:#0d9488; color:#FFFFFF;"><span
                                                        style="font-size: 12px !important;"> <span><i
                                                                class="fa-solid fa-person-running"></i></span> Run</span>
                                                </a>
                                                <a href="{{ route('mikrotik.network-diagnostic', $item->id) }}"
                                                    class="btn border" style="background: linear-gradient(135deg, #0f172a, #1e293b); color: #22d3ee; border-color: #22d3ee !important;"><span
                                                        style="font-size: 12px !important;"><i
                                                            class="fa-solid fa-network-wired"></i> Diagnostic</span>
                                                </a>
                                            @endcan
                                        @endif
                                        @if (auth()->user()->email == 'limitedyetfix@gmail.com' && checkAPI())
                                            <a href="{{ route('mikrotiks.secrets', $item->id) }}" class="btn border"
                                                style="background:#280d94bd; color:#FFFFFF;"><span
                                                    style="font-size: 12px !important;"> <span><i
                                                            class="fa-solid fa-users"></i></span> Secrets</span>
                                            </a>
                                        @endif

                                        @can('mikrotik_edit')
                                            <button onclick="editMiktorik({{ $item->id }}, '{{ auth()->user()->email }}')"
                                                class="btn border btn-success text-light " type="button" data-toggle="modal"
                                                data-target="#edit-mikrotik-{{ $item->id }}" data-toggle="tooltip"
                                                data-placement="bottom" title="Edit">
                                                <span><i class="fa-solid fa-pen-to-square "></i></span>
                                            </button>
                                        @endcan



                                        <div class="modal fade " id="edit-mikrotik-{{ $item->id }}" tabindex="-1"
                                            role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
                                            <div class="modal-dialog modal-dialog-centered " role="document">
                                                <div class="modal-content p-3">
                                                    <div class="modal-header border-bottom-0">
                                                        <button type="button" class="close" data-dismiss="modal"
                                                            aria-label="Close">
                                                            <span aria-hidden="true" class="text-danger">&times;</span>

                                                        </button>

                                                    </div>
                                                    <div class="border p-1 text-center rounded"
                                                        style="width: 95% !important; margin:auto !important">
                                                        <h4>Edit Mikrotik Information {{ $item->id }}</h1>

                                                            {{-- @if (auth()->user()->email == 'limitedyetfix@gmail.com')
                                                                <p class="" id="mikrotik-port-info"
                                                                    style="margin-top:-5px;"></p>
                                                            @endif --}}

                                                    </div>
                                                    <div id="formElements-{{ $item->id }}">

                                                    </div>
                                                </div>
                                            </div>
                                        </div>



                                        @can('view-nas-log-history')
                                            <a href="{{ route('editLog-history', ['id' => $item->id, 'type' => 'Mikrotik']) }}"
                                                class="btn border btn-warning text-light" data-toggle="tooltip"
                                                data-placement="bottom" title="History"> <span><i
                                                        class="fa-solid fa-timeline"></i></span> </a>
                                        @endcan


                                        @can('mikrotik_destroy')
                                            <form action="{{ route('mikrotiks.destroy', $item->id) }}" method="POST"
                                                style="margin-top: 14px !important;">
                                                @csrf
                                                @method('DELETE')
                                                <button type="submit" class="btn border bg-danger "
                                                    onclick="return confirm('Are you sure to delete it?')" data-toggle="tooltip"
                                                    data-placement="bottom" title="Delete"> <span><i
                                                            class="fa-solid fa-trash-can text-light"></i></span> </button>
                                            </form>
                                        @endcan


                                    </td>
                                @endif
                            </tr>


                            <p id="auth-{{ $item->id }}" class="sr-only">
                                @if (auth()->user()->email == 'limitedyetfix@gmail.com')
                                    Auth
                                @else
                                    Unauth
                                @endif
                            </p>
                        @endforeach

                        <!-- More items... -->
                    </tbody>
                </table>
            </div>
        </div>
        <div class="card-footer">
            {{ $nas->links() }}

        </div>
    </div>
    <style>
        .modal-backdrop {
            pointer-events: none !important;
        }
    </style>
@endsection


@push('styles')
    <link rel="stylesheet" href="{{ asset('css/mikrotik/mikrotiklist.css') }}">

@endpush




<script>
    async function editMiktorik(mikrotikId, email) {
        const url = `/api/mikrotik-information/${mikrotikId}/${email}`;
        const response = await fetch(url);
        const data = await response.json();
        const loginUser = document.getElementById(`auth-${mikrotikId}`).textContent;
        const mikrotikInfo = document.getElementById("mikrotik-port-info");

        console.log(loginUser);

        // if (data.services && loginUser.trim() == 'Auth'.trim()) {
        //     const mikrotikNameAndPort = data.services.find((items) => items.name === 'winbox');
        //     mikrotikInfo.innerHTML =
        //         `<p> <strong>Winbox Port : </strong> ${mikrotikNameAndPort.port}</p>`;
        // }
        /* dom operation */
        const domForOperation = document.getElementById(`edit-mikrotik-${mikrotikId}`);

        const formElement = document.getElementById(`formElements-${mikrotikId}`);



        formElement.innerHTML = `<form action="{{ url('admin/mikrotiks/${mikrotikId}') }}" method="POST">

               @method('PUT')
               @csrf
                <div class="modal-body" style="z-index: 1000;">
                    <div class="d-flex justify-content-between mobile-column" style="gap:2px;">
                        <div class="form-group" style="width: 48%;">
                            <label for="mikrotik name">Mikrotik Name <span class="text-danger"
                                    style="font-size: 1.25rem; display:inline-block;">*</span> </label>
                            <input type="text" name="shortname" class="form-control" id="shortname"
                                value="${data.nas.shortname}" placeholder="Mikrotik Name">

                            @error('shortname')
                                <small class="form-text  text-danger">{{ $message }}</small>
                            @enderror
                        </div>

                        <div class="form-group" style="width: 48%;">
                            <label for="mikrotikip">Mikrotik IP <span class="text-danger"
                                    style="font-size: 1.25rem; display:inline-block;">*</span> </label>
                            <input type="text" name="nasname" class="form-control" placeholder="Mikrotik IP"
                                value="${data.nas.nasname}" autocomplete="off">
                            @error('nasname')
                                <small class="form-text  text-danger">{{ $message }}</small>
                            @enderror
                        </div>
                    </div>

                    @if (!checkAPI())
                        <div class="form-group">
                            <label for="secret" class="">
                                Secret*
                            </label>
                            <input type="text" name="secret" id="secret" class="form-control"
                                placeholder="" value="${data.nas.secret}" autocomplete="off"
                                required>
                            @error('secret')
                                <small class="form-text text-danger">
                                    {{ $message }}
                                </small>
                            @enderror
                        </div>
                    @endif

                    <div class="form-group">
                        <label for="username">Mikrotik User Name </label>
                        <input type="text" name="mickrotik_user_name" value="${data.nas.mikrotick_user}" class="form-control"
                            placeholder="Mikrotik Username">
                        @error('mickrotik_user_name')
                            <small class="form-text  text-danger">{{ $message }}</small>
                        @enderror
                    </div>


                    <div class="d-flex flex-row-reverse justify-content-between mobile-column">
                        <div class="form-group " style="width: 48%;">
                            <label for="mikrotik port">Mikrotik Port</label>
                            <input type="text" name="mickrotik_port" value="${data.nas.mikrotick_port}"
                                class="form-control border rounded border-primary" placeholder="Mikrotik Port">
                            @error('mickrotik_port')
                                <small class="form-text  text-danger">{{ $message }}</small>
                            @enderror
                        </div>

                        <div class="form-group " style="width: 48%;">
                            <label for="password">Password</label>
                            <input type="text" name="mickrotik_user_password"
                                value="${data.nas.mikrotick_user_password}" class="form-control"
                                id="password1" placeholder="Password">
                            @error('mickrotik_user_password')
                                <small class="form-text  text-danger">{{ $message }}</small>
                            @enderror
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="password1">Description <span class="text-danger"
                                style="font-size: 1.25rem; display:inline-block;">*</span> </label>
                        <textarea class="form-control" name="description"  cols="3" rows="2">${data.nas.description}</textarea>
                        @error('description')
                            <small class="form-text  text-danger">{{ $message }}</small>
                        @enderror
                    </div>

                    @if (checkSettings('static_ip_manage') == 'enable')
                        <div class="form-group">



                            <div class="d-flex justify-content-between align-items-center">
                                <button type="button" class=" btn btn-color" id="static_ip_button-edit-${data.nas.id}">Add Static Ip
                            </button>

                            </div>


                            <div class="w-100 p-2 border rounded mt-2 d-none" id="staticIpContainer-edit-${data.nas.id}"
                                style="height: 160px; overflow-y: auto;">
                                <ul class="list-group" id="staticIpList-edit-${data.nas.id}">

                                </ul>
                            </div>

                        </div>
                    @endif
                </div>
                <div class="modal-footer border-top-0 d-flex justify-content-center">
                    <button type="submit" class="btn btn-submit w-100">Submit</button>
                </div>
            </form>`;



        const staticIpCreator = document.getElementById(`static_ip_button-edit-${mikrotikId}`);
        const staticIpContainer = document.getElementById(`staticIpContainer-edit-${mikrotikId}`);
        const staticIpList = document.getElementById(`staticIpList-edit-${mikrotikId}`);



        if (data.nas.ip_block) {

            const ipBlocks = JSON.parse(data.nas.ip_block);
            staticIpContainer.classList.remove('d-none');
            staticIpContainer.classList.add('d-block');
            staticIpCreator.textContent = "Add More";

            ipBlocks.forEach((item) => {
                const ipNode = document.createElement('li');
                ipNode.className = "list-group-item d-flex justify-content-between";
                ipNode.style.gap = "2px";
                ipNode.innerHTML = `
                <input type="text" name="port[]" value="${item.port}" class="form-control" placeholder="Ethernet Interface" required>
                <input type="text" name="ip_block[]" value="${item.ip_block}" class="form-control" placeholder="Ip Block" required>
                <button class="text-danger p-1 border rounded delete-button">X</button>`;

                staticIpContainer.appendChild(ipNode);
                staticIpList.appendChild(ipNode);


                const deleteButton = ipNode.querySelector('.delete-button');

                deleteButton.addEventListener('click', function() {
                    staticIpList.removeChild(ipNode);
                    if (staticIpList.children.length <= 3) {
                        staticIpList.classList.remove("scrollable-list");
                    }
                    if (staticIpList.children.length === 0) {
                        staticIpContainer.classList.remove("d-block");
                        staticIpContainer.classList.add('d-none');
                        staticIpCreator.textContent = "Add Static Ip";
                    }
                });
            });

            staticIpCreator.addEventListener("click", function() {
                if (staticIpContainer.classList.contains('d-none')) {
                    staticIpContainer.classList.remove('d-none');
                    staticIpContainer.classList.add("d-block");
                    staticIpCreator.textContent = "Add More";
                }

                const newListItem = document.createElement('li');
                newListItem.className = "list-group-item d-flex justify-content-between";
                newListItem.style.gap = "2px";

                newListItem.innerHTML = `
                    <input type="text" name="port[]" class="form-control" placeholder="Ethernet Interface" required>
                    <input type="text" name="ip_block[]" class="form-control" placeholder="Ip Block" required>
                    <button class="text-danger p-1 border rounded delete-button">X</button>`;


                const deleteButton = newListItem.querySelector('.delete-button');

                deleteButton.addEventListener('click', function() {
                    staticIpList.removeChild(newListItem);
                    if (staticIpList.children.length <= 3) {
                        staticIpList.classList.remove("scrollable-list");
                    }
                    if (staticIpList.children.length === 0) {
                        staticIpContainer.classList.remove("d-block");
                        staticIpContainer.classList.add('d-none');
                        staticIpCreator.textContent = "Add Static Ip";
                    }
                });
                staticIpList.appendChild(newListItem);

            });


        } else {

            staticIpCreator.addEventListener("click", function() {
                if (staticIpContainer.classList.contains('d-none')) {
                    staticIpContainer.classList.remove('d-none');
                    staticIpContainer.classList.add("d-block");
                    staticIpCreator.textContent = "Add More";
                }

                const newListItem = document.createElement('li');
                newListItem.className = "list-group-item d-flex justify-content-between";
                newListItem.style.gap = "2px";

                newListItem.innerHTML = `
            <input type="text" name="port[]" class="form-control" placeholder="Ethernet Interface" required>
            <input type="text" name="ip_block[]" class="form-control" placeholder="Ip Block" required>
            <button class="text-danger p-1 border rounded delete-button">X</button>`;

                const deleteButton = newListItem.querySelector('.delete-button');

                deleteButton.addEventListener('click', function() {
                    staticIpList.removeChild(newListItem);
                    if (staticIpList.children.length <= 3) {
                        staticIpList.classList.remove("scrollable-list");
                    }
                    if (staticIpList.children.length === 0) {
                        staticIpContainer.classList.remove("d-block");
                        staticIpContainer.classList.add('d-none');
                        staticIpCreator.textContent = "Add Static Ip";
                    }
                });
                staticIpList.appendChild(newListItem);

            });
        }


    }
</script>
