<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>
          <li>
            <router-link :to="{ name: 'customer' }">
              Customers
            </router-link>
          </li>
        </ul>
      </div>


      <div class="grid grid-cols-12 ">
        <div class="col-span-12 bg-neutral ">
          <div class="col-span-12 py-5 ">
            <router-link :to="{ name: 'customerProfile', params: { id: customer['id'] } }"
              class="btn btn-secondary btn-sm">
              View Profile
            </router-link>
          </div>
          <div class="grid grid-cols-12">
            <div class="col-span-12 font-bold flex pb-5 ">{{ customer.account_number }}</div>
            <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">

              {{ customer.customer_address }}
              <div v-if="customer.customer_apt != 'None'">
                {{ customer.customer_apt }}
              </div>

            </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 class="col-span-6 rounded-md p-6 ">
          <div class="grid grid-cols-12">
            <div class="col-span-12 text-[24px] ">
              Create Delivery
            </div>

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

              <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 checkbox-xs"
                  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 == true"
                  class="input input-bordered input-sm 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 input-sm w-full max-w-xs" id="title" type="date" min="2024-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="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">Emergency</label>
                <input v-model="CreateOilOrderForm.basicInfo.emergency" class="checkbox checkbox-xs" 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">Prime</label>
                <input v-model="CreateOilOrderForm.basicInfo.prime" class="checkbox checkbox-xs" 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 checkbox-xs" id="same_day"
                  type="checkbox" />
              </div>


              <div v-if="userCards.length > 0">
                <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 select-sm 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 v-else>
                <div class="col-span-12 md:col-span-4 mb-5 md:mb-0 py-5">
                  No Cards on File!
                  <a @click.prevent="test()" class="cursor-pointer underline hover:text-blue-300">
                    Edit Card
                  </a>
                  <!-- <router-link :to="{ name: 'cardadd', params: { id: customer.id } }">
                    <button class="btn btn-sm bg-blue-700 text-white">Add Credit Card</button>
                  </router-link> -->
                </div>
              </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 select-sm 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-4 mb-5 md:mb-0 gap-10 text-error">
                One or Both must be selected
              </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">Cash</label>
                <input v-model="CreateOilOrderForm.basicInfo.cash" class="checkbox checkbox-xs" id="cash"
                  type="checkbox" />
              </div>
              <div v-if="userCards.length > 0">
                <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.credit" class="checkbox checkbox-xs" id="Credit"
                    type="checkbox" />
                </div>
              </div>
              <div v-if="userCards.length > 0">
                <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">Check </label>
                  <input v-model="CreateOilOrderForm.basicInfo.check" class="checkbox checkbox-xs" id="Check"
                    type="checkbox" />
                </div>
              </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">Other </label>
                <input v-model="CreateOilOrderForm.basicInfo.other" class="checkbox checkbox-xs" id="Other"
                  type="checkbox" />
              </div>
              <div class="flex-1 mb-4">
                <label class="block text-white text-sm font-bold mb-2">Select a Promo</label>
                <select class="select select-bordered select-sm w-full max-w-xs" aria-label="Default select example"
                  id="userCards" v-model="CreateOilOrderForm.basicInfo.promos">
                  <option class="text-white" v-for="(promo, index) in promos" :key="index" :value="promo['id']">
                    {{ promo['name_of_promotion'] }} {{ promo['money_off_delivery'] }}
                  </option>
                </select>
              </div>

              <div class="mb-4">
                <label class="block text-white text-sm font-bold mb-2">Dispatcher Note on Ticket</label>
                <textarea v-model="CreateOilOrderForm.basicInfo.dispatcher_notes_taken" rows="4"
                class="textarea block p-2.5 w-full input-bordered " id="description" type="text" placeholder="Notes on ticket" />
              </div>



              <div class="col-span-12 md:col-span-12 flex mt-5 mb-5">
                <button class="btn-sm btn bg-orange-600 text-white">
                  Create Delivery
                </button>
              </div>
            </form>
          </div>
        </div>


        <div class="col-span-12 xl:col-span-6 p-5">

          <div class="grid grid-cols-12 ">
            <div class="col-span-12  text-2xl">Add a Credit Card</div>

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

                <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">Main Card</label>
                  <input v-model="CreateCardForm.basicInfo.main_card" class="checkbox" id="fill" type="checkbox" />
                </div>

                <div class="mb-4">
                  <label class="block text-white text-sm font-bold mb-2">Name on Card</label>
                  <input v-model="CreateCardForm.basicInfo.card_name"
                    class="input input-bordered input-sm w-full max-w-xs" id="title" type="text"
                    placeholder="Name on Card" />
                  <span v-if="v$.CreateCardForm.basicInfo.card_name.$error" class="text-red-600 text-center">
                    {{ v$.CreateCardForm.basicInfo.card_name.$errors[0].$message }}
                  </span>
                </div>

                <div class="mb-4">
                  <label class="block text-white text-sm font-bold mb-2">Card Number</label>
                  <input v-model="CreateCardForm.basicInfo.card_number"
                    class="input input-bordered input-sm w-full max-w-xs" id="title" type="text"
                    placeholder="Card Number" />
                  <span v-if="v$.CreateCardForm.basicInfo.card_number.$error" class="text-red-600 text-center">
                    {{ v$.CreateCardForm.basicInfo.card_number.$errors[0].$message }}
                  </span>
                </div>

                <div class="mb-4">
                  <label class="block text-white text-sm font-bold mb-2">Expiration Month</label>
                  <select v-model="CreateCardForm.basicInfo.expiration_month"
                    class="input input-bordered input-sm w-full max-w-xs" id="Month">
                    <option>01</option>
                    <option>02</option>
                    <option>03</option>
                    <option>04</option>
                    <option>05</option>
                    <option>06</option>
                    <option>07</option>
                    <option>08</option>
                    <option>09</option>
                    <option>10</option>
                    <option>11</option>
                    <option>12</option>
                  </select>
                </div>

                <div class="mb-4">
                  <label class="block text-white text-sm font-bold mb-2">Expiration Year</label>
                  <select v-model="CreateCardForm.basicInfo.expiration_year"
                    class="input input-bordered input-sm w-full max-w-xs" id="Month">
                    <option>2024</option>
                    <option>2025</option>
                    <option>2026</option>
                    <option>2027</option>
                    <option>2028</option>
                    <option>2029</option>
                    <option>2030</option>
                  </select>

                  <span v-if="v$.CreateCardForm.basicInfo.expiration_year.$error" class="text-red-600 text-center">
                    {{ v$.CreateCardForm.basicInfo.expiration_year.$errors[0].$message }}
                  </span>
                </div>

                <div class="mb-4">
                  <label class="block text-white text-sm font-bold mb-2">Type of Card</label>
                  <select v-model="CreateCardForm.basicInfo.type_of_card"
                    class="input input-bordered input-sm w-full max-w-xs" id="Month">
                    <option>Visa</option>
                    <option>MasterCard</option>
                    <option>Discover</option>
                    <option>American Express</option>
                  </select>

                  <span v-if="v$.CreateCardForm.basicInfo.type_of_card.$error" class="text-red-600 text-center">
                    {{ v$.CreateCardForm.basicInfo.type_of_card.$errors[0].$message }}
                  </span>
                </div>

                <div class="mb-4">
                  <label class="block text-white text-sm font-bold mb-2">Security Number</label>
                  <input v-model="CreateCardForm.basicInfo.security_number"
                    class="input input-bordered input-sm w-full max-w-xs" id="title" type="text"
                    placeholder="Back of card" />
                  <span v-if="v$.CreateCardForm.basicInfo.security_number.$error" class="text-red-600 text-center">
                    {{ v$.CreateCardForm.basicInfo.security_number.$errors[0].$message }}
                  </span>
                </div>

                <div class="mb-4">
                  <label class="block text-white text-sm font-bold mb-2">Zip Code</label>
                  <input v-model="CreateCardForm.basicInfo.zip_code"
                    class="input input-bordered input-sm w-full max-w-xs" id="title" type="text"
                    placeholder="Zip Code" />
                </div>



                <div class="col-span-12 md:col-span-12 flex mt-5 mb-5">
                  <button class="btn-sm btn bg-orange-600 text-white">
                    Save Credit Card
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>

      </div>
      <div class="grid grid-cols-12 ">
        <div class="col-span-12 text-center font-bold text-3xl">Remind customer of tank Inspection</div>
        <div class="col-span-12 text-center font-bold text-3xl">Ask how they heard about us</div>
      </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 { notify } from "@kyvg/vue3-notification"
