@extends('layouts.app')

@section('content')
    <div class="container-fluid">
        <div class="row align-items-center">
            <div class="col-xl-5 col-md-12">
                <div class="mb-1">Всего найдено: {{ $products->total() }}</div>
{{--                {{ $products->links() }}--}}
                Выбрано: <span id="count_selected">0</span>
                <button class="btn btn-sm btn-primary mx-3" onclick="select_export()">Экспорт</button>
                <button class="btn btn-sm btn-primary" onclick="reset_selected()">Сбросить выбор</button>
            </div>
            <div class="col-xl-7 col-md-12">
                <form class="" action="" method="get">
                    <div class="row my-2 justify-content-center">
                        <div class="col">
                            <label class="form-label" for="s">Поиск</label>
                            <input class="form-control form-control-sm"
                                   value="{{ $s ?? '' }}"
                                   type="text" id="s" name="s" placeholder="Поиск">
                        </div>
                        <div class="col">
                            <label class="form-label " for="series">Серия</label>
                            <select class="form-select form-select-sm" name="s_series" id="series">
                                <option value="">Все</option>
                                @foreach($series as $ser)
                                    <option {{ (isset($s_series) && ($ser->series == $s_series)) ? 'selected' : '' }} >{{ $ser->series }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col">
                            <label class="form-label " for="price_min">Цена от</label>
                            <input class="form-control form-control-sm"
                                   value="{{ $s_price_min ?? '' }}"
                                   type="number" id="price_min" name="s_price_min">
                        </div>
                        <div class="col">
                            <label class="form-label " for="price_max">Цена до</label>
                            <input class="form-control form-control-sm"
                                   value="{{ $s_price_max ?? '' }}"
                                   type="number" id="price_max" name="s_price_max">
                        </div>
                        <div class="col-auto">
                            <label class="form-label" for="perpage">На странице</label>
                            <select class="form-select form-select-sm" id="perpage" name="perpage">
                                <option {{ (isset($perpage) && ($perpage == 20)) ? 'selected' : '' }} value="20">20
                                </option>
                                <option {{ (isset($perpage) && ($perpage == 100)) ? 'selected' : '' }} value="100">100
                                </option>
                                <option {{ (isset($perpage) && ($perpage == 10000)) ? 'selected' : '' }} value="10000">
                                    Все
                                </option>
                            </select>
                        </div>
                        <div class="col-auto">
                            <button id="sb" class="btn btn-primary mt-4" type="submit">Поиск</button>
                            <a href="{{ route('index') }}" class="btn btn-light mt-4 ms-1">Сброс</a>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <div class="row">
            <div class="col-12">
                <table class="table">
                    <thead>
                    <tr class="align-top">
                        <th class="text-center">
                            <label>Все<br><input type="checkbox" class="check_all" onchange="toggle(this)"></label>
                        </th>
                        <th class="text-center">Артикул</th>
{{--                        <th>Группа <br> Наименование <br> Наименование под образец формы</th>--}}
                        <th>Цена,&nbsp;руб.</th>
                        <th>Характеристики</th>
                        <th>Техническое&nbsp;описание</th>
                        <th class="text-center ">Изображение</th>
                        <th>Создан&nbsp;/&nbsp;Изменён</th>
                    </thead>
                    </tr>
                    <tbody>
                    @foreach($products as $product)
                        <tr class="align-middle prod-tr">
                            <td class="text-center"><input type="checkbox" onchange="select_product({{ $product->id }}, this)" class="form-check-inline me-0 prd-chk" name="ids" value="{{ $product->id }}"></td>
                            <td class="text-center">
                                <label>
                                    {{ $product->article }}<br>
                                    {{ $product->series }}

                                </label>
                            </td>

{{--                            <td>--}}
{{--                                <a href="{{ route('view_product', $product->id) }}">--}}
{{--                                    <strong>Группа:</strong> {{ $product->product_group }}<br>--}}
{{--                                    <strong>Наименование:</strong> {{ $product->name }}<br>--}}
{{--                                    <strong>Наименование под образец формы:</strong> {{ $product->name_for_form }}--}}
{{--                                </a>--}}
{{--                            </td>--}}
                            <td>{!! number_format($product->price, 2, ',', '&nbsp') !!}</td>
                            <td>
                                <a href="{{ route('view_product', $product->id) }}">
                                    {!! nl2br($product->characteristics) !!}
                                </a>
                            </td>
                            <td title="{{ $product->tech_description }}" style="font-size: small">{!! Str::words(nl2br($product->tech_description), 22) !!}</td>
                            <td class="text-center align-middle">
                                @empty($product->image_path)
                                    Нет изображения
                                @else
                                    <img class="img-fluid" style="max-height: 80px"
                                         src="{{ '/' . env('IMAGES_PATH', '/fill_images_path_in_env') . '/' . $product->image_path }}"
                                         alt="{{ $product->article }}">
                                @endempty
                            </td>
                            <td>{!! date('d.m.Y_H:i', strtotime($product->created_at)) . '<br>' .date('d.m.Y_H:i', strtotime($product->updated_at)) !!}</td>
                        </tr>
                    @endforeach
                    </tbody>
                </table>
                <div class="d-flex">
                    {{ $products->links() }}
                </div>
            </div>
        </div>
    </div>

    <form action="{{ route('select_export') }}" method="post" class="visually-hidden" id="select_export">
        @csrf
        <textarea name="ids" id="ids"></textarea>

    </form>

    <script>

        // select all on page
        function toggle(source) {
            let checkboxes = document.querySelectorAll('.prd-chk');
            for(let i =0; i < checkboxes.length; i++){
                checkboxes[i].checked = source.checked;
                select_product(checkboxes[i].value, source);
            }
            calc_selected();
        }

        // select an deselect product to localstorage
        function select_product(id, status){
            let selected_products = JSON.parse(localStorage.getItem('selected_products'));
            if(!selected_products) selected_products = [];

            // console.log(status.checked);

            if(status.checked){
                // console.log('select '+id);
                if(!selected_products.includes(id.toString())){
                    selected_products.push(id.toString());
                }

            } else {

                const index = selected_products.indexOf(id.toString());
                if(index > -1){
                    selected_products.splice(index, 1);
                    // console.log('deselect '+id);
                }
            }

            localStorage.setItem('selected_products', JSON.stringify(selected_products));
            calc_selected();
        }

        // calcculate selected products and set checkboxes
        function calc_selected(){
            let selected_products = JSON.parse(localStorage.getItem('selected_products'));
            if(!selected_products) selected_products = [];
            document.getElementById('count_selected').innerText = selected_products.length;

            let checkboxes = document.querySelectorAll('.prd-chk');
            for(let i =0; i < checkboxes.length; i++){

                if(selected_products.includes(checkboxes[i].value)){
                    checkboxes[i].checked = true;
                }
            }
        }

        // reset all selected (flush localstorage var)
        function reset_selected(){
            localStorage.setItem('selected_products', JSON.stringify([]));
            let checkboxes = document.querySelectorAll('.prd-chk');
            for(let i =0; i < checkboxes.length; i++) {
                checkboxes[i].checked = false;
            }
            document.querySelector('.check_all').checked = false;

            calc_selected();
        }

        // send selected ids by form
        function select_export(){
            let selected_products = localStorage.getItem('selected_products')
            //document.location = '{{ route('select_export') }}?ids='+selected_products;
            document.getElementById('ids').value = selected_products;
            document.getElementById('select_export').submit();
        }

        // on page load set checkboxes and calculate selected count
        calc_selected();

    </script>

@endsection
