<template>
    
  <!-- Add Organisation Model End-->
  <!-- Header Start-->
  
   
  <!-- Body Start -->
  <div style="background-color:#F5F7F9; ">
  <div class="wrapper wrapper-body" style="background-color:#F5F7F9;  margin-top: -10px; x">
    <div class="dashboard-body container">
      <div class="container-fluid">
        <Transition name="slide-fade">
        <v-alert style="position: fixed; z-index: 2000; margin-top:105px" v-if="success" class="mb-6" color="#344470" type="success" variant="flat" closable > Order Sent!
        </v-alert>
        </Transition>
        
        <Transition name="slide-fade">
        <v-alert style="position: fixed; z-index: 2000;margin-top:105px" v-if="empty" class="mb-6" color="red" type="warning" variant="flat" closable > Fill In Your Info to Continue
        </v-alert>
        </Transition>
        <Transition name="slide-fade">
        <v-alert style="position: fixed; z-index: 2000;margin-top:105px" v-if="deleted" class="mb-6" color="red" type="warning" variant="flat" closable > Item Removed
        </v-alert>
        </Transition>

          <div class="row">
         
         
          
          <div class="col-md-10">
            
            <div style="margin-top: 120px;"></div>
            <div style="background:; ">
              
              <div ><a style="opacity:.4; margin-right: 7px">Showing </a> Cart</div>
            </div>
            <div style="margin-top: 20px;"></div>
            <div class=""  v-if="tableloading || loadingItem "  v-for="item in 1" :key="item">
              <div class="box">
                <div class="skeleton">
                      <div class="skeleton-left">
                    <div class="line"></div>
                    <div class="line h8 w50"></div>
                    </div>
                    <div class="skeleton-right">
                      <div class="line  w75"></div>
                    </div>
                  <div class="skeleton-right">
                      <div class="line  w75"></div>
                    </div>
                </div>
              </div>
            </div>
            <div class="  " v-if="!tableloading && cart==[]" style="  "  >
              <h2> Cart Is Empty!</h2>
            </div>
            
            <div class="row" v-if="!loadingItem">
              <div class="col-md-12 mt-2" style=" " >
                <div class="col-md-12 mt-2" style=" "  >
                  
                  <div class="  " v-if="!tableloading && !cart==[]" style="  height: ;"  >
                    <div class="row"  >
                     
                      <div class="col-md-12 mt-5">
                         <v-row>
                            <v-col v-for="(item, index) in cartItems" :key="item.id" cols="12" :md="cart.length==1?12:6">
                              <v-card class="pa-4">
                                <v-card-title style="font-size: 15px; word-wrap: break-word;">Item: {{ item.name }}</v-card-title>
                                <v-card-subtitle style="font-weight: normal;">Price: {{ item.price }}/ {{item.unit}} <b v-if="item.qty!=='1'" style="margin-left: 24%; font-weight: normal; color:black; font-weight:600">Qty: {{item.qty}}</b><b v-else style="margin-left: 24%;">Qty: 1</b></v-card-subtitle>

                                <v-card-text>
                                  <v-row align="center">
                                    <v-col cols="4">
                                      <v-btn icon="mdi-minus" @click="decreaseQuantity(item.id)" />
                                      <v-text-field
                                      style="width: 60px;"
                                        v-model="quantities[item.id]"
                                        type="number"
                                        min="1"
                                        class="mx-2"
                                        dense
                                        hide-details
                                      />
                                      <v-btn icon="mdi-plus" @click="increaseQuantity(item.id)" />
                                    </v-col>
                                    <v-col cols="4">
                                      <strong>Total: ${{ calculateTotal(item) }}</strong>
                                    </v-col>
                                    <v-col cols="4">
                                      <v-btn flat color="red" style="" @click="deleteItem(item.id)"><i class="fa-solid fa-trash" ></i><a style="text-transform: capitalize; font-size:12px;;">Remove</a> </v-btn>
                                    </v-col>
                                  </v-row>
                                </v-card-text>
                              </v-card>
                            </v-col>
                          </v-row>

                          <v-divider class="my-4"></v-divider>

                          <h3 class="text-h5">Grand Total: <b>${{ grandTotal }} </b></h3>
                      </div>
                      
                    </div>

                  </div>
                  <div>
                  </div>
                </div>
               
                <div class="main-card mt-4">
                  <div class="dashboard-wrap-content">
                    <div class="p-3 row">
                      
                      <div class="row">
                        <div class="col-md-4">
                          <input
                            v-model="Cname"
                            placeholder="Enter Your Name"
                            class="form-control"
                          ><input> 
                        </div>
                        <div class="col-md-4">
                          <input
                            v-model="Cphone"
                            placeholder="Phone Number"
                            class="form-control"
                          ><input> 
                        </div>
                        <div class="col-md-4">
                          <input
                            v-model="Cemail"
                            placeholder="Email(optional)"
                            class="form-control"
                          ><input> 
                        </div>
                        
                      </div> 
                    </div>         
                  </div>          
              </div> 
              <div class="col-md-12 mt-3 justify-content-center mx-auto text-center">
                  <v-btn  style="width:130px; background: #344470;height: 45px; "
                          class="site-btn text-center mt-4 text-white"
                          variant="flat"
                          :loading="loadingOrder"
                          @click="submitCart"max-width="200px">
                    Send Order
                  </v-btn>
                </div>
              </div>
            </div>
            <div>
              <div>
                
              </div>
            </div>
            
          </div>
         
          <div class="col-md-12 d-none">
            <div class="main-card mt-8" style="">
              <div class="main-card "  >
                <div class="dashboard-wrap-content " style="">
                  <div class="text-center align-items-center p-2" style="background-color:#e2f8f1; margin-bottom: -19px; border-radius: 0px;">
                    <h5 class="text-center"></h5>
                  </div>
                </div>
              </div>
              <div class="main-card mt-4">
                  <div class="dashboard-wrap-content">
                    <div class="p-3 row">
                      
                     

                      <v-spacer></v-spacer>
                      <v-text-field
                        density="compact"
                        label="Search"
                        prepend-inner-icon="mdi-magnify"
                        variant="solo-filled"
                        flat
                        hide-details
                        single-line
                      ></v-text-field>  
                    </div>
                    
                   
                    
                   
                          
                  </div>
                  <v-dialog
                    v-model="dialog"
                    max-width="680px"
                    style="height: 90vh; overflow-y: scroll;"
                  >
                    
                  </v-dialog>
                  <v-dialog v-model="dialogDelete" max-width="500px">
                    <v-card style="font-size: 14px;">
                      <v-card-title class="text-h5 " >
                      <p class="pl-5 pr-5 pt-4" style="font-size: 16px;">Are you sure you want to delete this item?</p></v-card-title>
                      <v-card-actions>
                        <v-spacer></v-spacer>
                        <v-btn color="#344470" variant="text" @click="closeDelete">Cancel</v-btn>
                        <v-btn color="#344470" variant="flat" @click="deleteItemConfirm(editteam.id)">OK</v-btn>
                        <v-spacer></v-spacer>
                      </v-card-actions>
                    </v-card>
                  </v-dialog>
              </div>  
            </div>
          </div>
         
       
        </div>
      </div>
    </div>
  </div>    
  </div>
