@extends('layouts.admin')
@section('title')
{{ __('Set up order') }}
@endsection

@section('content')
<div class="page-content-wrapper">
    <div class="container-fluid">
        <div class="row">
            <div class="col-sm-12">
                <div class="page-title-box">


                    <h4 class="page-title mt-2">Set up order</h4>

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



        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-body">
                        <h4 class="mt-0 header-title">Set up order</h4>
                        <div class="row">
                            <div class="col-12 mb-3">
                                <h6 class="input-title mt-2">Balance : {{ $user->balance }}</h6>

                            </div>
                            <form class="form-inline col-md-12" id="filterForm">
                                @csrf
                                <div class="col-4 mb-3">
                                    <h6 class="input-title mt-2">Min Price</h6>
                                    <input type="text" class="form-control" maxlength="25" name="min_price" id="min_price" placeholder="enter Min Price" />
                                </div>
                                <div class="col-4 mb-3">
                                    <h6 class="input-title mt-2">Max Price</h6>
                                    <input type="text" class="form-control" maxlength="25" name="max_price" id="max_price" placeholder="enter Max Price" />
                                </div>
                                <div class="col-4 mt-4 ">


                                    <button type="button" id="filter" class="btn btn-primary waves-effect mt-3">Lookup</button>


                                </div>
                            </form>
                            <form class=" col-md-12" id="lockjourneyForm" method="POST" action="{{ route('lock.journey',$user->id) }}">
                                @csrf
                                <div class="repeater">
                                    <div data-repeater-list="journeys">


                                    </div>

                                </div>
                                <div class="col-12 mb-3">
                                    <button type="submit" id="lock-btn" class="btn btn-primary waves-effect mt-3">Lock Journey</button>
                                </div>
                            </form>




                        </div>
                        <div class="table-responsive py-4" id="productList">
                            <table class="table border-1">
                                <thead>
                                    <tr>
                                        <th>#</th>
                                        <th>Name</th>
                                        <th>Price</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach($products as $product)
                                    <tr>
                                        <td>
                                            <input type="checkbox" class="productCheckbox" name="selected_products" value="{{ $product->id }}"
                                                @if(!empty($user->lock_journey) && in_array($product->id, array_column(json_decode($user->lock_journey, true), 'current_setting')))
                                            checked
                                            @endif
                                            > {{ $product->id }}
                                        </td>
                                        <td>{{ $product->name }}</td>
                                        <td>{{ round($product->price * $product->qty,2) }}</td>
                                    </tr>
                                    @endforeach
                                </tbody>
                            </table>
                            <input type="hidden" id="savedJourneyData" value="{{ $user->lock_journey }}">

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

@endsection

@push('css')
<link rel="stylesheet" href="{{ asset('assets/admin/lib/datatables/dataTables.css') }}">
@include('layouts.includes.datatable_css')
@endpush
@push('javascript')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.repeater/1.2.1/jquery.repeater.min.js"></script>

