@extends('layouts.app')

@section('content')
    <div class="container-fluid">
        <div class="row align-items-center">
            <div class="col-xl-3 col-md-12">
                <div class="mb-1">Всего найдено: {{ $products->total() }}</div>
                Выбрано: <span id="count_selected">0</span>
                <button class="btn btn-sm btn-primary mx-2 disabled" id="export-button" onclick="select_export()">Экспорт</button>
                <button class="btn btn-sm btn-primary" onclick="reset_selected()">Сбросить выбор</button>
                <button class="d-md-none btn btn-sm ms-2 btn-light" type="button" data-bs-target="#searchForm" data-bs-toggle="collapse"
                        aria-expanded="false" aria-controls="searchForm"
                >Фильтр</button>
            </div>
            <div class="col-xl-9 col-md-12 collapse d-md-block" id="searchForm">
                <form class="" action="" method="get">
                    <div class="row my-2 justify-content-center">
                        <div class="col-6 col-sm-6 col-md-auto">
                            <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-6 col-sm-6 col-md-auto">
                            <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="d-none d-md-block col-md-auto mt-3 mt-md-0">
                            <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="d-none d-md-block col-md-auto mt-3 mt-md-0">
                            <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="d-none d-md-block col-md-auto -md-0">
                            <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-12 col-md-auto  mt-md-1 text-center">
                            <button id="sb" class="btn btn-sm btn-primary mt-4" type="submit">Применить</button>
                            <a href="{{ route('index') }}" class="btn btn-sm 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 class="d-none d-md-table-cell">Цена,&nbsp;руб.</th>
                        <th class="d-none d-md-table-cell">Характеристики</th>
                        <th class="d-none d-md-table-cell">Техническое&nbsp;описание</th>
                        <th class="text-center ">Изображение</th>
                        <th class="d-none d-md-table-cell">Создан&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">
                                <a href="{{ route('view_product', $product->id) }}">
                                    {{ $product->article }}<br>
                                    {{ $product->series }}

                                </a>
                            </td>

                            <td class="d-none d-md-table-cell">{!! number_format($product->price, 2, ',', '&nbsp') !!}</td>
                            <td class="d-none d-md-table-cell">{!! nl2br($product->characteristics) !!}</td>
                            <td class="d-none d-md-table-cell" 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 class="d-none d-md-table-cell">{!! 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>
        </div>
        <div class="row">
            <div class="col-12">
                <div class="pagination pagination-sm justify-content-center">
                    {{ $products->onEachSide(0)->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;
                }
            }

            if(selected_products.length > 0){
                document.getElementById('export-button').classList.remove('disabled');
            } else {
                document.getElementById('export-button').classList.add('disabled');
            }


        }

        // 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