<SideNav @clicked="ChangeT($event)" @category="ChangeC($event)" />


    
  </template>
  
  <script setup>
  import { useStore } from 'vuex';
  import { ref, onMounted,onBeforeMount, computed } from 'vue'
  import axiosClient from "../../axios";
  import { useRoute } from 'vue-router';
  import router from '@/router';
  import SideNav from "../../components/LayOut2.vue"
  import ViewProducts from "../../components/views/ViewProducts.vue"
  // Import Vue FilePond
  import { watch ,toRefs} from 'vue'
  import { read, utils, writeFile } from 'xlsx';
 

  
  // Date picker

 
  
  const newdates = ref();

  const dialog = ref(false);
  const dialogDelete = ref(false);
  const editteam = ref([]);

  // ---data ---//

  const Tid = ref('');
  const Teamname = ref('');
  const Tlogo = ref('');
  const Tbigmatch = ref('');
  const imgurl = ref('');
  const imgurl2 = ref('');
  const file = ref('') ;
  const file2 = ref('') ;
  const products = ref([]) ;


  const loading = ref(false);
  const success = ref(false);
  const err = ref('');
  const empty = ref(false);
  const tableloading = ref(true);
  const deleted = ref(false);
  const loadingOrder = ref(false);
  const search = ref();
  const exceldata =ref([])
  const categories =ref([])
  const category =ref()
  const newdata =ref()
  const viewall =ref()


  //--- end data ---//

  const store = useStore();
  const user = ref('');
  const route = useRoute();
  const routeName = computed(() => route.name);
  const searchR = computed(() => search.value);
  const catR = computed(() => category.value);
  
  const itemsPerPage = 10;
  const currentPage = ref(1);
  const loadingItem = ref(false);
  const loadingCart = ref({});
  const loadingC = ref({}); 
  const tempCart = ref([]); 
  const Cname = ref(); 
  const Cphone = ref(); 
  const Cemail = ref(); 
  const data = ref(
    
  );
  let cart2 =''
  if(sessionStorage.getItem("cart")){
   cart2 =JSON.parse(sessionStorage.getItem("cart"))

  }
  const cart = ref(cart2);
  cart.value=JSON.parse(sessionStorage.getItem("cart"))

  // ----- cart
  

  const price =ref()
  const total1 =ref()
  const quantity =ref(1)
  const priceWatch = computed(() => price.value);
  const qWatch = computed(() => quantity.value);
  
  const watchData = computed(() => data.value);
  const totalPages = computed(() => Math.ceil(newdata.value.length / itemsPerPage));

  const paginatedData = computed(() => {
    const start = (currentPage.value - 1) * itemsPerPage;
    return newdata.value.slice(start, start + itemsPerPage);
  });

  // const increaseQuantity = (id,price0) => {
  //   tempCart.value = cart.value.filter((item)=>{
  //     return (item.id!==id)
  //   })
  //   // let newq= quantity.value++ + 1
  //   // let NPrice = price0.split("$")[1]
  //   // price.value="$"+parseFloat(NPrice * newq).toFixed(2)
  //   console.log(tempCart.value)
  // };

  // const decreaseQuantity = (price0) => {
  //   if(quantity.value==2 || quantity.value>1){
  //     let newq= quantity.value-- - 1
  //       let NPrice = price0.split("$")[1]
  //       price.value="$"+parseFloat(NPrice * newq).toFixed(2)
  //       console.log(price.value)
  //       }
    
  // };
  
  const deleteItem = (cid) => {  
 
    const newCart = cart.value.filter((item) =>{
       return (parseInt(item.id,10)!==cid)
    });
    sessionStorage.removeItem('cart')
    sessionStorage.setItem('cart',  JSON.stringify(newCart))
    deleted.value=true
    setTimeout(function() {
      window.location.reload()
    }, 1000);
    
    console.log(newCart)

  };

  const teamdetails= ref([''])
  // teamdetails.value =  products.value
  let userdata=''
  let userdata2=''
  let usertoken=''
  if(store.state){
    userdata = computed(() => JSON.parse(store.state.user.data))
    userdata2 = computed(() => store.state.user.data)
    usertoken = computed(() => store.state.user.token)

  }

  

  function clearCart() {

     sessionStorage.removeItem('cart')
     window.location.reload()
   }

  watch(priceWatch, (newValue, oldValue) => {
  
  });

  watch(qWatch, (newValue, oldValue) => {
  
     
      
  });

  watch(searchR, (newValue, oldValue) => {
  console.log(
          "changes: ",newValue
        );
    viewall.value=newValue
    items.value=true
    loadingItem.value=true
      setTimeout(()=>{
          loadingItem.value=false
      },400)
    if(newValue==''){
      items.value=false
    }
    newdata.value = data.value.filter((item) =>{
           return (item.item.toLowerCase().startsWith(newValue)||item.category.toLowerCase().startsWith(newValue)|| item.item.toLowerCase().includes(newValue))
        });
        currentPage.value=1
  });
  

  function all() {
      loadingItem.value=true
        setTimeout(()=>{
            loadingItem.value=false
        },400)
      items.value=true
        newdata.value = data.value
        currentPage.value=1
        viewall.value='All Items'

        
    
  }


  onMounted(()=>{


    axiosClient.get('/categories/get').then((res)=>{
        let data  = res.data;

      
      for (var bm = 0; bm < data.length; bm++) {
        categories.value.push(data[bm])
        
      }

    })

    setTimeout(()=>{
      axiosClient.get('/products/get').then((res)=>{
        let data  = res.data;
        let prod  = [];
        let Ids  = [];

        for (var bm = 0; bm < data.length; bm++) {
          prod.push(data[bm])
          for (var i = 0; i < cart.value.length; i++) {
            Ids.push(cart.value[i].id)
          }
          products.value=prod.filter((item) =>{
           return (Ids.includes(item.id))
        });
          tableloading.value = false
           exceldata.value.push({
            Item: data[bm].item,
            Umri:data[bm].umri,
            ID:data[bm].IDno,
            Kijiji:data[bm].kijiji,
            Kata:data[bm].kata,
            Wilaya:data[bm].wilaya
           })
         
        }

      })

    },950)


  })

  

    function ChangeT(title)
    {
      this.title=title;
      search.value=title
      console.log(title)
    }

    function ChangeC(title)
    {
      this.title=title;
      category.value=title
      console.log(title)
    }

   
  //------------------------------- cart--------------------------------------

   function addToCart(item){
    success.value=true
    setTimeout(function() {
     success.value=false
      }, 3000);  
     loadingCart.value[item] = true; // Set loadingCart state for the clicked button

    setTimeout(()=>{
      loadingCart.value[item] = false
    }, 750);
    console.log(item)
   }

   

   const rawData = cart.value
   let cartItems =''
