@extends('layouts.admin')
@section('title' ,$title)

<style>

    .product-card {
        /* width: 150px; */
        position: relative;
        box-shadow: 0 2px 7px #dfdfdf;
        /* margin: 50px auto; */
        background: #fafafa;
    }

    .product-card:hover {

        box-shadow: 0 2px 7px var(--success);
        /* margin: 50px auto; */
        background: var(--success);

    }

    .product-card:hover .product-name,.product-card:hover  .product-price{
        color: white !important;
    }

    .badge {
        position: absolute;
        left: 0;
        top: 20px;
        /* text-transform: uppercase; */
        font-size: 8px;
        font-weight: 700;
        background: red;
        color: #fff;
        padding: 3px 10px;
    }

    .product-tumb {
        display: flex;
        /*align-items: center;*/
        align-items: baseline;
        justify-content: center;
        /*height: 300px;*/
        /* padding: 15px; */
        background: #f0f0f0;
    }

    .product-tumb img {
        max-width: 100%;
        max-height: 100%;
        height: 150px !important;
        width: 170px !important;
    }

    .product-details {
        padding: 30px;
    }

    .card {
        border-radius: 7px !important;
        border-color: #e1e7ec;
    }

    @media only screen and (min-width: 769px) and (max-width: 1025px) {

        .block .block-title{
            font-size: 13px !important;
        }

        .product-tumb img {
            max-width: 100%;
            max-height: 100%;
            height: 100px !important;
            width: 130px !important;
        }
        .product-card .product-name,.product-card .product-price{
            font-size: 10px !important
        }
    }

</style>

