@extends('layouts.frontend.app')

@push('meta')
    <meta name='description' content="Buy now product" />
    <meta name='keywords' content="@foreach ($product->tags as $tag){{ $tag->name . ', ' }} @endforeach" />
@endpush

@section('title', 'Minimal - Buy now product')

@section('content')
    @php
        $order = App\Models\Order::where('user_id', auth()->id())
            ->select('address', 'shipping_charge', 'town', 'district', 'thana')
            ->first();
    @endphp
    <div id="checkout">
        <div class="container">
            <form action="{{route('order.store_minimal')}}" method="POST">
                @csrf
                <div class="row mt-3">
                    <div class="col-md-8 offset-md-2 alert-message">
                        <div class="alert"></div>
                    </div>
                    
                    {{-- Billing Info --}}
                    <div class="widget3 col-md-7">
                        <h4 class="form-title"><span>1</span> Billing Info </h4>
                        @include('frontend.partial.checkout.checkout_part.billing_info_minimal')
                    </div>
                    

                    <div class="widget3 col-md-5">

                        {{-- Payment Methode --}}
                        <div class="row">
                            <style>
                                #accordion .card {
                                    padding: 0 !important;
                                }
                        
                                #accordion .card-body {
                                    padding: 0;
                                    margin-top: 10px;
                                }
                        
                                #accordion .card-header {
                                    padding: 0;
                                }
                        
                                #accordion .card-header h5 div {
                                    font-size: 15px;
                                    padding: 10px;
                                    background: var(--primary_color);
                                    color: white;
                                    cursor: pointer;
                                }
                        
                                label img {
                                    width: 100px;
                                    height: 50px;
                                    object-fit: contain;
                                }
                        
                                .pa label {
                                    text-align: center;
                                    box-shadow: 0px 0px 6px gainsboro;
                                    padding: 10px 20px;
                                    border-radius: 5px;
                                    position: relative;
                                    cursor: pointer;
                                }
                        
                                .arrow-in {
                                    top: 5px;
                                }
                        
                                .payment_method {
                                    position: absolute;
                                    z-index: -9;
                                }
                            </style>
                            <div class="widget-3 col-md-12">
                                <div class="widget3">
                                    <h4 class="form-title"><span>2</span>Payment Method</h4>
                                    @include('frontend.partial.checkout.checkout_part.payment_methode_minimal')
                                </div>
                            </div>
                        </div>

                        <input type="hidden" value="{{ $request->dynamic_price }}" name="dynamic_prices">

                        <h4 class="form-title"><span>3</span>Order Summary </h4>
                        <div class="card">
                            <?php
                            if ($request->qty >= 6 && $product->whole_price > 0) {
                                $sub_total = $product->whole_price * $request->qty;
                            } else {
                                $sub_total = $request->dynamic_price * $request->qty;
                            }
                            ?>
                            <div style="margin-bottom: 10px;display: flex;" class="product">
                                {{-- <img style="width:50px" src="{{ asset('uploads/product/' . $product->image) }}" --}}
                                <img style="width:50px" src="{{ asset('uploads/product/' . ($product->color_image ? $product->color_image : $product->image)) }}"
                                    alt="">
                                <a id="product_name" class="product_name" style="margin-left:10px"
                                    href="{{ route('product.details', $product->slug) }}">{{ $product->title }}</a>
                                <span class="text-muted">{{ $product->color }}</span>
                                <span style="flex: 1 auto;text-align: right;"> {{ $sub_total }}</span>
                                <input type="hidden" name="id" value="{{ $request->id }}">
                                <input type="hidden" name="qty" value="{{ $request->qty }}">
                                <?php
                                $attr = [];
                                $attributes = DB::table('attributes')->get();
                                foreach ($attributes as $attribute) {
                                    $attribute_prouct = DB::table('attribute_product')
                                        ->select('*')
                                        ->join('attribute_values', 'attribute_values.id', '=', 'attribute_product.attribute_value_id')
                                        ->addselect('attribute_values.name as vName')
                                        ->addselect('attribute_product.id as vid')
                                        ->join('attributes', 'attributes.id', '=', 'attribute_values.attributes_id')
                                        ->where('attribute_product.product_id', $product->id)
                                        ->where('attributes.id', $attribute->id)
                                        ->get();
                                    if ($attribute_prouct->count() > 0) {
                                        $slug = $attribute->slug;
                                        $attr[$slug] = $request->$slug;
                                    }
                                }
                                ?>
                                <input type="hidden" name="size"
                                    value="{{ $attr != '' ? json_encode($attr) : 'blank' }}">
                                <input type="hidden" name="color" value="{{ $request->color }}">
                            </div>

                            <style>
                                .arrow2 .icofont-simple-down {
                                    display: block;
                                }

                                .arrow2 .icofont-simple-right {
                                    display: none;
                                }

                                .collapsed .arrow2 .icofont-simple-down {
                                    display: none !important;
                                }

                                .collapsed .arrow2 .icofont-simple-right {
                                    display: block !important;
                                }
                            </style>
                            <div class="form-group">
                                <div class="form-group instruction">
                                    <a class="collapsed" data-toggle="collapse" href="#collapseExample" role="button"
                                        aria-expanded="false" aria-controls="collapseExample">
                                        <span><label for="">Coupon</label> </span><span class="arrow2"></span>
                                    </a>
                                    <div class="collapse" id="collapseExample">
                                        <input type="text" id="coupon" class="form-control"
                                            placeholder="Coupon Code" />
                                        <button type="button" class="btn btn-primary btn-block py-2"
                                            id="apply-coupon">Apply</button>
                                    </div>
                                </div>
                            </div>
                            <input type="hidden" value="0" id="partial_paid" name="partial_paid"
                                class="form-control" placeholder="Partial Amount" />
                            <div class="rvinfo">
                                <span>Subtotal</span>
                                <span><span id="sub-total"> {{ $sub_total }}</span> <strong> {{ setting('CURRENCY_CODE_MIN') ?? 'TK' }}</strong></span>
                            </div>
                            <div class="rvinfo">
                                <span>Shipping Charge</span>
                                <span>+ <span id="ship-charge">
                                        @if (isset($order->shipping_charge))
                                            {{ $order->shipping_charge }}
                                        @else
                                            0.00
                                        @endif
                                    </span><strong> {{ setting('CURRENCY_CODE_MIN') ?? 'TK' }}</strong></span>
                            </div>

                            <div class="rvinfo coupon">
                                <span>Coupon <span class="coupon-name"></span> <a id="reset_coupon_btn" href="{{ route('reset.coupon') }}" class="btn bg-danger text-white text-sm-left @if(Session::has('coupon'))d-visible @else d-none @endif" style="padding:.0rem .4rem;">x</a></span>
                                <span>- <span
                                        id="coupon">{{ Session::has('coupon') ? number_format(Session::get('coupon')['discount'], 2, '.', ',') : '0.00' }}</span><strong>
                                            {{ setting('CURRENCY_CODE_MIN') ?? 'TK' }}</strong></span>
                            </div>
                            <hr>
                            <div class="rvinfo">
                                <span>Total</span>
                                <h4>
                                    @if (Session::has('coupon'))
                                        @php
                                            $discount = Session::get('coupon')['discount'];
                                            $total = number_format($sub_total - $discount, 2, '.', ',');
                                        @endphp
                                    @endif
                                    <strong>
                                        <span id="total">
                                            {{ $total ?? number_format($sub_total, 2, '.', ',') }}</span> {{ setting('CURRENCY_CODE_MIN') ?? 'TK' }}
                                    </strong>
                                </h4>
                            </div>
                        </div>
                        <input value="Order" type="submit">
                    </div>
                </div>
            </form>
        </div>
    </div>