// Remove duplicates based on ID
   const quantities = ref({});
   if(cart.value){

 cartItems = ref([...new Map(rawData.map(item => [item.id, item])).values()]);



// Initialize quantities
cartItems.value.forEach((item) => {
  quantities.value[item.id] = 1;
});
}else{
  loadingItem.value=false
  tableloading.value=false

}
// Convert price string to number (removing "$")
const parsePrice = (price) => Number(price.replace("$", ""));

// Increase quantity
const increaseQuantity = (id) => {
  quantities.value[id]++;
};

// Decrease quantity (Minimum = 1)
const decreaseQuantity = (id) => {
  if (quantities.value[id] > 1) {
    quantities.value[id]--;
  }
};

// Remove item from cart
const removeFromCart = (id) => {
  cartItems.value = cartItems.value.filter((item) => item.id !== id);
  delete quantities.value[id]; // Remove quantity tracking
};

// Calculate total price per item
const calculateTotal = (item) => {
  if(item.total!=="0" ){
    return (quantities.value[item.id] * parsePrice(item.total)).toFixed(2);
  }else{
    return (quantities.value[item.id] * parsePrice(item.price)).toFixed(2);
  }
  
};

// Compute Grand Total
const grandTotal = computed(() =>

   cartItems.value.reduce(
    (sum, item) => 
    
    sum + parsePrice(item.price)* parsePrice(item.qty) * quantities.value[item.id],
    0
  ).toFixed(2)

  
);


   // Log updated cart data
