@extends('layouts.app')

@section('content')

    <div class="px-3">
        <div class="row mb-2">
            <div class="col-6">
                <h3>Площадка {{ $order->object_address }}</h3>
            </div>
            <div class="col-6 text-end">
                <a href="{{ route('order.edit', $order) }}" class="btn btn-primary">Редактировать</a>
                @if(hasRole('admin') && ($order->order_status_id == App\Models\Order::STATUS_NEW))
                    <a href="#" onclick="if(confirm('Удалить площадку?')) $('form#destroy').submit();"
                       class="btn btn-danger">Удалить</a>
                    <form action="{{ route('order.destroy', $order) }}" method="post" class="d-none" id="destroy">
                        @csrf
                        @method('DELETE')
                    </form>
                @endif
            </div>
        </div>
        <div class="row">
            <div class="col-xl-3">
                <h4>Общая информация об объекте</h4>
                <div>Название: {{ $order->name }}</div>
                <div>ID площадки: {{ $order->id }}</div>
                <div>
                    Адрес: {{ $order->common_name }}
                </div>

                <div>Тип объекта: {{ $order->objectType->name }}</div>
                <div>Статус объекта: {{ $order->orderStatus->name }}</div>
                <div>Комментарий: {{ $order->comment }}</div>
                <div>Дата выхода на монтаж: {{ $order->installation_date }}</div>
                <div>Дата готовности площадки: {{ $order->ready_date }}</div>
                <div>Бригадир: {{ $order?->brigadier?->name }}, тел. {{ $order?->brigadier?->phone }}</div>
                <div>Менеджер: {{ $order->user->name }}, тел. {{ $order->user->phone }}</div>
                <div>Название группы в ТГ: {{ $order->tg_group_name }}</div>
                <div>Ссылка на группу в ТГ: {{ $order->tg_group_link }}</div>
                <hr>
                <div class="photo">
                    Фотографии <button class="btn btn-sm text-success" onclick="$('#upl-photo').trigger('click');"><i class="bi bi-plus-circle-fill"></i> Загрузить</button>
                    <form action="{{ route('order.upload-photo', $order) }}" enctype="multipart/form-data" method="post" class="visually-hidden">
                        @csrf
                        <input required type="file" id="upl-photo" onchange="$(this).parent().submit()" multiple name="photo[]" class="form-control form-control-sm" accept=".jpg,.jpeg,.png">
                    </form>
                    <div class="row my-2 g-1">
                        @foreach($order->photos as $photo)
                            <div class="col-4">
                                <a href="{{ $photo->link }}"
                                   data-toggle="lightbox" data-gallery="photos" data-size="fullscreen">
                                    <img class="img-thumbnail" src="{{ $photo->link }}" alt="">
                                </a>
                                @if(hasRole('admin'))
                                    <i class="bi bi-x-circle-fill fs-6 text-danger cursor-pointer rm-but"
                                       onclick="if(confirm('Удалить фото?')) $('#photo-{{ $photo->id }}').submit()"
                                       title="Удалить"></i>
                                @endif
                                <form action="{{ route('order.delete-photo', [$order, $photo]) }}" method="POST" id="photo-{{ $photo->id }}" class="visually-hidden">
                                    @csrf
                                    @method('DELETE')
                                </form>
                            </div>
                        @endforeach
                    </div>
                </div>

                <hr>

                <div class="documents">
                    Документы <button class="btn btn-sm text-success" onclick="$('#upl-documents').trigger('click');"><i class="bi bi-plus-circle-fill"></i> Загрузить</button>
                    <form action="{{ route('order.upload-document', $order) }}" enctype="multipart/form-data" method="post" class="visually-hidden">
                        @csrf
                        <input required type="file" id="upl-documents" onchange="$(this).parent().submit()" multiple name="document[]" class="form-control form-control-sm">
                    </form>
                    <div class="row my-2 g-1">
                        @foreach($order->documents as $document)
                            <div class="col-12">
                                <a href="{{ $document->link }}">
                                    {{ $document->original_name }}
                                </a>
                                @if(hasRole('admin'))
                                    <i class="bi bi-x-circle-fill fs-6 text-danger cursor-pointer ms-2"
                                       onclick="if(confirm('Удалить?')) $('#document-{{ $document->id }}').submit()"
                                       title="Удалить"></i>
                                @endif
                                <form action="{{ route('order.delete-document', [$order, $document]) }}" method="POST" id="document-{{ $document->id }}" class="visually-hidden">
                                    @csrf
                                    @method('DELETE')
                                </form>
                            </div>
                        @endforeach
                    </div>
                </div>
                <hr>
                <div class="statements">
                    Ведомости <button class="btn btn-sm text-success" onclick="$('#upl-statements').trigger('click');"><i class="bi bi-plus-circle-fill"></i> Загрузить</button>
                    <form action="{{ route('order.upload-statement', $order) }}" enctype="multipart/form-data" method="post" class="visually-hidden">
                        @csrf
                        <input required type="file" id="upl-statements" onchange="$(this).parent().submit()" multiple name="statement[]" class="form-control form-control-sm">
                    </form>
                    <div class="row my-2 g-1">
                        @foreach($order->statements as $statement)
                            <div class="col-12">
                                <a href="{{ $statement->link }}">
                                    {{ $statement->original_name }}
                                </a>
                                @if(hasRole('admin'))
                                    <i class="bi bi-x-circle-fill fs-6 text-danger cursor-pointer ms-2"
                                       onclick="if(confirm('Удалить?')) $('#statement-{{ $statement->id }}').submit()"
                                       title="Удалить"></i>
                                @endif
                                <form action="{{ route('order.delete-statement', [$order, $statement]) }}" method="POST" id="statement-{{ $statement->id }}" class="visually-hidden">
                                    @csrf
                                    @method('DELETE')
                                </form>
                            </div>
                        @endforeach
                    </div>
                </div>


            </div>
            <div class="col-xl-9">
                <h4>МАФы заказа</h4>

                <div id="selected_maf">
                    @if(isset($order) && $order->products_sku)
                        <table class="table">
                            <thead>
                            <tr>
                                <th><input type="checkbox" class="form-check" id="check-all-maf"></th>
                                <th>МАФ</th>
                                <th>Тип</th>
                                <th>Статус</th>
                                <th>Номер заказа МАФ</th>
                                <th>RFID</th>
                                <th>Заводской номер</th>
                                <th>Дата производства</th>
                                <th>Срок эксплуатации</th>
                                <th>Склад</th>
                            </tr>
                            </thead>
                            <tbody>
                            @php
                                $needs = $order->getNeeds();
                            @endphp
                            @foreach($order->products_sku as $p)
                                <tr>
                                    <td>
                                        <input type="checkbox" class="form-check check-maf" data-maf-id="{{ $p->id }}">
                                    </td>
                                    <td>
                                        <a href="{{ route('product_sku.show', $p) }}">
                                            {!! $p->product->article !!}
                                        </a>
                                    </td>
                                    <td>{!! $p->product->nomenclature_number !!}</td>
                                    <td>{{ $p->status }}</td>
                                    <td>{{ $p->maf_order?->order_number }}</td>
                                    <td>{{ $p->rfid }}</td>
                                    <td>{{ $p->factory_number }}</td>
                                    <td>{{ $p->manufacture_date }}</td>
                                    <td>{{ $p->service_life }}</td>
                                    <td class="text-center">
                                        @if($p->maf_order?->order_number)
                                            <i class="bi bi-check-all text-success fw-bold"></i>
                                        @else
                                            @if($needs[$p->product_id]['sku']-- > 0)
                                                <i class="bi bi-check text-success fw-bold"></i>
                                            @else
                                                <i class="bi bi-x text-danger fw-bold"></i>
                                            @endif
                                        @endif
                                    </td>
                                </tr>
                            @endforeach
                            </tbody>
                        </table>
                        <div>
                            <a href="{{ route('order.get-maf', $order) }}" class="btn btn-primary btn-sm @disabled($order->ready_to_mount == 'Нет' )">Привязать все МАФы</a>
                            <a href="{{ route('order.revert-maf', $order) }}" class="btn btn-primary btn-sm">Отвязать все МАФы</a>
                            <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#moveModal">Перенести МАФы</button>
                        </div>
                    @endif
                </div>

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


    <!-- Модальное окно переноса -->
    <div class="modal fade" id="moveModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-fullscreen-sm-down modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h1 class="modal-title fs-5" id="addModalLabel">Выбрать площадку, куда переносим</h1>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрыть"></button>
                </div>
                <div class="modal-body">
                    <form action="{{ route('order.move-maf') }}" method="post">
                        @csrf
                        <div id="select_maf_form">
                            <input type="text" class="form-control mb-2" placeholder="Поиск площадки" id="search_order">
                            <select id="select_order" name="new_order_id" class="form-select mb-3" size="30" multiple required></select>
                            <a href="#" class="btn btn-primary" id="moveMaf">Перенести</a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

@endsection


@push('scripts')
    <script type="module">
        // select order
        $('#search_order').on('keyup', function () {
            // search products on backend
            $.get('{{ route('order.search') }}?s=' + $(this).val(),
                function (data) {
                    $('#select_order').children().remove()
                    $.each(data, function (id, name) {
                        $('#select_order').append('<option value=\'' + id + '\'>' + name + '</option>');
                    });
                }
            );
        }).trigger('keyup');



        $('#check-all-maf').on('change', function () {
            $('input:checkbox.check-maf').not(this).prop('checked', this.checked);
        });

        // move maf
        $('#moveMaf').on('click', function () {
            let ids = Array();
            $('.check-maf').each(function () {
                if ($(this).prop('checked')) {
                    ids.push($(this).attr('data-maf-id'));
                }
            });

            $.post('{{ route('order.move-maf') }}',
                {
                    '_token': $('meta[name=csrf-token]').attr('content'),
                    ids: JSON.stringify(ids),
                    'new_order_id': $('#select_order').find(":selected").val()
                },
                function () {
                    location.reload();
                }
            );
        });


    </script>
@endpush