@extends('shop.layouts.app')

@section('content')
    <x-page-banner title="Select Packages" subTitle="Prepared, Packed & Delivered the same day"/>

    <section class="section-padding">
        <div class="container">
            <form class="row" action="" method="POST">
                @csrf
                <div class="col-md-4">
                    <div class="row align-items-center">
                        <div class="col-md-12">
                            <h1 class="text-left">Choose Your Package</h1>
                        </div>

                        @forelse ($packages as $package_key => $package)
                            <div class="col-md-12 pl-8 pr-8">
                                <div class="packagesbox">
                                    <div class="boxcontent text-center">{{ $package->name ?? '' }}</div>
                                    <div class="row package-price-container">
                                        @foreach ($package->package_price as $price_key => $price)
                                            <div class="col-md-{{ 12/ count($package->package_price) }} no-padding package-price-item">
                                                <div class="choosedates">
                                                    <div class="form-check text-center">
                                                        <input
                                                            class="form-check-input package-days"
                                                            type="radio"
                                                            data-day="{{ $price->days ?? 0 }}"
                                                            data-range="{{ $package->days_range }}"
                                                            data-price="{{ $price->price }}"
                                                            value="{{ $price->id }}"
                                                            name="package"
                                                            @if($package_key == 0 ) checked @endif
                                                            id="{{ $package->id.'_'.$price->id }}"
                                                        >
                                                        <label class="form-check-label" for="{{ $package->id.'_'.$price->id }}">
                                                           {{  $price->days ?? '' }} Days
                                                        </label>
                                                    </div>
                                                    <label class="price text-center block" for="{{ $package->id.'_'.$price->id }}">${{ $price->price ?? '' }}</label>
                                                </div>
                                            </div>
                                        @endforeach

                                    </div>
                                </div>
                            </div>
                        @empty
                            <h2 class="text-center">No result found</h2>
                        @endforelse

                    </div>
                </div>{{-- end packege selection --}}

                <div class="col-md-5">
                    <div class="">
                        <h1>Choose Dates</h1>
                        <div class="input-group date form-group datepicker-div">
                            <div  id="datepicker"> </div>
                            <span class="input-group-addon">
                                <i class="glyphicon glyphicon-calendar"></i>
                                <span class="dates-list"></span>
                            </span>
                        </div>
                    </div>

                    <div class="col-md-12">
                        <div class="row">
                            <div class="col-md-3 text-center">
                                <button class="btn btn-success btn-prev" type="button" onclick="change_active('prev')">Prev</button>
                            </div>
                            <div class="col-md-6">
                                <div class="dates dateselected" id="active-date"></div>
                            </div>
                            <div class="col-md-3 text-center">
                                <button class="btn btn-success btn-next" type="button" onclick="change_active('next')">Next</button>
                            </div>
                        </div>
                    </div>

                    <div class="selectpackages">
                        <div class="noofdays">
                            Default Tiffin
                        </div>
                        <div class="row defaultpackages">

                            @foreach ($tiffin_items as $default)
                                <div class="col-md-12  mt-20">
                                    <p class="text-bold"><b>{{ $default->title ?? '' }}</b></p>

                                    @if ($default->is_options)
                                        <table class="tablecss">
                                            <tr>
                                                @foreach ($default->options as $option)
                                                    <th class="text-center">{{ $option->title }}</th>
                                                @endforeach
                                            </tr>
                                            @for ($j = 0; $j <= count($default->options[0]->products) - 1; $j++)
                                                <tr class="">
                                                    @for ($i = 0; $i < count($default->options); $i++)
                                                        <td>
                                                            @if (isset($default->options[$i]->products[$j]))
                                                                <div class="form-check text-left">
                                                                    <input
                                                                        class="form-check-input"
                                                                        type="radio"
                                                                        value="{{ $default->options[$i]->products[$j]->id }}"
                                                                        @if($j == 0) checked @endif
                                                                        name="default{{ $default->options[$i]->id }}]"
                                                                        id="id_{{ $default->options[$i]->id.'_'.$default->options[$i]->products[$j]->id }}"
                                                                    >
                                                                    <label class="form-check-label" for="id_{{ $default->options[$i]->id.'_'.$default->options[$i]->products[$j]->id }}">
                                                                        {{  $default->options[$i]->products[$j]->product->name }}
                                                                    </label>
                                                                </div>
                                                            @endif
                                                        </td>
                                                    @endfor
                                                </tr>
                                            @endfor

                                        </table>
                                    @else
                                        @if (count($default->options) > 0)
                                            @foreach ($default->options[0]->products as $product)
                                                <div class="form-check text-left">
                                                    <input class="form-check-input" type="radio" name="default[{{ $default->id }}]" id="ida_{{ $product->id.'_'.$product->product->id }}">
                                                    <label class="form-check-label" for="ida_{{ $product->id.'_'.$product->product->id }}">
                                                        {{ $product->product->name }}
                                                    </label>
                                                </div>
                                            @endforeach
                                        @endif
                                    @endif

                                </div>
                            @endforeach

                            <div class="col-md-12">
                                <p><b>Salad and Pickle are complimentarly included in the packages</b></p>
                            </div>
                        </div>
                    </div>

                    <div class="selectpackages pb-0">
                        <div class="noofdays px-2 mb-0" data-toggle="collapse" href="#collapseExample" role="button" aria-expanded="false" aria-controls="collapseExample">
                            Add ons <span class="pull-right"><i class="fa fa-chevron-down"></i></span>
                        </div>
                        <div class="row defaultpackages collapse" id="collapseExample">
                            <div class="col-md-12">
                                <div class="row">
                                    <div class="col-md-6">

                                    </div>
                                    <div class="col-md-4">

                                    </div>
                                    <div class="col-md-2">
                                        <p class="text-center"><b>Total</b></p>
                                    </div>
                                </div>
                                @forelse ($addons as $addon)
                                     <div class="borderlinebottom">
                                    <p><b>{{ $addon->category->name }}-</b></p>
                                        @foreach ($addon->addons as $addon_product)
                                            <div class="row sabji1">
                                                <div class="col-md-6">
                                                    <div class="form-check">
                                                        <input type="checkbox" class="form-check-input" id="sabji1" checked>
                                                        <label class="form-check-label" for="sabji1">{{ $addon_product->product->name }}</label>
                                                    </div>
                                                </div>
                                                <div class="col-md-4">
                                                    <div class="input-group mb-3">
                                                        <div class="input-group-prepend">
                                                            <button type="button" data-val="{{ $addon_product->id }}" onclick="handleAddon('{{ $addon_product->id }}', 'desc')" class="input-group-text p59">-</button>
                                                        </div>
                                                        <input  type="text"
                                                                class="form-control addon-field"
                                                                id="addon_{{ $addon_product->id }}"
                                                                readonly
                                                                data-addon-price="{{ $addon_product->product->price }}"
                                                                data-addon-id="{{ $addon_product->product->id }}"
                                                                min="0"
                                                                value="0"
                                                                style="background: #fff;"
                                                        >
                                                        <div class="input-group-append">
                                                            <button type="button" data-val="{{ $addon_product->id }}" onclick="handleAddon('{{ $addon_product->id }}', 'inc')" class="input-group-text">+</button>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="col-md-2">
                                                    <p class="text-center"><span id="addon-price-{{ $addon_product->id }}">0.00</span> </p>
                                                </div>
                                            </div>
                                        @endforeach
                                </div>
                                @empty
                                        <h2 class="text-center">No addon Available</h2>
                                @endforelse

                            </div>
                        </div>

                    </div>

                    <div class="selectpackages pt-3">
                        <div class="col-md-12">
                                <div class="row">
                                    <div class="col-md-6">
                                        <p><b>Total</b></p>
                                    </div>
                                    <div class="col-md-6">
                                        <p class="text-right" id="addon-total">$00.00</p>
                                    </div>
                                    <div class="col-md-12">
                                        <button type="button" data-date="" date-amount=""
                                            class="btn btn-success btn-block add-to-cart-btn">Add to Cart</button>
                                    </div>
                                </div>
                            </div>
                    </div>


                </div>{{-- end middle  --}}

                <div class="col-md-3">
                    <div class="sticky-pos">
                        <div class="mt-6">
                            <div class="selectpackages">
                                <div class="noofdays">
                                    Selected Dates
                                </div>
                                <div class="selecteddates" id="date-list">

                                </div>
                            </div>
                        </div>
                        <div class="">
                            <div class="selectpackages plr-20 pb-0">
                                <div class="noofdays">
                                    Your Cart
                                </div>
                                <div class="chartsection">
                                    <table class="package-amount-table">
                                    </table>
                                    <hr>
                                    <table>
                                        <tr>
                                            <th>Addon</th>
                                        </tr>
                                    </table>
                                    <table class="date-amount-table">
                                    </table>
                                </div>

                                <table class="mt-20">
                                    <tr class="totalcss">
                                        <td class="text-left pl-20">Total</td>
                                        <td class="text-right pr-20 total-amount">$0.00</td>
                                    </tr>
                                </table>
                            </div>
                            <div class="">
                                <button type="button" class="btn btn-success btn-block">Pay Now</button>
                            </div>
                        </div>
                    </div>
                </div>{{-- end Summery --}}
            </form>

        </div>
    </section>