const submitCart = () => {
  if (!Cname.value || ! Cphone.value) {
    empty.value=true

    setTimeout(function() {
      empty.value=false
    }, 4000);
  }else{
     const cartData = cartItems.value.map(item => ({
      item: item.name,
      quantity: quantities.value[item.id],
      qty: item.qty,
      price: item.price,
      total: `$${calculateTotal(item)}`
    }));  


      const config = {
          headers: { 'content-type': 'multipart/form-data', 'accepts':'application/json','Access-Control-Allow-Origin':'*'}
      }

      loadingOrder.value=true
      const formData = new FormData();
      formData.append('name',Cname.value);
      formData.append('phone',Cphone.value);
      formData.append('email',Cemail.value);
      formData.append('cart',JSON.stringify(cartData) );
      formData.append('Gtotal',grandTotal.value);
     

      try {
           axiosClient.post('/sendMail' ,formData,config ).then(()=>{


           success.value=true
           sessionStorage.removeItem('cart')
          setTimeout(function() {
            success.value=false
            loadingOrder.value=false
            window.location.replace('/home')
          }, 4000);

           }).catch(error => {
           console.log(error.response.data.message)
           err.value = error.response.data.message

          setTimeout(function() {
           err.value = ''
           }, 6000);  
   

        })

      }
      catch(error) {
        if(error){
          console.log(error)
          
        }
          
      // }

      }    
     
     console.log("🛒 Updated Cart Data:", cartData,grandTotal.value,Cname.value);
  }
 
  
  
};