@section('content')

    <div class="row" x-data>
        <div class="col-lg-6 col-xxl-7 col-md-12 col-sm-12 form-group">
            <div class="row">
                <div class="col-lg-12 m-b-10">
                    <div class="card block" x-data="block_products({{$products}})">
                        <div class="card-body" >
                            <h4 class="block-title">Products</h4>
                            <div class="row">
                                <div class="col-lg-12 m-b-5">
                                    <div class="pull-right">
                                        <div class="form-group">
                                            <input type="text" x-model="search" class="form-control form-control-sm" placeholder="Search ...">
                                        </div>
                                    </div>
                                </div>
                                <div class="col-lg-12">
                                    <div class="row" style="max-height:400px; overflow-y:scroll">
                                        <template x-for="product in filteredProducts" :key="product.id">

                                            <div class="col-lg-3 col-xxl-2 col-md-4 col-sm-4 col-xs-6 form-group" x-data="bloc_cart">
                                                <div class="product-card cursor-pointer" @click="$store.cart.add(product)">
                                                    <div x-show="!product.is_available" class="badge fs-8">{{__("Unavailable")}}</div>
                                                    <div class="product-tumb">
                                                       <img :src="`${product.image}`" :alt="product.name">
                                                    </div>
                                                    <div class="product-details p-2 text-center">
                                                        <strong class="fs-12 text-uppercase product-name" x-text="product.name"></strong>
                                                        <div class="product-price text-success">
                                                            <strong class="" x-text="formatNumber(product.price,'{{getSettingsOf('currency')}}')"></strong>
                                                        </div>
                                                    </div>
                                                    {{-- <div class="card-footer">
                                                        <button class="btn btn-success btn-block"><i class="fa fa-shopping-cart"></i></button>
                                                    </div> --}}
                                                </div>
                                            </div>
                                        </template>
                                    </div>
                                </div>

                                <div role="alert" aria-live="assertive" aria-atomic="true" class="toast" data-autohide="false">
                                    <div class="toast-header">
                                        <img src="..." class="rounded mr-2" alt="...">
                                        <strong class="mr-auto">Bootstrap</strong>
                                        <small>11 mins ago</small>
                                        <button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
                                            <span aria-hidden="true">&times;</span>
                                        </button>
                                    </div>
                                    <div class="toast-body">
                                        Hello, world! This is a toast message.
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-6 col-xl-5 col-md-12 col-sm-12">
            <div class="row">
                <div class="col-lg-12 m-b-10" x-data="block_customers({{$customers}})">
                    <div class="card block">
                        <div class="card-body p-2">
                            <div class="rowq">
                                <div class="col-lg-12">
                                    <h4 class="block-title">Customer</h4>
                                </div>
                                <div class="col-lg-12 m-b-5">
                                    <template x-if="!$store.cart.customer">
                                        <div class="form-group" @click.away="active=false;">
                                            <input type="text"
                                            x-model="search"
                                            @focus="active=true"
                                            placeholder="Name, Phone Number"
                                            class="form-control form-control-sm m-b-0" />

                                            <template x-if="active && filteredCustomers">
                                                <div class="m-t-0"
                                                    style="position: relative; width:100%; z-index:1;"
                                                    x-cloak
                                                    x-transition>
                                                    <div class="mt-1 border bg-white rounded"
                                                         style="position: absolute; width:100% ; max-height: 300px; overflow-y:scroll">
                                                        <ul class="list-group">
                                                            <template x-for="(customer, index) in filteredCustomers" :key="index">
                                                                <a href="javascript:void(0)" @click="$store.cart.setCustomer(customer); active = false;">
                                                                    <li class="list-group-item list-group-item-action cursor-pointer m-b-0 p-5s">
                                                                        <div class="media">
                                                                            <img :src="`${customer.avatar}`" :alt="customer.full_name"  class="mr-2 rounded-pill"
                                                                                 style="width: 40px; height: 40px">
                                                                            <div class="media-body">
                                                                                <strong class="fs-12 list-group-item-heading text-uppercase m-b-0" x-text="customer.full_name"></strong>
                                                                                <div class="fs-11" x-text="customer.email ?? '---'"></div>
                                                                                <div class="fs-11" x-text="customer.phone ?? '---'"></div>
                                                                            </div>
                                                                        </div>
                                                                    </li>
                                                                </a>
                                                            </template>
                                                        </ul>
                                                    </div>
                                                </div>
                                            </template>
                                            <template x-if="filteredCustomers.length <=0 && search !== ''">
                                                <ul class="list-group">
                                                    <li class="list-group-item list-group-item-action cursor-pointer text-center" @click="addCustomer">
                                                        <h5 class="fs-14 text-danger m-b-0"><strong>Customer Not Found.</strong></h5>
                                                        <div class="text-muted">
                                                            <div class="m-b-0 fs-11">{{__("Click to add new customer.")}}</div>
                                                           <div> <i class="fs-15 fa fa-plus"></i></div>
                                                        </div>
                                                    </li>
                                                </ul>
                                            </template>

                                        </div>
                                    </template>
                                </div>
                                 <div class="col-lg-12" >

                                </div>

                               <template x-if="!active && $store.cart.customer">
                                    <div class="col-lg-12" >
                                        <div class="media">
                                            <img :src="`${$store.cart.customer.avatar}`" :alt="$store.cart.customer.full_name"  class="mr-2 rounded-pill"
                                            style="width: 50px; height: 50px">
                                            <div class="media-body">
                                                <h5 class="m-b-0 fs-14 text-uppercase text-success" x-text="$store.cart.customer.full_name"></h5>
                                                <template x-if="$store.cart.customer.email">
                                                    <div class="fs-11">
                                                        <i class="fa fa-envelope"></i>
                                                        <span x-text="$store.cart.customer.email"></span>
                                                    </div>
                                                </template>
                                                <template x-if="$store.cart.customer.phone">
                                                    <div class="fs-11">
                                                        <i class="fa fa-phone"></i>
                                                        <span x-text="$store.cart.customer.phone"></span>
                                                    </div>
                                                </template>
                                                <div class="float-right fs-11">
                                                    <button class="btn btn-outline-success p-1"
                                                            @click="$store.cart.setCustomer(null); active = true">
                                                        Change
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                               </template>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-lg-12">
                    <div class="card block" x-data="bloc_cart">
                        <div class="card-body order-detailss p-2">
                            <h4 class="block-title text-center">Order</h4>

                           <div class="row" id="bloc-display-order">
                               <template x-if="$store.cart.count" x-transition>

                                   <div class="col-lg-12 m-b-10"  style="display: table-row">
                                       <center>
                                           <img src="{{url("img/logo-bw.png")}}" alt="Logo" style="height: 50px; width:150px;">
                                       </center>
                                       <div class="col-lg-6s col-sm-6s col-xs-6s "
                                            styles="display: table-cell ; width: 50% ; align-content: start; border-right: 2px solid #eee">
                                           <div class="float-left fs-11">
                                               <div><strong>Colen's Lounge</strong></div>
                                               <div><strong>{{getSettingsOf("phone_number")}}</strong></div>
                                               <div><strong>{{getSettingsOf("address2")}}</strong></div>

                                           </div>
                                       </div>
                                       <div classs="col-lg-6 col-sm-6 col-xs-6" styles="display: table-cell ; width: 50%;">
                                           <template x-if="$store.cart.customer">
                                               <div class="float-right fs-11" >
                                                   <h6 class="m-b-1 fs-13"><strong>Customer Infos</strong></h6>
                                                   <div>Full Name : <strong x-text="$store.cart.customer.full_name ?? '---'"></strong></div>
                                                   <div>Email : <strong x-text="$store.cart.customer.email ?? '---'"></strong></div>
                                                   <div>Phone : <strong x-text="$store.cart.customer.phone ?? '---'"></strong></div>
{{--                                                   <div>Address : <strong x-text="$store.cart.customer.full_default_address"></strong></div>--}}
                                               </div>
                                           </template>
                                       </div>
                                   </div>
                               </template>

                                <div class="col-lg-12 m-b-5">
                                    <table class="table table-bordereds table-condensed" id="table-cart" style="border: none">
                                        <thead>
                                        <tr>
                                            <th class="left fs-12">Product</th>
                                            <th class="right fs-12">P.U</th>
                                            {{-- <th class="right fs-12">Qty</th> --}}
                                            <th class="right fs-12">Amount</th>
                                            <th class="right fs-12 d-print-none" width="2%">---</th>
                                        </tr>
                                        </thead>
                                        <tbody>
                                        <template x-for="(item,index) in $store.cart.items" :key="index">
                                            <tr class="fs-12">
                                                <td class="fs-12 cursor-pointer" @click="updateQty($el,item)">
                                                    <span class="text-success text-underline">
                                                        <span x-text="formatNumber(item.qty)"></span>
                                                        <span> x </span>
                                                        <span class="text-uppercase" x-text="item.name"></span>
        {{--                                                <span class="float-right fa fa-edit"></span>--}}
                                                    </span>
                                                </td>
                                                {{-- <td class="fs-12 right"> <span x-text="formatNumber(item.qry)"></span></td> --}}
                                                <td class="fs-12 right"> <span x-text="formatNumber(item.price)"></span></td>
                                                <td class="fs-12 right">
                                                    <span x-text="formatNumber(item.amount)"></span>
                                                </td>
                                                <td class="fs-12 right d-print-none">
                                                    <div class="pull-right">
                                                        <small class="text-danger btn btn-sm"
                                                               @click="$store.cart.remove(item)">
                                                            <i class="fa fa-times"></i>
                                                        </small>
                                                    </div>
                                                </td>
                                            </tr>
                                        </template>
                                        <template x-if="$store.cart.count <= 0">
                                            <tr>
                                                <td colspan="3" class="center">
                                                    <div>
                                                        <h5 class="fs-14 text-danger"><strong>No Product in cart.</strong></h5>
                                                        <p class="text-muted fs-10">For add product in order, you may to click on any item in products list</p>
                                                    </div>
                                                </td>
                                            </tr>
                                        </template>
                                        </tbody>
                                    </table>

                                    <template x-if="$store.cart.count">
                                        <table class="table table-borderedq table-condensed">
                                            <thead>
                                            <template x-for="T in Object.values(allTotal)">
                                                <tr>
                                                    <th :class="T.className" class="left" x-text="T.label"></th>
                                                    <th :class="T.className" class="right" x-text="formatNumber(T.value,currency)"></th>
                                                </tr>
                                            </template>

                                            </thead>
                                        </table>
                                    </template>
                                </div>

                               <template x-if="$store.cart.count">
                                   <div class="col-lg-12 d-print-none">
                                       <div class="border border-dark p-2 rounded-sm d-flex justify-content-between">
                                           <div>
                                               <div class="custom-control custom-switch cursor-pointer">
                                                   <input type="checkbox" checked class="custom-control-input cursor-pointer" id="customSwitch1">
                                                   <label class="custom-control-label fs-14" for="customSwitch1">Check Stock</label>
                                               </div>
                                           </div>
                                           <div>
                                               <div class="custom-control custom-switch cursor-pointer">
                                                   <input type="checkbox" checked class="custom-control-input cursor-pointer" id="customSwitch12">
                                                   <label class="custom-control-label fs-14 cursor-pointer" for="customSwitch12">Payment</label>
                                               </div>
                                           </div>
                                       </div>
                                   </div>
                                   <div class="col-lg-12 d-print-none">
                                       <template x-if="$store.cart.config.payable">
                                           <div class="row">
                                               <template x-for="(method,index) in paymentMethods" :key="index">

                                                   <div class="col-lg-6 col-sm-6 m-b-5">
                                                       <div class="card cursor-pointer p-2" style="max-height: 150px;">
                                                           <div class="media">
                                                               <div>
                                                                   <div class="custom-control custom-radio mr-sm-1 cursor-pointer">
                                                                       <input name="dr" type="radio"
                                                                              x-model="paymentMethodId"
                                                                              class="custom-control-input"
                                                                              :id="'radio-'+index"
                                                                              :value=""
                                                                       />
                                                                       <label class="custom-control-label fs-12 cursor-pointer" :for="'radio-'+index"></label>
                                                                   </div>
                                                               </div>
                                                               <div class="media-body">
                                                                   <h5 class="mt-0 mb-1 fs-12" x-text="method.name"></h5>
                                                               </div>
                                                               <div  class="float-right my-s1">
                                                                   <img class="mr-3s" :src="`${method.image}`" :alt="method.name" style="width: 70px; height: 50px">
                                                               </div>

                                                           </div>

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


                        <template x-if="$store.cart.count">
                            <div class="card-footer p-1">
                                <template x-if="payable">
                                    <button class="btn btn-success rounded-sm btn-block text-uppercase" @click="payOrder">Pay <i class="m-l-2 fa fa-money-bill-alt"></i></button>
                                </template>
                                <template x-if="!payable">
                                    <button class="btn btn-success rounded-sm btn-block text-uppercase" @click="sendOrder">Send <i class="m-l-2 fa fa-save"></i></button>
                                </template>
                                <button class="btn btn-warning rounded-sm btn-block text-uppercase" @click="printOrder">Print <i class="m-l-2 fa fa-print"></i></button>
                                <button class="btn btn-success rounded-sm btn-block text-uppercase" @click="addOrderToDraft">Copy to Draft <i class="m-l-2 fa fa-drafting-compass"></i></button>
                            </div>
                        </template>
                     </div>
                </div>
            </div>
        </div>

