<template>
    <div class="card card-primary">
        <div class="panel panel-black">
            <div v-if="showMessage" >
                <div class="alert alert-success">
                    {{ message }}
                </div>
            </div>
            <div>
                <table class="table table-hover">
                    <thead>
                    <tr>
                        <th scope="col">Name</th>
                        <th scope="col">Price</th>
                        <th scope="col">Quantity</th>
                        <th scope="col">Remove</th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr v-for="(prod,index) in selected_products" :key="componentKey + index">
                        <th scope="row">{{prod.name}}-{{prod.description}}</th>
                        <td :id="'amount'+ prod.product_id" >#{{ prod.price * selected_products[prod.product_id].quantity }}</td>
                        <td><input v-on:click="quantity(prod.product_id)"
                                   v-on:focusout="quantity(prod.product_id)"
                                   type="number" required placeholder="Enter Quantity" min="1" :id="'quantity' + prod.product_id " :value="prod.quantity" ></td>
                        <td><button class="btn-danger" @click="delete_from_cart(prod.product_id)" >Delete</button></td>
                    </tr>
                    </tbody>
                </table>
            </div>
            <div class="panel-body">
                <form class="form-horizontal" role="form" method="POST"
                      action="">
                    <div class="form-group">
                        <label class="col-md-4 control-label">Product</label>
                        <div class="col-md-6">
                            <select v-model="productId" v-on:click="total" class="form-control" id="product_id">
                                <option value="">Select Product</option>
                                <option v-for="product in products" :key="product.id"
                                        data-price="product.price" id="product" :value="product.id"> {{product.name}} -  {{product.description}}</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-md-6">
                            <label for="total_amount">Total Amount</label>
                            <p id="total_amount" readonly class="col-md-4 control-label form-control"></p>
                        </div>

                    </div>
                    <div class="form-group">
                        <label class="col-md-4 control-label">Date</label>

                        <div class="col-md-6">
                            <input v-model="date" type="date" name="date" required id="date"
                                   class="form-control">
                        </div>
                    </div>


                    <div class="form-group">
                        <div class="col-md-6">
                            <select v-model="mode_of_payment" class="form-control" id="pay_channel">
                                <option value="">Select Payment Channel</option>
                                <option value="POS">POS</option>
                                <option value="CASH">CASH</option>
                                <option value="TRANSFER">TRANSFER</option>
                                <option value="ONLINE">ONLINE</option>
                                <option value="PENDING">PENDING</option>
                            </select>
                        </div>

                    </div>

                    <div class="form-group">
                        <div v-show="rev_show" class="col-md-6 review_wrapper" id="review_wrapper">
                            <label >Review</label>
                            <input v-model="review" type="text" placeholder="Review" required class="form-control" name="review" id="review">
                        </div>
                    </div>

                    <div class="form-group">
                        <p id="amounts" class="col-md-6 col-md-offset-4"></p>
                    </div>
                    <div class="form-group">
                        <div class="col-md-6 col-md-offset-4">
                            <button @click="submit" type="button" style="border: 1px solid #f25f43;" class="btn btn-primary">
                                <i class="fa fa-btn fa-money"></i> Make Sale
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</template>

<script>
import { mixin as clickaway } from 'vue-clickaway';

export default {
    name: "newsales"
    ,
    mixins: [ clickaway ],
    data(){
        return {
            the_inventory:{},
            checkInventory:0,
            dict:{},
            review:'',
            mode_of_payment:'',
            rev_show:false,
            date:'',
            componentKey:1000,
            selected_products:{},
            finds:{},
            productId:'',
            showMessage:false,
            message:'',
        }
    },
    watch:{
        productId(){
            if (! this.selected_products[this.productId] && this.productId){
                if (this.inInventory(this.productId)){
                    this.cart();
                    this.total()
                }
                // console.log(this.inventories[0][this.productId])
            }
        },
        mode_of_payment(){
            this.rev_show = this.mode_of_payment === 'PENDING';
        },
    },
    methods: {
        cart(){

            if (this.productId){
                let i = 0
                let len = Object.keys(this.products).length
                for (; i<len;i++){
                    if (this.productId === this.products[i]['id']){
                        // console.log(this.products[i]['id'])
                        this.finds[this.productId] = this.products[i];
                        this.selected_products[this.productId] = {'product_id':this.productId,'price': this.products[i].price ,
                            'name':this.products[i].name,
                            'description':this.products[i].description,
                            'quantity':1 , 'amount':this.products[i].price}
                        this.productId = '';
                    }
                }
            }
        },
        quantity(product_id){
            let inputValue = document.getElementById("quantity"+product_id.toString()).value
            this.selected_products[product_id].quantity = inputValue;
            this.selected_products[product_id].amount = inputValue * this.selected_products[product_id].price;
            document.getElementById('amount'+product_id.toString()).innerHTML = "#"+this.selected_products[product_id].amount
            this.total()

        },
        total(){
            let a = 0;
            let leng = Object.keys(this.selected_products).length;
            // console.log(leng)
            let tot = 0;
            for (; a<leng;a++){
                 tot+=parseInt(Object.values(this.selected_products)[a].amount);
                }
            document.getElementById('total_amount').innerHTML = "#"+ tot
            },
        delete_from_cart(product_id){
            // in any component
            this.$confirm("Are you sure? This action is irreversible",'Remove Item From Cart ','warning').then(() => {
                delete this.selected_products[product_id];
                this.componentKey++
                this.total()
            });
        },
        submit(){
            if (this.mode_of_payment){
               if(this.date){
                   let len = Object.keys(this.selected_products).length
                   if (len > 0){
                       this.$confirm("",'Confirm Sales','info').then(() => {
                           let i = 0
                           for(;i<len;i++){
                               Object.values(this.selected_products)[i]['date']=this.date
                               Object.values(this.selected_products)[i]['pay_channel']=this.mode_of_payment
                               this.dict = Object.values(this.selected_products)[i];
                               axios.post('new',{
                                   'pay_channel':this.dict.pay_channel,
                                   'product_id':this.dict.product_id,
                                   'amount':this.dict.amount,
                                   'date':this.dict.date,
                                   'review':this.review,
                                   'quantity':this.dict.quantity})
                                   .then(res=>{
                                       if (i === len){
                                           this.selected_products = {}
                                           this.dict = {}
                                           this.$alert('Item(s) sold successfully','Items Sold','success')
                                           setTimeout(() => this.showMessage = false, 5000)
                                       }
                                   })
                                   .catch(error=>{
                                       alert(error)
                                   })
                           }
                       });

                   }
                   else {
                       this.$alert('No Item selected', 'Empty Cart','error')
                   }
               }
               else {
                   this.$alert('Pick a date','No Date Selected','error')
               }
            }
            else {
                this.$alert('Select a payment channel','NO PAYMENT CHANNEL SELECTED','error')
            }
        },
        inInventory(x) {
            if (this.the_inventory[x]) {
                return true
            }
            else if(this.the_inventory[x] === undefined){
                this.$alert('This Item is not in the Inventory, Notify the admin','OPPS','error')
                return false
            }

        }
        },
    mounted(){
           let a = 0;
           let len = this.inventories.length
           for (; a<len;a++){
               this.the_inventory[this.inventories[a]['product_id']] = {'quantity':this.inventories[a]['quantity'],'id':this.inventories[a]['product_id']}

           }


    },
    props:['products', 'inventories']
}
</script>

<style scoped>

</style>