function sData(e){
   
   
    

 }

  </script>

  <style >
    
    .v-enter-active,
    .v-leave-active {
      transition: opacity 0.5s ease;
    }

    .v-enter-from,
    .v-leave-to {
      opacity: 0;
    }

    .topsearch{
      border: 1px solid #d7d7d7;
      background: white;
      width: 200px;
      height: 44px;
/*      color: #d6d6d6;
*/      padding: 15px;
    }



    :root {
      /*General*/
      --dp-font-family: -apple-system, blinkmacsystemfont, "Segoe UI", roboto, oxygen, ubuntu, cantarell, "Open Sans",
      "Helvetica Neue", sans-serif;
      --dp-border-radius: 4px; /*Configurable border-radius*/
      --dp-cell-border-radius: 4px; /*Specific border radius for the calendar cell*/
      --dp-common-transition: all 0.1s ease-in; /*Generic transition applied on buttons and calendar cells*/

      /*Sizing*/
      --dp-button-height:38px; /*Size for buttons in overlays*/
      --dp-month-year-row-height: 35px; /*Height of the month-year select row*/
      --dp-month-year-row-button-size: 35px; /*Specific height for the next/previous buttons*/
      --dp-button-icon-height: 20px; /*Icon sizing in buttons*/
      --dp-cell-size: 35px; /*Width and height of calendar cell*/
      --dp-cell-padding: 5px; /*Padding in the cell*/
      --dp-common-padding: 10px; /*Common padding used*/
      --dp-input-icon-padding: 35px; /*Padding on the left side of the input if icon is present*/
      --dp-input-padding: 6px 30px 6px 12px; /*Padding in the input*/
      --dp-menu-min-width: 310px; /*Adjust the min width of the menu*/
      --dp-action-buttons-padding: 2px 5px; /*Adjust padding for the action buttons in action row*/
      --dp-row-maring:  5px 0; /*Adjust the spacing between rows in the calendar*/
      --dp-calendar-header-cell-padding:  0.5rem; /*Adjust padding in calendar header cells*/
      --dp-two-calendars-spacing:10px; /*Space between multiple calendars*/
      --dp-overlay-col-padding:  3px; /*Padding in the overlay column*/
      --dp-time-inc-dec-button-size:  32px; /*Sizing for arrow buttons in the time picker*/
      --dp-menu-padding: 6px 8px; /*Menu padding*/
      
      /*Font sizes*/
      --dp-font-size: 1rem; /*Default font-size*/
      --dp-preview-font-size: 0.8rem; /*Font size of the date preview in the action row*/
      --dp-time-font-size: 0.8rem; /*Font size in the time picker*/
      
      /*Transitions*/
      --dp-animation-duration: 0.1s; /*Transition duration*/
      --dp-menu-appear-transition-timing: cubic-bezier(.4, 0, 1, 1); /*Timing on menu appear animation*/
      --dp-transition-timing: ease-out; /*Timing on slide animations*/


    }

    .dp-custom-calendar 
    .dp__calendar_item {
/*     border: 1px solid var(--dp-border-color-hover);
*/    }



    .dp-custom-cell {
      color:#132f65 ;
    }

    .dp__theme_light {
   --dp-background-color: #ffffff;
   --dp-text-color: #132f65;
   --dp-hover-color: #f3f3f3;
   --dp-hover-text-color: #212121;
   --dp-hover-icon-color: #959595;
   --dp-primary-color: #ff6f60;
   --dp-primary-text-color: #fff;
   --dp-secondary-color: #c0c4cc;
   --dp-border-color: #ddd;
   --dp-menu-border-color: #fff;
   --dp-border-color-hover: #aaaeb7;
   --dp-disabled-color: #f6f6f6;
   --dp-scroll-bar-background: #f3f3f3;
   --dp-scroll-bar-color: #959595;
   --dp-success-color: #959595;
   --dp-success-color-disabled: #a3d9b1;
   --dp-icon-color: #959595;
   --dp-danger-color: #ff6f60;
   --dp-highlight-color: rgba(25, 118, 210, 0.3);
}


   .custom-select{
      cursor: pointer;
      color: white;
      background: #132f65;
      margin: 0 0 0 20px;
      padding: 7px;
/*      width: 140px;
*/      font-size: 16px;
      border-radius: 3px;
      display: inline-block;
   }

  .btn2-primary{
    background: #132f65;
    color: #fff;
}

