<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 class="w-full mt-10">

          <div class="grid grid-cols-12 gap-5">
            <div class="col-span-4 p-5 ">
              <img src="../../../assets/images/user_placeholder.png" alt="Drone Image" width="200" height="250" />
            </div>
            <div class="col-span-8  p-5">
              <div class="grid grid-cols-12">
                <div class="col-span-12 font-bold flex justify-evenly pb-5">

                  <router-link :to="{ name: 'deliveryCreate', params: { id: customer.id } }"
                    class="btn-sm btn btn-accent">
                    Create Delivery
                  </router-link>

                  <router-link :to="{ name: 'customerEdit', params: { id: customer.id } }"
                    class="btn-sm btn btn-accent">
                    Edit Customer
                  </router-link>
             
                  <div v-if="automatic_status === 0">
                  <button v-on:click="userAutomatic(customer.id)" class="btn btn-accent btn-sm">
                    Become Automatic Customer
                  </button>
                  </div>
                  <div v-else>
                    <button  v-on:click="userAutomatic(customer.id)"  class="btn btn-accent btn-sm">
                      Become Will Call Customer
                    </button>
                  </div>

                </div>
                <div class="col-span-12 font-bold flex pb-5 text-lg" v-if="automatic_status === 1" >Automatic </div>

                <div class="col-span-12 font-bold flex pb-5 text-lg"  v-else>Will Call</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 class="col-span-12 font-bold flex">{{ customer.account_number }}</div>
              </div>
            </div>

            <div class="col-span-12 ">
              <hr class=" h-1 mx-auto my-4 bg-gray-100 border-0 rounded dark:bg-gray-400">
            </div>
            <div class="col-span-6  ">
              <div class="grid grid-cols-12">
                <div class="col-span-12 font-bold flex text-2xl">
                  Description
                </div>    
                <div class="col-span-6">
                  <div class="col-span-12 py-2 font-bold">Home Description</div>
                  <div class="col-span-12 py-2 px-2">
                   {{ customer_description.description }}
                  </div>
                  <div class="col-span-12 py-2 font-bold">Fill Location</div>
                  <div class="col-span-12 py-2 px-2">
                    {{ customer_description.fill_location }}
                  </div>
             
                </div>
              </div>
            </div>
            
            <div class="col-span-6  ">
              <div class="grid grid-cols-12">
                <div class="col-span-12 font-bold flex text-2xl">
                  Stats
                </div>
                <div class="col-span-6">
                  <div class="col-span-12 py-2 px-2">
                    Total Calls: {{ customer_stats.total_calls }}
                  </div>
                  <div class="col-span-12 py-2  font-bold">Delivery</div>
                  <div class="col-span-12 py-2 px-2">
                    Total Delivery Orders: {{ customer_stats.oil_deliveries }}
                  </div>
                  <div class="col-span-12 py-2 px-2">
                    Total Gallons: {{ customer_stats.oil_total_gallons }}
                  </div>
                  <div class="col-span-12 py-2 px-2">
                    Last Delivery: {{ customer_last_delivery }}
                  </div>
                </div>
              </div>
            </div>

            <div class="col-span-12 ">
              <hr class=" h-1 mx-auto my-4 bg-gray-100 border-0 rounded  dark:bg-gray-400">
            </div>

            <div class="col-span-12  p-5">
              <div class="grid grid-cols-12">
                <div class="col-span-6 font-bold flex text-2xl">
                  Credit Cards
                </div>
                <div class="col-span-6 font-bold flex ">

                  <router-link :to="{ name: 'cardadd', params: { id: customer.user_id } }">
                    <button class="btn btn-sm btn-accent">Add Credit Card</button>
                  </router-link>
                </div>
                <div class="col-span-12 font-bold flex">
                  <div class="text-red-600" v-if="credit_cards_count == 0">
                    No Cards on File! Cash Customer till card added.
                  </div>
                  <div v-else>
                    {{ credit_cards_count }} credit card(s) on file.
                  </div>
                </div>
                <div v-for="card in credit_cards" class="col-span-12">

                  <div class="flex flex-row ">
                    <div v-if="card.main_card" class="basis-1/3 p-2">
                      <div class="bg-accent rounded-md border-2 ">
                        <div class="flex p-3">
                          {{ card.type_of_card }}
                        </div>
                        <div class="flex p-1 pl-4">
                          {{ card.name_on_card }}
                        </div>
                        <div class="flex p-1 pl-4">
                         {{ card.card_number }}
                        </div>
                        <div class="flex p-1 pl-4">
                          {{ card.expiration_month }}/ {{ card.expiration_year }}
                        </div>
                        <div class="flex p-1 pl-4">
                          {{ card.zip_code }}
                        </div>
                        <div class="flex justify-between">

                          <a @click.prevent="editCard(card.id)" class="cursor-pointer underline hover:text-blue-300">
                            Edit Card
                          </a>
                          <a @click.prevent="removeCard(card.id)" class="cursor-pointer underline hover:text-blue-300">
                            RemoveCard
                          </a>
                        </div>
                      </div>
                    </div>
                    <div v-else class="basis-1/3 p-2">
                      <div class="rounded-md border-2 ">
                        <div class="flex p-3">
                          {{ card.type_of_card }}
                        </div>
                        <div class="flex p-1 pl-4">
                          {{ card.name_on_card }}
                        </div>
                        <div class="flex p-1 pl-4">
                          {{ card.card_number }}
                        </div>
                        <div class="flex p-1 pl-4">
                          {{ card.expiration_month }}/ {{ card.expiration_year }}
                        </div>
                        <div class="flex p-1 pl-4">
                          {{ card.zip_code }}
                        </div>
                        <div class="flex justify-between">
                          <a @click.prevent="editCard(card.id)"
                            class="cursor-pointer underline hover:text-blue-300">Edit
                            Card</a>
                          <a @click.prevent="removeCard(card.id)"
                            class="cursor-pointer underline hover:text-blue-300">Remove
                            Card</a>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- <div class="col-span-12 p-5">
              <div class="grid grid-cols-12">
                <div class="col-span-6 font-bold flex text-2xl">
                  Financial
                </div>
              </div>
            </div> -->

            <div class="col-span-12  p-5">
              <div class="grid grid-cols-12">
                <div class="col-span-12 font-bold flex text-2xl">Orders</div>
              </div>
              <div class="grid grid-cols-12 bg-neutral">

                <table class="table col-span-12">
                  <!-- head -->
                  <thead>
                    <tr>
                      <th>id</th>
                      <th>Status</th>
                      <th>Town</th>
                      <th>Name</th>
                      <th>Address</th>
                      <th>Gallons</th>
                      <th>Date</th>
                      <th>Automatic</th>
                      <th>Prime</th>
                      <th>Same Day</th>
                      <th></th>
                    </tr>
                  </thead>
                  <tbody>
                    <!-- row 1 -->
                    <tr v-for="oil in deliveries" :key="oil['id']">
                      <td>{{ oil['id'] }}</td>
                      <td>
                        <div v-if="oil['delivery_status'] == 0">Waiting</div>
                        <div v-else-if="oil['delivery_status'] == 1">delivered</div>
                        <div v-else-if="oil['delivery_status'] == 2">Out for Delivery</div>
                        <div v-else-if="oil['delivery_status'] == 3">Cancelled</div>
                        <div v-else-if="oil['delivery_status'] == 4">Partial Delivery</div>
                        <div v-else-if="oil['delivery_status'] == 5">Issue</div>
                        <div v-else-if="oil['delivery_status'] == 10">Finalized</div>
                        <div v-else></div>
                      </td>
                      <td>{{ oil['customer_town'] }}</td>
                      <td>{{ oil['customer_name'] }}</td>
                      <td>{{ oil['customer_address'] }}</td>
                      <td>
                        <div v-if="oil['customer_asked_for_fill'] == 1">Fill</div>
                        <div v-else> {{ oil['gallons_ordered'] }}</div>
                      </td>
                      <td>{{ oil['expected_delivery_date'] }}</td>
                      <td>
                        <div v-if="oil['automatic'] == 0">No</div>
                        <div v-else>Yes</div>
                      </td>
                      <td>
                        <div v-if="oil['prime'] == 0">No</div>
                        <div v-else>Yes</div>
                      </td>
                      <td>
                        <div v-if="oil['same_day'] == 0">No</div>
                        <div v-else>Yes</div>
                      </td>
                      <td class="flex gap-5 ">
                        <router-link :to="{ name: 'deliveryOrder', params: { id: oil['id'] } }">
                  <button class="btn btn-accent btn-sm">View</button>
                </router-link>
                        <router-link  :to="{ name: 'Ticket', params: { id: oil['id'] } }">
                          <button class="btn btn-accent btn-sm">Print</button>
                        </router-link>

                        <router-link :to="{ name: 'deliveryEdit', params: { id: oil['id'] } }">
                          <button class="btn btn-sm btn-accent">Edit</button>
                        </router-link>
                        
                        <router-link :to="{ name: 'finalizeTicket', params: { id: oil['id'] } }" v-if="oil['delivery_status'] != 10">
                        <button class="btn btn-sm btn-success">Finalize</button>
                        </router-link>