@endsection

@push('js')
    {{-- <script src="{{ asset('/') }}assets/frontend/js/city.js"></script> --}}
    <script>
        $(document).ready(function() {
            
            // Coupon
            $(document).on('click', '#apply-coupon', function(e) {
                e.preventDefault();
                $('#coupon').removeClass('is-invalid');
                let code = $('input#coupon').val();
                let id = "{!! $request->id !!}";
                let qty = "{!! $request->qty !!}";
                let dynamic_price = "{!! $request->dynamic_price !!}";
                let shipping_charge = 0;
                let download_able = "{!! $product->download_able !!}";

                if (download_able != 1) {
                    if ($("select[name='shipping_range']").val() == 1) {
                        let charge = "{!! setting('shipping_charge') !!}";
                        shipping_charge += parseInt(charge);
                    } else {
                        let charge = "{!! setting('shipping_charge_out_of_range') !!}";
                        shipping_charge += parseInt(charge);
                    }
                }

                if (code != '') {
                    $.ajax({
                        type: 'GET',
                        url: '/apply/coupon/buy-now/' + code + '/' + id + '/' + qty + '/' +
                            dynamic_price,
                        dataType: "JSON",
                        success: function(response) {
                            console.log(response);
                            $('.alert-message').removeClass('d-none');
                            if (response.alert == 'success') {
                                $('.alert-message .alert').removeClass('alert-danger').addClass(
                                    'alert-success').text(response.message);
                                $('span#ship-charge').text(number_format(shipping_charge, 2,
                                    '.', ','));
                                $('span#coupon').text(number_format(response.discount, 2, '.',
                                    ','));
                                let total = response.total + shipping_charge;
                                $('span#total').text(number_format(total, 2, '.', ','));
                                $('span.coupon-name').text('(' + code + ')');
                                $('#coupon').val('');
                                $('#reset_coupon_btn').removeClass('d-none');
                                // $('#reset_coupon_btn').addClass('d-visible');
                                
                            } else {
                                $('.alert-message .alert').removeClass('alert-success')
                                    .addClass('alert-danger').text(response.message);
                            }
                        },
                        error: function(xhr) {
                            console.log(xhr);
                        }
                    });
                } else {
                    $('#coupon').addClass('is-invalid');
                }
                setTimeout(() => {
                    $('.alert-message .alert').removeClass('alert-danger alert-success').text('');
                }, 10000);

            });




            /* 
            ** Shipping
            * */
            $(document).on('change', '#shipping_range', function(e) {
                divis()
            });

            divis();
            function divis() {
                let shipping_charge = 0;
                let download_able = "{!! $product->download_able !!}";
                if (download_able != 1) {
                    if($("select[name='shipping_range']").val() == 3){
                        let charge = 0;
                        shipping_charge += parseInt(charge);
                    }else if($("select[name='shipping_range']").val() == 2){
                        let charge = "{!! $product->dedicated_shipping_charge !!}";
                        shipping_charge += parseInt(charge);
                    }else if ($("select[name='shipping_range']").val() == 1) {
                        let charge = "{!! setting('shipping_charge') !!}";
                        shipping_charge += parseInt(charge);
                    } else {
                        let charge = "{!! setting('shipping_charge_out_of_range') !!}";
                        shipping_charge += parseInt(charge);
                    }
                }
                let subtotal = $('span#sub-total').text();
                let coupon = $('span#coupon').text();
                let rep_subtotal = subtotal.replace(',', '');
                let rep_coupon = coupon.replace(',', '');
                let total = (parseInt(rep_subtotal) + shipping_charge) - parseInt(rep_coupon);
                $('span#ship-charge').text(number_format(shipping_charge, 2, '.', ','));
                $('span#total').text(number_format(total, 2, '.', ','));
            }

            function number_format(number, decimals, dec_point, thousands_sep) {
                var n = !isFinite(+number) ? 0 : +number,
                    prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
                    sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
                    dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
                    toFixedFix = function(n, prec) {
                        // Fix for IE parseFloat(0.55).toFixed(0) = 0;
                        var k = Math.pow(10, prec);
                        return Math.round(n * k) / k;
                    },
                    s = (prec ? toFixedFix(n, prec) : Math.round(n)).toString().split('.');
                if (s[0].length > 3) {
                    s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
                }
                if ((s[1] || '').length < prec) {
                    s[1] = s[1] || '';
                    s[1] += new Array(prec - s[1].length + 1).join('0');
                }
                return s.join(dec);
            }
        });
    </script>

    @if(setting('GTM_DATA_LAYER_STATUS') == 1 || setting('GTM_DATA_LAYER_STATUS') == null)
        <script type="text/javascript">

            $(document).ready(function() {
            
                var price = {{ $request->dynamic_price }};
                var quantity = {{ $request->qty }};
                var totalPrice = price * quantity;

              
                window.dataLayer = window.dataLayer || [];
                window.dataLayer.push({
                    event: "begin_checkout",
                    ecommerce: {
                        currency: "{!! setting('CURRENCY_CODE') !!}",  
                        value: totalPrice,
                        coupon: "",  
                        items: [
                            {
                                item_id: "{!! $product->id !!}",  
                                item_name: "{!! $product->title !!}",
                                affiliation: "",  
                                coupon: "",  
                                discount: {!! Session::get('coupon')['discount'] ?? 0 !!},  
                                index: "",  
                                item_brand: "{!! $product->brand['name'] !!}",  
                                item_category: "",  
                                item_category2: "",  
                                item_category3: "",  
                                item_category4: "",  
                                item_variant: "",  
                                item_list_id: "",  
                                item_list_name: "",  
                                location_id: "",  
                                price: price,  
                                quantity: quantity
                            }
                        ]
                    }
                });
            });
        </script>
    @endif
@endpush