.btn2-secondary{
/*    background: #F5F7F9;
*/    color: #fff;
}


.pagination {
  margin-top: 10px;
}
.btnPage {
  margin: 5px;
  padding: 5px 10px;
  border: none;
  background: #344470;
  color: white;
  cursor: pointer;
  border-radius: 5px;
}
.btnPage:disabled {
  background: #ccc;
}


*{
     box-sizing: border-box;
}

 .box{
     max-width: 100%;
     width: 100%;
     padding: 0 px;
}
 .skeleton {
     padding:15px;
     max-width: 100%;
     width: 100%;
     background: #fff;
     margin-bottom: 20px;
     border-radius: 5px;
     display: flex;
     justify-content: center;
     align-items: center;
     border:1px solid #d2d2d2;
}
 .skeleton .square {
     height: 80px;
     border-radius: 5px;
     background: rgba(130, 130, 130, 0.2);
     background: -webkit-gradient(linear, left top, right top, color-stop(8%, rgba(130, 130, 130, 0.2)), color-stop(18%, rgba(130, 130, 130, 0.3)), color-stop(33%, rgba(130, 130, 130, 0.2)));
     background: linear-gradient(to right, rgba(130, 130, 130, 0.2) 8%, rgba(130, 130, 130, 0.3) 18%, rgba(130, 130, 130, 0.2) 33%);
     background-size: 800px 100px;
     animation: wave-squares 2s infinite ease-out;
}
 .skeleton .line {
     height: 12px;
     margin-bottom:6px;
     border-radius: 2px;
     background: rgba(130, 130, 130, 0.2);
     background: -webkit-gradient(linear, left top, right top, color-stop(8%, rgba(130, 130, 130, 0.2)), color-stop(18%, rgba(130, 130, 130, 0.3)), color-stop(33%, rgba(130, 130, 130, 0.2)));
     background: linear-gradient(to right, rgba(130, 130, 130, 0.2) 8%, rgba(130, 130, 130, 0.3) 18%, rgba(130, 130, 130, 0.2) 33%);
     background-size: 800px 100px;
     animation: wave-lines 2s infinite ease-out;
}
 .skeleton-right{
    flex:1;
}
 .skeleton-left{
    flex:2;
    padding-right:15px;
}
 .flex1{
    flex: 1;
}
 .flex2{
    flex: 2;
}
 .skeleton .line:last-child{
    margin-bottom: 0;
}
 .h8{
    height: 8px !important;
}
 .h10{
    height: 10px !important;
}
 .h12{
    height: 12px !important;
}
 .h15{
    height: 15px !important;
}
 .h17{
    height: 17px !important;
}
 .h20{
    height: 20px !important;
}
 .h25{
    height: 25px !important;
}
 .w25{
    width: 25% !important
}
 .w40{
    width:40% !important;
}
 .w50{
    width: 50% !important
}
 .w75{
    width: 75% !important
}
 .m10{
    margin-bottom: 10px !important;
}
 .circle{
    border-radius: 50% !important;
     height: 80px !important;
     width: 80px;
}
 @keyframes wave-lines {
    0% {
        background-position: -468px 0;
    }
     100% {
        background-position: 468px 0;
    }
}
 @keyframes wave-squares {
    0% {
        background-position: -468px 0;
    }
     100% {
        background-position: 468px 0;
    }
}
*{
     box-sizing: border-box;
}
 
 .card{
  background: linear-gradient(45deg, #fff, #fff 60%,#ffffff00 80%, #fff);
}
  </style>