<!-- 
                        <a @click.prevent="deleteCall(oil['id'])">
                          <button class="btn btn-sm btn-error">Delete</button>
                        </a> -->
                     
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </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 PaginationComp from "../../../components/pagination.vue";
import { notify } from "@kyvg/vue3-notification";

export default defineComponent({
  name: 'CustomerProfile',

  components: {
    Header,
    SideBar,
    Footer,
  },

  data() {
    return {
      token: null,
      user: null,
      isTrue: true,
      automatic_status: 0,
      automatic_response: 0,
      customer_last_delivery: '',
      credit_cards: [
        {
          id: 0,
          name_on_card: '',
          main_card: false,
          card_number: '',
          expiration_month: '',
          type_of_card: '',
          last_four_digits: '',
          expiration_year: '',
          zip_code: '',

        }
      ],
      credit_cards_count: 0,
      customer: {
        id: 0,
        user_id: 0,
        customer_first_name: '',
        customer_last_name: '',
        customer_town: '',
        customer_address: '',
        customer_state: 0,
        customer_zip: '',
        customer_apt: '',
        customer_home_type: 0,
        customer_phone_number: '',
        account_number: '',
      },
      customer_description: {
        id: 0,
        customer_id: 0,
        account_number: '',
        company_id: '',
        fill_location: 0,
        description: '',
      },
      customer_stats: {
        id: 0,
        customer_id: 0,
        total_calls: 0,
        service_calls_total: 0,
        service_calls_total_spent: 0,
        service_calls_total_profit: 0,

        oil_deliveries: 0,
        oil_total_gallons: 0,
        oil_total_spent: 0,
        oil_total_profit: 0,

      },
      deliveries: [],
      delivery_page: 1,
      delivery_perPage: 50,
      delivery_recordsLength: 0,
      delivery_options: {
        delivery_edgeNavigation: false,
        delivery_format: false,
        delivery_template: PaginationComp
      },

    }
  },
  created() {
    this.userStatus()
    this.getCustomer(this.$route.params.id);
    this.getCreditCards(this.$route.params.id)
    this.getCreditCardsCount(this.$route.params.id)
  },
  mounted() {
    this.getPage(this.delivery_page)
  },

  watch: {
    $route() {
      this.getCustomer(this.$route.params.id);
    },
  },
  methods: {
    getPage: function (page: any) {
      // we simulate an api call that fetch the records from a backend
      this.getCustomerDelivery(this.$route.params.id, page)
    },
    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
        })
    },
  
    userAutomaticStatus(userid: any) {
      let path = import.meta.env.VITE_BASE_URL + '/customer/automatic/status/' + userid;
      axios({
        method: 'get',
        url: path,
        headers: authHeader(),
      }).then((response: any) => {
        this.automatic_status = response.data.status
       
      })
    },


    userAutomatic(userid: any) {
      let path = import.meta.env.VITE_BASE_URL + '/customer/automatic/assign/' + userid;
      axios({
        method: 'get',
        url: path,
        headers: authHeader(),
      }).then((response: any) => {
        this.automatic_response = response.data.status

        if (this.automatic_response == 1) {
          this.$notify({
            title: "Automatic Status",
            text: 'Customer is now Automatic Customer',
            type: 'Success'
          });
        } else if (this.automatic_response == 2) {
          this.$notify({
            title: "Automatic Status",
            text: 'Customer does not have a main credit card.  Can not make automatic.',
            type: 'Error'
          });
        } else if (this.automatic_response == 3) {
          this.$notify({
            title: "Automatic Status",
            text: 'Customer is now a Call in ',
            type: 'Info'  // Adjust type if needed
          });
        } else {
          this.$notify({
            title: "Automatic Status",
            text: 'Customer is now Manual Customer',
            type: 'Warning'  // Adjust type if needed
          });
        }
      
        this.getCustomer(this.$route.params.id);
        this.getCreditCards(this.$route.params.id)
        this.getCreditCardsCount(this.$route.params.id)
      })
    },

    getCustomer(userid: any) {
      let path = import.meta.env.VITE_BASE_URL + '/customer/' + userid;
      axios({
        method: 'get',
        url: path,
        headers: authHeader(),
      }).then((response: any) => {

        this.customer = response.data
        this.userAutomaticStatus(this.customer.id);
        this.getCustomerDescription(this.customer.id);
        this.getCustomerStats(this.customer.id);
        this.getCustomerLastDelivery(this.customer.id);
      })
    },
    getCustomerLastDelivery(userid: any) {
      let path = import.meta.env.VITE_BASE_URL + '/stats/user/lastdelivery/' + userid;
      axios({
        method: 'get',
        url: path,
        headers: authHeader(),
      }).then((response: any) => {
        
        this.customer_last_delivery = response.data.date
        console.log(response.data)
      })
    },
    getCustomerStats(userid: any) {
      let path = import.meta.env.VITE_BASE_URL + '/stats/user/' + userid;
      axios({
        method: 'get',
        url: path,
        headers: authHeader(),
      }).then((response: any) => {
        this.customer_stats = response.data

      })
    },
    getCustomerDescription(userid: any) {
      let path = import.meta.env.VITE_BASE_URL + '/customer/description/' + userid;
      axios({
        method: 'get',
        url: path,
        headers: authHeader(),
      }).then((response: any) => {

        this.customer_description = response.data
      })
    },


    getCreditCards(user_id: any) {
      let path = import.meta.env.VITE_BASE_URL + '/payment/cards/' + user_id;
      axios({
        method: 'get',
        url: path,
        headers: authHeader(),
      }).then((response: any) => {

        this.credit_cards = response.data
      })
    },

    getCreditCardsCount(user_id: any) {
      let path = import.meta.env.VITE_BASE_URL + '/payment/cards/onfile/' + user_id;
      axios({
        method: 'get',
        url: path,
        headers: authHeader(),
      }).then((response: any) => {

        this.credit_cards_count = response.data.cards
      })
    },

    getCustomerDelivery(userid: any, delivery_page: any) {
      let path = import.meta.env.VITE_BASE_URL + '/delivery/customer/' + userid + '/' + delivery_page;
      axios({
        method: 'get',
        url: path,
        headers: authHeader(),
      }).then((response: any) => {
        this.deliveries = response.data
      })
    },

    editCard(card_id: any) {
      this.$router.push({ name: "cardedit", params: { id: card_id } });
    },

    removeCard(card_id: any) {
      let path = import.meta.env.VITE_BASE_URL + '/payment/card/remove/' + card_id;
      axios({
        method: 'delete',
        url: path,
        headers: authHeader(),
      }).then(() => {
        this.getCreditCards(this.$route.params.id)
        this.getCreditCardsCount(this.$route.params.id)
        notify({
          title: "Card Status",
          text: "Card Removed",
          type: "Success",
        });
      })
    },

    deleteCall(delivery_id: any) {
      let path = import.meta.env.VITE_BASE_URL + '/delivery/delete/' + delivery_id;
      axios({
        method: 'delete',
        url: path,
        headers: authHeader(),
      }).then((response: any) => {
        if (response.data.ok) {
          notify({
            title: "Success",
            text: "deleted oil order",
            type: "success",
          });
          this.getPage(1)
        } else {
          notify({
            title: "Failure",
            text: "error deleting oil order",
            type: "success",
          });
        }
      })
    },
  },
})
</script>

<style scoped></style>