@endsection
@push('js')
    <script >
        const editor =  DataTableEditor( {
            fields: [
                {
                    label: "{{__('Qty')}} : ",
                    name: "qty" ,
                    type: "text",
                    attr : {  type:"number" },
                },

            ],
        } );

        const editorCustomer =  DataTableEditor( {
            fields: [
                {
                    label: "{{__('Phone Number')}} : ",
                    name: "phone" ,
                    type: "text",
                    def : "2376",
                    attr : {  type:"number", required : true },
                },
                {
                    label: "{{__('First Name')}} : ",
                    name: "first_name" ,
                    type: "text",
                    attr : {  },
                },
                {
                    label: "{{__('Last Name')}} : ",
                    name: "last_name" ,
                    type: "text",
                },
                {
                    label: "{{__('Email')}} : ",
                    name: "email" ,
                    type: "text",
                },

            ],
        } );
        const currency = '{{getSettingsOf("currency")}}';

        $("#sidebarToggle").trigger('click');

        document.addEventListener('alpine:init', () => {

            Alpine.store('draft',{

                orders : JSON.parse(localStorage.getItem("ORDERS_DRAFT")) ?? [],

                add(order){
                   const orders = this.orders;
                   // order.id = orders.length + 1;
                   orders.push(order);
                   this.setOrders(orders)
                },
                setOrders (orders){
                    if(orders) {
                        orders.forEach((order,i) => order.id = i++)
                    }
                    localStorage.setItem("ORDERS_DRAFT",JSON.stringify(orders))
                    this.orders = JSON.parse(localStorage.getItem("ORDERS_DRAFT"))
                },

                reset : () => this.setOrders([]),

                openOrder (index) {
                    const order = this.orders[index]
                    if(order) {
                        this.$store.cart.setCart(order);
                    }
                },
            })

            Alpine.store('cart', {
                init (){
                    const cart = this.content;
                    this.items = cart.items ?? [] ;
                    this.customer = cart.customer ?? null ;
                    this.config = {
                        check_stock : true,
                        payment_required : true,
                    }
                },
                customer : null,
                items :  [],
                config: {},

                get count () {
                    return this.items.length
                }  ,

                get content  () {
                    return  JSON.parse(localStorage.getItem("CART")) ?? {};
                },
                reset : () => this.setCart({items : [] , customer : null}),

                setCart ( cart){
                    localStorage.setItem("CART",JSON.stringify(cart))
                    this.customer = cart.customer;
                    this.config = cart.config
                },

                setCustomer (customer){
                    const cart = this.content;
                    cart.customer = customer;
                    this.setCart(cart)

                },
                setConfig (param = {}){
                    const cart = this.content;
                    const {config} = cart;
                    cart.config = {...param,...config};
                    this.setCart(cart)
                },

                setItems (items){
                    const cart  = this.content ;
                    if(items) {
                       items.forEach(item => item.amount = item.price * item.qty);
                       cart.items = items;
                       this.setCart(cart)
                    }
                    this.items = cart.items;
                },

                find (item){
                   return (this.items.length) ? this.items.find( ({id}) => (id === item.id)) : null
                },

                get total () {
                    return getSum(this.items,"amount")
                }  ,

                add(item){
                    const items = this.items;
                    const product = this.find(item)
                    if (product){
                        this.update(product,++product.qty)
                        item = product
                    }else{
                        item.qty = 1;
                        items.push(item)
                    }

                    toast({title : "<span class='fs-12'> " + item.qty +" x "+ item.name.toUpperCase()+"</span>"})
                   this.setItems(items)
                },
                update (item, qty){
                    const items = this.items;
                    if (typeof item === 'object' && ('id' in item)){
                      item = item.id;
                    }
                    items.forEach( cart_item => {
                        if (cart_item.id === item) {
                            cart_item.qty = qty
                        }
                    })
                    this.setItems(items)
                },
                remove (product){
                   let items = this.items;
                   items =  items.filter(item => item.id !== product.id);
                   this.setItems(items)
                },
            });

            Alpine.data('block_products', (allProducts = []) => ({
                search : "",
                products : allProducts,

                get filteredProducts (){
                    const search = this.search.toLowerCase()
                    if(search){
                        return this.products.filter(
                            product => product.name.toLowerCase().startsWith(search) || product.fullName.toLowerCase().includes(search)
                        )
                    }
                    return this.products;
                }
            }));

            Alpine.data('block_customers', (allCustomers = []) => ({
                init (){
                   // localStorage.setItem("CUSTOMERS_LIST",JSON.stringify(allCustomers))
                    //JSON.parse(localStorage.getItem("CUSTOMERS_LIST")) ?? []
                },
                search : "",
                customers : allCustomers,
                active : false,

                get filteredCustomers (){
                    const search = this.search.toLowerCase()
                    if(search){
                        return this.customers.filter(
                            customer=> (
                                customer.full_name.toLowerCase().startsWith(search) ||
                                customer.phone.startsWith(search) ||
                                // customer.email.toLowerCase().includes(search) ||
                                customer.full_name.toLowerCase().includes(search) ||
                                customer.phone.includes(search)

                            )
                        )
                    }
                    return [];
                },

                addCustomer (){
                    const alpine = this;
                    editorCustomer.create({
                        title : "{{__("Add Customer")}}",
                        buttons: {
                            label: "{{__("Add")}} <i class='fa fa-plus'></i>",
                            className : "btn-success",
                            fn : function (e) {
                                const first_name = this.field('first_name').get();
                                const last_name = this.field('last_name').get();
                                const phone = this.field('phone').get().toString();
                                const email = this.field('email').get();
                                const avatar = "{{get_gravatar(fake()->email)}}";

                                const customer = {
                                    id : ++alpine.customers.length,
                                    first_name,
                                    last_name,
                                    full_name : first_name + " " + last_name,
                                    email,
                                    phone,
                                    avatar,
                                    is_new : true
                                }

                                if (phone === ""){
                                    this.field('phone').error('This field is required')
                                    return ;
                                }

                                alpine.customers.push(customer);
                                alpine.$store.cart.setCustomer(customer);
                                alpine.active = false;

                                this.close();
                            },
                        },
                    })
                }
            }));

            Alpine.data('bloc_cart', () => ({

                init(){
                    this.paymentMethods = @json($paymentMethods),
                    this.paymentMethods.push({
                        code : "NO_PAYMENT",
                        name : "No Payment",
                        image : "{{url('images/payments-methods/default.jpg')}}",
                    })

                    this.paymentMethod = this.paymentMethods.find(method => method.code === "NO_PAYMENT")
                },
                paymentMethods : [],
                paymentMethod : null,
                paymentMethodId : null,

                updateQty (td,item) {
                    const alpine = this;
                    const qty = item.qty;

                    editor.field('qty').s.def = qty
                    editor.field('qty').set(qty)
                    editor.field('qty').dom.inputControl.value = qty;

                    editor.bubble( td,["qty"], {
                        message: item.name.toUpperCase(),
                        buttons: {
                            label: '{{__("OK")}}',
                            className : "btn-success fs-11",
                            fn : function (e) {
                                const new_qty = parseFloat(this.field('qty').get());

                                if(new_qty > 0){
                                    alpine.$store.cart.update(item, new_qty)
                                    this.close();
                                }else{
                                    this.field('qty').error("{{__('This value is invalid.')}}");
                                }
                                // $(".DTE_Form_Error").css("display","none")
                            },
                        },
                    } );

                },

                get payable(){
                  const {code} = this.paymentMethod;
                  const {net_payable} = this.allTotal;

                  let result = true;

                  if (code === 'NO_PAYMENT' || net_payable ===0){
                      result = false;
                  }
                  else if (code !== 'NO_PAYMENT' && net_payable > 0){
                      result = true;
                  }
                  return result;
                },

                get allTotal (){

                    const cart = this.$store.cart;
                    const {total,customer} = cart;

                    const  {balance} = customer;
                    const  tax = 0;

                    const  discount = 0;

                    const cartTotal = (total + tax) - discount;
                    let    net_payable = cartTotal;

                    const result = {
                        sub_total : {
                            label: "Sub Total",
                            className: "fs-12",
                            value : total,
                        },
                        tax  : {
                            label: "Tax",
                            className: "fs-12",
                            value :  tax
                        },
                        discount  : {
                            label: "Discount"+" ("+discount/100+"%)",
                            className: "fs-12 text-success",
                            value : discount
                        },
                        total  : {
                            label: "Total",
                            className: "fs-13 text-success",
                            value : cartTotal
                        },
                    };

                    if (balance <= cartTotal){
                        net_payable = cartTotal - balance;
                    }else if ( balance > cartTotal){
                        net_payable = 0;
                    }
                    result.net_payable = {
                        label: "Net Payable",
                        className: "fs-14 text-danger",
                        value : net_payable
                    }
                    return result;
                },

                addOrderToDraft(){
                    console.log(this.paymentMethodId)
                    const order = this.$store.cart.content;
                    if (order){
                        this.$store.draft.add(order)
                    }
                },

                printOrder(order = null){

                },

                sendOrder(order,payment = null){

                },

                payOrder(){
                    const alpine = this
                    const paymentMethod = alpine.paymentMethod;
                    const order = alpine.$store.cart.content;
                    const widget = paymentWidget({
                        paymentMethod,
                        onCompleted (){
                          alpine.sendOrder(order)
                        },
                    })

                    if (paymentMethod) {
                      return  widget.show();
                    }

                },


            })  );
        })
    </script>
@endpush