<!-- <script src="{{ asset('assets/admin/lib/jquery/jquery-3.7.1.min.js') }}"></script> -->
<!-- <script src="{{ asset('assets/admin/lib/datatables/dataTables.js') }}"></script> -->
@include('layouts.includes.datatable_js')
<script>
    $(document).ready(function() {
        var selectedProducts = [];
        $(document).on("click", "#filter", function() {
            var formData = $('#filterForm').serialize();
            $.ajax({
                type: 'POST',
                url: '{{ route("filter.journey") }}',
                data: formData,
                success: function(response) {
                    $('#current_setting').val('');
                    $('#productList').html(response);
                    selectedProducts = [];
                }
            });
        });

        $('.repeater').repeater({
            initEmpty: true,
            defaultValues: {
                'lock_journey': '',
                'current_setting': ''
            },
            show: function() {
                $(this).slideDown();
                updateLockButton();
            },
            hide: function(deleteElement) {
                if ($('.repeater [data-repeater-item]').length > 1) {
                    if (confirm('Are you sure you want to delete this element?')) {
                        var productId = $(this).find('input[name="current_setting"]').val();
                        $(`.productCheckbox[value="${productId}"]`).prop('checked', false);
                        $(this).slideUp(deleteElement, function() {
                            $(this).remove();
                            updateLockButton();
                        });
                    }
                } else {
                    alert('At least one row must remain.');
                }
            }
        });

        $(document).on('click', '.productCheckbox', function() {
            var productId = $(this).val();
            var productName = $(this).data('name');
            var productPrice = $(this).data('price');

            if ($(this).is(':checked')) {
                var newItem = `
                    <div data-repeater-item class="row mb-3" data-product-id="${productId}">
                        <div class="col-md-4">
                            <input type="text" required class="form-control" value="" maxlength="25" name="lock_journey[]" id="lock_journey" placeholder="Enter lock journey count" />
                        </div>
                        <div class="col-md-4">
                            <input type="text" readonly="readonly" class="form-control" value="${productId}" maxlength="25" name="current_setting[]" id="current_setting" />
                        </div>
                        <div class="col-md-4">
                            <button type="button" class="btn btn-danger" data-repeater-delete>Delete</button>
                        </div>
                    </div>
                `;

                $('.repeater [data-repeater-list]').append(newItem);

                // Append labels only once
                if ($('.repeater .input-title').length === 0) {
                    var labels = `
                        <div class="row mb-3">
                            <div class="col-md-4">
                                <h6 class="input-title mt-2">Lock Num Of journey</h6>
                            </div>
                            <div class="col-md-4">
                                <h6 class="input-title mt-2">Current order settings</h6>
                            </div>
                            <div class="col-md-4">
                                <h6 class="input-title mt-2">Action</h6>
                            </div>
                        </div>
                    `;
                    $('.repeater [data-repeater-list]').prepend(labels);
                }

                updateLockButton();
            } else {
                if ($('.repeater [data-repeater-item][data-product-id]').length === 1) {
                    alert('At least one row must remain.');
                    $(this).prop('checked', true);
                    return;
                }
                $(`.repeater [data-repeater-item][data-product-id="${productId}"]`).remove();
                updateLockButton();
            }
        });

        function updateLockButton() {
            if ($('.repeater [data-repeater-item]').length > 0) {
                $('#lock-btn').show();
            } else {
                $('#lock-btn').hide();
            }
        }

        // Initial call to updateLockButton to handle pre-existing rows
        updateLockButton();

        // Load saved data and populate the repeater
        var savedJourneyData = $('#savedJourneyData').val();
        if (savedJourneyData) {
            var journeys = JSON.parse(savedJourneyData);
            journeys.forEach(function(journey) {
                var newItem = `
                    <div data-repeater-item class="row mb-3" data-product-id="${journey.current_setting}">
                        <div class="col-md-4">
                            <input type="text" required class="form-control" value="${journey.lock_journey}" maxlength="25" name="lock_journey[]" id="lock_journey" placeholder="Enter lock journey count" />
                        </div>
                        <div class="col-md-4">
                            <input type="text" readonly="readonly" class="form-control" value="${journey.current_setting}" maxlength="25" name="current_setting[]" id="current_setting" />
                        </div>
                        <div class="col-md-4">
                            <button type="button" class="btn btn-danger" data-repeater-delete>Delete</button>
                        </div>
                    </div>
                `;
                $('.repeater [data-repeater-list]').append(newItem);
            });

            // Append labels only once
            if ($('.repeater .input-title').length === 0) {
                var labels = `
                    <div class="row mb-3">
                        <div class="col-md-4">
                            <h6 class="input-title mt-2">Lock Num Of journey</h6>
                        </div>
                        <div class="col-md-4">
                            <h6 class="input-title mt-2">Current order settings</h6>
                        </div>
                        <div class="col-md-4">
                            <h6 class="input-title mt-2">Action</h6>
                        </div>
                    </div>
                `;
                $('.repeater [data-repeater-list]').prepend(labels);
            }

            updateLockButton();
        }


    });
</script>
@endpush