@endsection

@push('js')
    <script src="//code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
    <script src="//cdn.rawgit.com/dubrox/Multiple-Dates-Picker-for-jQuery-UI/master/jquery-ui.multidatespicker.js"></script>


    <script>
        $(function () {
            var datepicker      = $('#datepicker');
            var selected_days   = $("input[name='package']:checked").attr('data-day');
            var selected_range  = $("input[name='package']:checked").attr('data-range');
            var package_price   = $("input[name='package']:checked").attr('data-price');
            var date_array      = [];
            var cart_items      = [];
            var total           = 0;
            var grand_total     = $("input[name='package']:checked").attr('data-price');
            var picker;
            var date_list       = $('#date-list');
            var active_date     = $('#active-date');
            var active          = 0;

            // initialize calender
            function intCalender(range, days){
                picker =  datepicker.multiDatesPicker({
                    minDate: 0,
                    maxPicks: days,
                    pickableRange: range,
                    adjustRangeToDisabled: true,
                    changeMonth: true,
                    changeYear: false,
                    dateFormat: "dd-mm-yy",
                    onSelect:(dateText) => selectedDates(dateText),
                });
                addPckagePrice();
            }

            // package Change
            $('.package-days').change(function (e){
                e.preventDefault();
                selected_days = $(this).attr('data-day');
                selected_range = $(this).attr('data-range');
                datepicker.multiDatesPicker('destroy');
                package_price = $("input[name='package']:checked").attr('data-price');
                grand_total = $("input[name='package']:checked").attr('data-price');
                date_array = [];
                cart_items = [];
                active_date.empty();
                date_list.empty();
                intCalender(selected_range, selected_days);
                addPckagePrice();
            });

            // add packege price
            function addPckagePrice() {
                $('.package-amount-table').empty();
                $('.package-amount-table').append(`
                    <tr>
                        <th colspan="2">Packege Price</th>
                    </tr>
                    <tr>
                        <td>`+selected_range +` Dyas</td>
                        <td align="right">$`+parseFloat(package_price).toFixed(2)+`</td>
                    </tr>
                `);

                $('.total-amount').text('$'+parseFloat(grand_total).toFixed(2));
            }

            // function calls
            intCalender(selected_range, selected_days);

            // handle addons
            handleAddon = function(id, type){
                var value = parseInt($('#addon_'+id).val());
                var price = parseFloat($('#addon_'+id).attr('data-addon-price'));
                if(type == 'inc'){
                    value = parseInt(value) + 1;
                    total = parseFloat(total) + parseFloat(price);
                }else{
                    if(value > 0){
                        value = parseInt(value) - 1;
                        total = parseFloat(total) - parseFloat(price);
                    }else if(value == 0){
                        value = 0;
                        total = total;
                    }
                }
                // set values
                $('#addon_'+id).val(value);
                $('#addon-total').text('$'+total.toFixed(2));
                $('#addon-price-'+id).text('$'+(parseFloat(price) * parseFloat(value)).toFixed(2));
            }

            // selected dates
            function selectedDates(dateText) {

                if(date_array.includes(dateText)){
                    date_array = $.grep(date_array, function(value) {
                        return value != dateText;
                    });
                }else{
                    date_array.push(dateText);
                }


                // cart Items or summery
                date_list.empty();
                cart_items = [];
                date_array.forEach((element, key) => {
                    var cart = {
                        items:[],
                        addons:[],
                        date:null,
                        is_done:false,
                        is_error:false,
                        is_active:false,
                        price:0.00
                    }

                    date_list.append(`<div class="date-item">`+element+`</div>`);
                    if(key == 0){
                        cart.is_active = true;
                        date_list.find('.date-item').addClass('active');
                        active_date.text(element);
                    }
                    cart.date = element;
                    cart_items.push(cart);
                });


            }

            // Active check
            change_active = function(type) {
                cart_items[active].is_active = false;
                if(type == 'next'){
                   active = (cart_items.length - 1) == active ?   active  : active + 1;
                }else{
                    active = 0 == active ?  active  : active - 1;
                }
                cart_items[active].is_active = true;
                active_date.text(cart_items[active].date);
                dateActiveChange()
            }

            // handle add to cart
            $('.add-to-cart-btn').click(function (e) {
                e.preventDefault();
                if(date_array.length > 0){
                    let addonItems = $('.addon-field');
                    let total = 0;
                    for (let ind = 0; ind < addonItems.length; ind++) {
                        let addonItem = addonItems[ind];
                        if(addonItem.value > 0 && typeof cart_items[active] != undefined){

                            cart_items[active].addons.push({
                                id: addonItem.dataset.addonId,
                                qty : addonItem.value,
                                price : parseFloat(addonItem.value) * parseFloat(addonItem.dataset.addonPrice),
                            });
                            total += parseFloat(addonItem.value) * parseFloat(addonItem.dataset.addonPrice);
                        }
                    }
                    grand_total = parseFloat(grand_total) + parseFloat(total);
                    cartSummery();
                }
            });

            // cart summery
            function cartSummery() {
                // re-init
                cart_items[active].is_done = true;
                cart_items[active].is_active = false;
                active = (cart_items.length - 1) == active ?   active  : active + 1;
                cart_items[active].is_active = true;
                active_date.text(cart_items[active].date);
                $('.total-amount').text('$'+ parseFloat(grand_total).toFixed(2));

                $('.date-amount-table').empty();
                cart_items.forEach(element => {
                    if(element.is_done){
                        element.addons.forEach(addon => {
                            let temp_total = 0;
                            temp_total += parseFloat(addon.qty) * parseFloat(addon.price);
                            $('.date-amount-table').append(`
                                <tr>
                                    <td>`+element.date+`</td>
                                    <td align="right">$`+ (temp_total).toFixed(2) +`</td>
                                </tr>
                            `);
                        });
                    }
                });
                dateActiveChange();

            }

            // date Actives
            function dateActiveChange() {
                date_list.empty();
                cart_items.forEach((element, key) => {
                    if(element.is_done){
                        date_list.append(`<div class="date-item done">`+element.date+`</div>`);
                    }else if(element.is_active){
                        date_list.append(`<div class="date-item active">`+element.date+`</div>`);
                    }else{
                        date_list.append(`<div class="date-item">`+element.date+`</div>`);
                    }
                });
            }

        });






</script>
@endpush


@push('css')
    <link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.12.1/themes/pepper-grinder/jquery-ui.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.rawgit.com/dubrox/Multiple-Dates-Picker-for-jQuery-UI/master/jquery-ui.multidatespicker.css">

    <style>
        #datepicker, .ui-datepicker-inline{
            width: 100%
        }
        .date-item {
            border: 1px solid #d4d4d4;
            margin-bottom: 5px;
            padding: 8px;
            border-radius: 5px;
            background: #ececec;
        }

        .date-item.active{
            background: #E3F4E6;
            border: 1px solid #28b93f;
        }

        .date-item.done{
            background: #28b93f;
            border: 1px solid #28b93f;
        }

        .date-item.error{
            border: 1px solid #eb1414;
            background: #e9bcbc;
        }

        .sticky-pos{
            position: sticky;
            top: 0;
        }
    </style>
@endpush