import { minLength, required } from "@vuelidate/validators";

export default defineComponent({
  name: 'deliveryCreate',

  components: {
    Header,
    SideBar,
    Footer,
  },

  data() {
    return {
      v$: useValidate(),
      user: null,
      checked: false,
      userCards: [],
      promos: [],
      truckDriversList: [],
      CreateOilOrderForm: {
        basicInfo: {
          gallons_ordered: '',
          customer_asked_for_fill: false,
          expected_delivery_date: '',
          dispatcher_notes_taken: '',
          prime: false,
          emergency: false,
          userCards: [],
          promos: [],
          same_day: false,
          credit: false,
          cash: false,
          check: false,
          other: false,
          credit_card_id: 0,
          promo_id: 0,
          driver_driver: '',
        },
      },
      CreateCardForm: {
        basicInfo: {
          card_name: '',
          expiration_month: '',
          expiration_year: '',
          type_of_card: '',
          security_number: '',
          card_number: '',
          zip_code: '',
          main_card: false,
        },
      },
      deliveries: [],
      customer: {
        id: 0,
        customer_last_name: '',
        customer_first_name: '',
        customer_town: '',
        customer_state: 0,
        customer_zip: '',
        customer_first_call: '',
        customer_email: '',
        customer_automatic: '',
        customer_phone_number: '',
        customer_home_type: 0,
        customer_apt: '',
        customer_address: '',
        account_number: '',
      },
    }
  },
  validations() {
    return {
      CreateCardForm: {
        basicInfo: {
          card_name: { required, minLength: minLength(1) },
          expiration_month: { required, minLength: minLength(1) },
          expiration_year: { required, minLength: minLength(1) },
          security_number: { required, minLength: minLength(1) },
          type_of_card: { required, minLength: minLength(1) },
          card_number: { required, minLength: minLength(1) },
        },
      },

      CreateOilOrderForm: {
        basicInfo: {
          gallons_ordered: { required, minLength: minLength(1) },
          expected_delivery_date: { required },
        },
      },
    };
  },
  created() {
    this.userStatus()
    this.getDriversList()
    this.getPromos()
  },
  watch: {
    $route() {
      this.getCustomer(this.$route.params.id);
      this.getPaymentCards(this.$route.params.id);
      this.getCustomerDelivery(this.$route.params.id)
    },
  },
  mounted() {
    this.getCustomer(this.$route.params.id)

    this.getPaymentCards(this.$route.params.id);
    this.getCustomerDelivery(this.$route.params.id)
  },
  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
        })
    },

    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;

        })
        .catch(() => {
          notify({
            title: "Error",
            text: "Could not find customer",
            type: "error",
          });
        });
    },
    test() {
      this.CreateOilOrderForm.basicInfo.gallons_ordered = '100'
    },
    getCustomerDelivery(userid: any) {
      let path = import.meta.env.VITE_BASE_URL + '/delivery/customer/' + userid + '/1';
      axios({
        method: 'get',
        url: path,
        headers: authHeader(),
      }).then((response: any) => {
        this.deliveries = response.data
      })
    },

    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(() => {
        });
    },
    getPromos() {
      let path = import.meta.env.VITE_BASE_URL + "/promo/all";
      axios({
        method: "get",
        url: path,
        withCredentials: true,
      })
        .then((response: any) => {
          this.promos = response.data;
        })
        .catch(() => {
        });
    },
    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(() => {
        });
    },
    CreateOilOrder(payload: {
      gallons_ordered: string;
      customer_asked_for_fill: boolean;
      prime: boolean;
      same_day: boolean;
      emergency: boolean;
      cash: boolean;
      credit: boolean;
      check: boolean;
      other: boolean;
      expected_delivery_date: string;
      dispatcher_notes_taken: string;
      credit_card_id: any;
      promo_id: any;
      driver_employee_id: string,

    }) {
      let path = import.meta.env.VITE_BASE_URL + "/delivery/create/" + this.customer.id;
      axios({
        method: "post",
        url: path,
        data: payload,
        withCredentials: true,
        headers: authHeader(),
      })
        .then((response: any) => {
          if (response.data.ok) {
            this.$router.push({ name: "payOil", params: { id: response.data.delivery_id } });
          }
          if (response.data.error) {
            this.$router.push("/");
          }
        })
    },

    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,
        emergency: this.CreateOilOrderForm.basicInfo.emergency,
        same_day: this.CreateOilOrderForm.basicInfo.same_day,
        cash: this.CreateOilOrderForm.basicInfo.cash,
        credit: this.CreateOilOrderForm.basicInfo.credit,
        check: this.CreateOilOrderForm.basicInfo.check,
        other: this.CreateOilOrderForm.basicInfo.other,
        credit_card_id: this.CreateOilOrderForm.basicInfo.userCards,
        promo_id: this.CreateOilOrderForm.basicInfo.promos,
        driver_employee_id: this.CreateOilOrderForm.basicInfo.driver_driver,
      };
      let pass = 0;
      if (this.CreateOilOrderForm.basicInfo.driver_driver === '') {
        notify({
          title: "Error",
          text: "Did not add a driver",
          type: "error",
        });
        pass += 1;
      }
      if (this.CreateOilOrderForm.basicInfo.cash === false && this.CreateOilOrderForm.basicInfo.credit === false && this.CreateOilOrderForm.basicInfo.check === false && this.CreateOilOrderForm.basicInfo.other === false) {
        notify({
          title: "Error",
          text: "Did not select a payment method",
          type: "error",
        });
        pass += 1;
      }
      if (pass == 0) {
        this.CreateOilOrder(payload);
      }
    },



    CreateCard(payload: {
      card_name: string;
      expiration_month: string;
      expiration_year: string;
      type_of_card: string;
      security_number: string;
      zip_code: string;
      card_number: string;
      main_card: boolean;
    }) {
      let path = import.meta.env.VITE_BASE_URL + "/payment/card/create/" + this.customer.id;
      axios({
        method: "post",
        url: path,
        data: payload,
        withCredentials: true,
        headers: authHeader(),
      })
        .then((response: any) => {
          if (response.data.ok) {
            this.getPaymentCards(this.$route.params.id)
          }
          if (response.data.error) {
            notify({
              title: "Error",
              text: "Error adding card",
              type: "error",
            });
          }
        })
    },
    onSubmitCard() {
      let payload = {
        card_name: this.CreateCardForm.basicInfo.card_name,
        card_number: this.CreateCardForm.basicInfo.card_number,
        expiration_month: this.CreateCardForm.basicInfo.expiration_month,
        expiration_year: this.CreateCardForm.basicInfo.expiration_year,
        type_of_card: this.CreateCardForm.basicInfo.type_of_card,
        security_number: this.CreateCardForm.basicInfo.security_number,
        main_card: this.CreateCardForm.basicInfo.main_card,
        zip_code: this.CreateCardForm.basicInfo.zip_code,
      };
      this.CreateCard(payload);
    },
  },
})
</script>

<style scoped></style>