<template>
  <Header/>

  <div class="flex">
    <div class="">
      <SideBar/>
    </div>
    <div class=" w-full px-10">
      <div class="text-sm breadcrumbs">
        <ul>
          <li>
            <router-link :to="{ name: 'home' }">
              Home
            </router-link>
          </li>
        </ul>
      </div>


      <div class="grid grid-cols-1 rounded-md p-6 ">
        <div class="text-[24px]">
          Edit Oil Delivery
        </div>
        <div class="bg-neutral rounded-md mx-5 my-5">
          <div class="flex">
            Delivery id: {{ deliveryOrder.id }}
            <div class="grid grid-cols-12">
              <div class="col-span-6 bg-neutral p-5">
                <div class="grid grid-cols-12">
                  <div class="col-span-12 font-bold flex">
                    {{ customer.customer_first_name }}
                    {{ customer.customer_last_name }}
                  </div>
                  <div class="col-span-12 font-bold flex">
                    <div class="pr-2">
                      {{ customer.customer_town }},
                    </div>
                    <div class="pr-2">
                      <div v-if="customer.customer_state == 0">Massachusetts</div>
                      <div v-else-if="customer.customer_state == 1">Rhode Island</div>
                      <div v-else-if="customer.customer_state == 2">New Hampshire</div>
                      <div v-else-if="customer.customer_state == 3">Maine</div>
                      <div v-else-if="customer.customer_state == 4">Vermont</div>
                      <div v-else-if="customer.customer_state == 5">Maine</div>
                      <div v-else-if="customer.customer_state == 6">New York</div>
                      <div v-else>Unknown state</div>
                    </div>
                    <div class="pr-2">
                      {{ customer.customer_zip }}
                    </div>
                  </div>

                  <div class="col-span-12 font-bold flex" v-if="customer.customer_apt !== 'None'">
                    {{ customer.customer_apt }}
                  </div>
                  <div class="col-span-12 font-bold flex">
                    <div v-if="customer.customer_home_type == 0">Residential</div>
                    <div v-else-if="customer.customer_home_type == 1">apartment</div>
                    <div v-else-if="customer.customer_home_type == 2">condo</div>
                    <div v-else-if="customer.customer_home_type == 3">commercial</div>
                    <div v-else-if="customer.customer_home_type == 4">business</div>
                    <div v-else-if="customer.customer_home_type == 5">construction</div>
                    <div v-else-if="customer.customer_home_type == 6">container</div>
                  </div>
                  <div class="col-span-12 font-bold flex">
                    {{ customer.customer_phone_number }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="grid grid-cols-1" v-if="deliveryOrder.payment_type==1">
          <div class="flex">
            <div class="basis-1/3 p-2">
              <div class="bg-neutral rounded-md border-2 ">
                <div class="flex p-3">
                  {{ userCard.type_of_card }}
                </div>
                <div class="flex p-1 pl-4">
                  {{ userCard.name_on_card }}
                </div>
                <div class="flex p-1 pl-4">
                  {{ userCard.card_number }}
                </div>
                <div class="flex p-1 pl-4">
                  {{ userCard.expiration_month }}/ {{ userCard.expiration_year }}
                </div>
              </div>
            </div>
          </div>
        </div>


        <div class="bg-neutral rounded-md mx-5 my-5">
          <div class="flex">
            Order Date: {{ deliveryOrder.when_ordered }}
          </div>
          <div class="flex">
            Expected Delivery Date: {{ deliveryOrder.expected_delivery_date }}
          </div>
          <div class="flex">
            Price per gallon: {{ deliveryOrder.customer_price }}
          </div>
        </div>
        <div class="bg-neutral rounded-md mx-5 my-5">
          <div class="flex">

          </div>
        </div>

        <form class="rounded-md px-8 pt-6 pb-8 mb-4 w-full" enctype="multipart/form-data" @submit.prevent="onSubmit">

            <div class="bg-neutral">

            <div class="col-span-12 md:col-span-4 mb-5 md:mb-0 gap-10">
              <label class="block text-white text-sm font-bold cursor-pointer label">Cash</label>
              <input v-model="CreateOilOrderForm.basicInfo.cash"
                     class="checkbox"
                     id="cash"
                     type="checkbox"/>
            </div>

            <div class="col-span-12 md:col-span-4 mb-5 md:mb-0 gap-10">
              <label class="block text-white text-sm font-bold cursor-pointer label">Credit </label>
              <input v-model="CreateOilOrderForm.basicInfo.card"
                     class="checkbox"
                     id="Credit"
                     type="checkbox"/>
            </div>

            <div class="flex-1 mb-4">
              <label class="block text-white text-sm font-bold mb-2">Customer Cards Payment</label>
              <select
                  class="select select-bordered w-full max-w-xs"
                  aria-label="Default select example" id="userCards"
                  v-model="CreateOilOrderForm.basicInfo.userCards">
                <option class="text-white" v-for="(card, index) in userCards"
                        :key="index"
                        :value="card['id']">
                  {{ card['type_of_card'] }} {{ card['card_number'] }}
                </option>
              </select>
            </div>
          </div>

          <div class="flex-1 mb-4">
            <label class="block text-white text-sm font-bold mb-2">Delivery Status</label>
            <select
                class="select select-bordered w-full max-w-xs"
                aria-label="Default select example" id="delivery_status"
                v-model="CreateOilOrderForm.basicInfo.delivery_status">
              <option class="text-white" v-for="(delivery, index) in deliveryStatus"
                      :key="index"
                      :value="delivery['value']">
                {{ delivery['text'] }}
              </option>
            </select>
            <span v-if="v$.CreateOilOrderForm.basicInfo.delivery_status.$error" class="text-red-600 text-center">
                    {{ v$.CreateCustomerForm.basicInfo.delivery_status.$errors[0].$message }}
                </span>
          </div>


          <div class="col-span-12 md:col-span-4 mb-5 md:mb-0 gap-10">
            <label class="block text-white text-sm font-bold cursor-pointer label">Fill </label>
            <input v-model="CreateOilOrderForm.basicInfo.customer_asked_for_fill"
                   class="checkbox"
                   id="fill"
                   type="checkbox"/>
          </div>

          <div class="mb-4">
            <label class="block text-white text-sm font-bold mb-2">Gallons Ordered</label>
            <input v-model="CreateOilOrderForm.basicInfo.gallons_ordered"
                   :disabled="CreateOilOrderForm.basicInfo.customer_asked_for_fill "
                   class="input input-bordered w-full max-w-xs"
                   id="title" type="text" placeholder="# gallons"/>
            <span v-if="v$.CreateOilOrderForm.basicInfo.gallons_ordered.$error" class="text-red-600 text-center">
              {{ v$.CreateOilOrderForm.basicInfo.gallons_ordered.$errors[0].$message }}
            </span>
          </div>

          <div class="mb-4">
            <label class="block text-white text-sm font-bold mb-2">Expected </label>
            <input v-model="CreateOilOrderForm.basicInfo.expected_delivery_date"
                   class="input input-bordered w-full max-w-xs"
                   id="title" type="date"
                   min="2023-01-01" max="2030-01-01"/>
            <span v-if="v$.CreateOilOrderForm.basicInfo.expected_delivery_date.$error"
                  class="text-red-600 text-center">
              {{ v$.CreateOilOrderForm.basicInfo.expected_delivery_date.$errors[0].$message }}
            </span>
          </div>

          <div class="mb-4">
            <label class="block text-white text-sm font-bold cursor-pointer label">Delivery Notes</label>

            <textarea class="textarea textarea-bordered h-24 w-full"
                      placeholder="Describe any thing given from the customer .."
                      v-model="CreateOilOrderForm.basicInfo.dispatcher_notes_taken"></textarea>

          </div>


          <div class="col-span-12 md:col-span-4 mb-5 md:mb-0 gap-10">
            <label class="block text-white text-sm font-bold cursor-pointer label">Prime</label>
            <input v-model="CreateOilOrderForm.basicInfo.prime"
                   class="checkbox"
                   id="prime"
                   type="checkbox"/>
          </div>


          <div class="col-span-12 md:col-span-4 mb-5 md:mb-0 gap-10">
            <label class="block text-white text-sm font-bold cursor-pointer label">Same Day </label>
            <input v-model="CreateOilOrderForm.basicInfo.same_day"
                   class="checkbox"
                   id="same_day"
                   type="checkbox"/>
          </div>

            <div class="flex-1 mb-4">
            <label class="block text-white text-sm font-bold mb-2">Delivery Driver </label>
            <select class="select select-bordered w-full max-w-xs" aria-label="Default select example" id="customer_state"
              v-model="CreateOilOrderForm.basicInfo.driver_driver">
              <option class="text-white" v-for="(driver, index) in truckDriversList" :key="index" :value="driver['id']">
                {{ driver['employee_first_name'] }}  {{ driver['employee_last_name'] }}
              </option>
            </select>

          </div>


          <div class="col-span-12 md:col-span-12 flex mt-5 mb-5">
            <button
                class="btn">
              Edit Oil Delivery
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
  <Footer/>
</template>


<script lang="ts">
import {defineComponent} from 'vue'
import axios from 'axios'
import authHeader from '../../services/auth.header'
import Header from '../../layouts/headers/headerauth.vue'
import SideBar from '../../layouts/sidebar/sidebar.vue'
import Footer from '../../layouts/footers/footer.vue'
import useValidate from "@vuelidate/core";
import {minLength, required} from "@vuelidate/validators";
import {notify} from "@kyvg/vue3-notification";

export default defineComponent({
  name: 'deliveryEdit',

  components: {
    Header,
    SideBar,
    Footer,
  },

  data() {
    return {
      v$: useValidate(),
      user: null,
      deliveryStatus: [],
      truckDriversList: [],
      userCards: [],
      userCard: {
        date_added: '',
        user_id: '',
        card_number: '',
        last_four_digits: '',
        name_on_card: '',
        expiration_month: '',
        expiration_year: '',
        type_of_card: '',
        security_number: '',
        accepted_or_declined: '',
        main_card: '',
      },
      customer: {
        id: 0,
        user_id: 0,
        customer_first_name: '',
        customer_last_name: '',
        customer_town: '',
        customer_state: 0,
        customer_zip: '',
        customer_apt: '',
        customer_home_type: 0,
        customer_phone_number: '',
      },
      deliveryOrder: {
        id: '',
        customer_id: 0,
        customer_name: '',
        customer_address: '',
        customer_town: '',
        customer_state: 0,
        customer_zip: '',
        gallons_ordered: 0,
        customer_asked_for_fill: 0,
        gallons_delivered: '',
        customer_filled: 0,
        delivery_status: 0,
        when_ordered: '',
        when_delivered: '',
        expected_delivery_date: '',
        automatic: 0,
        oil_id: 0,
        supplier_price: '',
        customer_price: '',
        customer_temperature: '',
        dispatcher_notes: '',
        prime: 0,
        same_day: 0,
        payment_type: 0,
        payment_card_id: 0,
        driver_employee_id: 0,
        driver_first_name: '',
        driver_last_name: '',
      },
      CreateOilOrderForm: {
        basicInfo: {
          gallons_ordered: '',
          customer_asked_for_fill: false,
          expected_delivery_date: '',
          dispatcher_notes_taken: '',
          prime: false,
          same_day: false,
          delivery_status: '',
          userCards: [],
          credit_card_id: 0,
          cash: false,
          card: false,
          driver_driver: '',
        },
      },
    }
  },
  validations() {
    return {
      CreateOilOrderForm: {
        basicInfo: {
          gallons_ordered: {required, minLength: minLength(1)},
          expected_delivery_date: {required},
          delivery_status: {required},
        },
      },
    };
  },
  created() {
    this.userStatus()
    this.getDriversList()
  },
  watch: {
    $route() {
      this.getDeliveryForm(this.$route.params.id);
      this.getDeliveryOrder(this.$route.params.id);
    },
  },
  mounted() {
    this.getDeliveryForm(this.$route.params.id)
    this.getDeliveryOrder(this.$route.params.id);
    this.getDeliveryStatusList();
  },
  methods: {
    userStatus() {
      let path = import.meta.env.VITE_BASE_URL + '/auth/whoami';
      axios({
        method: 'get',
        url: path,
        withCredentials: true,
        headers: authHeader(),
      })
          .then((response: any) => {
            if (response.data.ok) {
              this.user = response.data.user;
            }
          })
          .catch(() => {
            this.user = null
          })
    },

    getDeliveryOrder(delivery_id: any) {
      let path = import.meta.env.VITE_BASE_URL + "/delivery/" + delivery_id;
      axios({
        method: "get",
        url: path,
        withCredentials: true,
        headers: authHeader(),
      })
          .then((response: any) => {
            if (response.data) {
              this.CreateOilOrderForm.basicInfo.gallons_ordered = response.data.delivery.delivery_gallons_ordered;
              this.CreateOilOrderForm.basicInfo.customer_asked_for_fill = response.data.delivery.delivery_asked_for_fill;
              this.CreateOilOrderForm.basicInfo.expected_delivery_date = response.data.delivery.delivery_expected_delivery_date;
              this.CreateOilOrderForm.basicInfo.dispatcher_notes_taken = response.data.delivery.delivery_dispatcher_notes;
              this.CreateOilOrderForm.basicInfo.prime = response.data.delivery.delivery_prime;
              this.CreateOilOrderForm.basicInfo.same_day = response.data.delivery.delivery_same_day;
              this.CreateOilOrderForm.basicInfo.delivery_status = response.data.delivery.delivery_status;

              this.CreateOilOrderForm.basicInfo.driver_driver = response.data.delivery.driver_employee_id;

              if (response.data.delivery.payment_type == 1) {
                this.CreateOilOrderForm.basicInfo.userCards = response.data.delivery.payment_card_id;
              }
              if (response.data.delivery.delivery_prime == 1) {
                this.CreateOilOrderForm.basicInfo.prime = true
              }
              if (response.data.delivery.delivery_same_day == 1) {
                this.CreateOilOrderForm.basicInfo.same_day = true
              }

              if (response.data.delivery.payment_type == 0) {
                this.CreateOilOrderForm.basicInfo.card = false
                this.CreateOilOrderForm.basicInfo.cash = true
              }
              if (response.data.delivery.payment_type == 1) {
                this.CreateOilOrderForm.basicInfo.card = true
                this.CreateOilOrderForm.basicInfo.cash = false
              }
              if (response.data.delivery.payment_type == 2) {
                this.CreateOilOrderForm.basicInfo.card = true
                this.CreateOilOrderForm.basicInfo.cash = true
              }
            }
          })
    },
    getDeliveryForm(delivery_id: any) {
      let path = import.meta.env.VITE_BASE_URL + "/delivery/order/" + delivery_id;
      axios({
        method: "get",
        url: path,
        withCredentials: true,
        headers: authHeader(),
      })
          .then((response: any) => {
            if (response.data) {
              this.deliveryOrder = response.data
              this.getCustomer(this.deliveryOrder.customer_id)
            }
          })
    },
    getCustomer(user_id: any) {
      let path = import.meta.env.VITE_BASE_URL + "/customer/" + user_id;
      axios({
        method: "get",
        url: path,
        withCredentials: true,
      })
          .then((response: any) => {
            this.customer = response.data;
            console.log(this.deliveryOrder.payment_card_id)
            this.getPaymentCards(this.deliveryOrder.customer_id);
            if (this.deliveryOrder.payment_type == 1 ) {
              this.getPaymentCard(this.deliveryOrder.payment_card_id)
            }
             if (this.deliveryOrder.payment_type == 2 ) {
              this.getPaymentCard(this.deliveryOrder.payment_card_id)
            }
          })
          .catch(() => {
            notify({
              title: "Error",
              text: "Could not find customer",
              type: "error",
            });
          });
    },
    getPaymentCard(card_id: any) {
      let path = import.meta.env.VITE_BASE_URL + "/payment/card/" + card_id;
      axios({
        method: "get",
        url: path,
        withCredentials: true,
      })
          .then((response: any) => {
            this.userCard = response.data;
            this.CreateOilOrderForm.basicInfo.userCards = response.data.id
          })
          .catch(() => {
          });
    },
    getPaymentCards(user_id: any) {
      let path = import.meta.env.VITE_BASE_URL + "/payment/cards/"+ user_id;
      axios({
        method: "get",
        url: path,
        withCredentials: true,
      })
          .then((response: any) => {
            this.userCards = response.data;
          })
          .catch(() => {
          });
    },
    editOilOrder(payload: {
      gallons_ordered: string;
      customer_asked_for_fill: boolean;
      prime: boolean;
      same_day: boolean;
      delivery_status: string;
      expected_delivery_date: string;
      dispatcher_notes_taken: string;
      cash: boolean;
      credit: boolean;
      credit_card_id: any;
      driver_employee_id: string,
    }) {
      let path = import.meta.env.VITE_BASE_URL + "/delivery/edit/" + this.deliveryOrder.id;
      axios({
        method: "post",
        url: path,
        data: payload,
        withCredentials: true,
        headers: authHeader(),
      })
          .then((response: any) => {
            if (response.data.ok) {
              this.$router.push({name: "delivery"});
            }
            if (response.data.error) {
              this.$router.push("/");
            }
          })
    },
    getDeliveryStatusList() {
      let path = import.meta.env.VITE_BASE_URL + "/query/deliverystatus";
      axios({
        method: "get",
        url: path,
        withCredentials: true,
      })
          .then((response: any) => {
            this.deliveryStatus = response.data;
          })
          .catch(() => {
          });
    },


    onSubmit() {
      let payload = {
        gallons_ordered: this.CreateOilOrderForm.basicInfo.gallons_ordered,
        customer_asked_for_fill: this.CreateOilOrderForm.basicInfo.customer_asked_for_fill,
        expected_delivery_date: this.CreateOilOrderForm.basicInfo.expected_delivery_date,
        dispatcher_notes_taken: this.CreateOilOrderForm.basicInfo.dispatcher_notes_taken,
        prime: this.CreateOilOrderForm.basicInfo.prime,
        same_day: this.CreateOilOrderForm.basicInfo.same_day,
        delivery_status: this.CreateOilOrderForm.basicInfo.delivery_status,
        driver_employee_id: this.CreateOilOrderForm.basicInfo.driver_driver,
        cash: this.CreateOilOrderForm.basicInfo.cash,
        credit: this.CreateOilOrderForm.basicInfo.card,
        credit_card_id: this.CreateOilOrderForm.basicInfo.userCards,
      };
      this.editOilOrder(payload);
    },


    getDriversList() {
      let path = import.meta.env.VITE_BASE_URL + "/employee/drivers";
      axios({
        method: "get",
        url: path,
        withCredentials: true,
         headers: authHeader(),
      })
          .then((response: any) => {
            this.truckDriversList = response.data;

          })
          .catch(() => {
          });
    },

  },
})
</script>

<style scoped>

</style>