<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-6 p-5  ">
              <div class="grid grid-cols-12 gap-5">
                <div class="col-span-12 font-bold text-3xl ">
                  {{ customer.account_number }}
                </div>
                <div class="col-span-12 font-bold ">
                  <div style="height:400px; width:100%">
                    <l-map ref="map" v-model:zoom="zoom"
                      :center="[customer.customer_latitude, customer.customer_longitude]">
                      <l-tile-layer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" layer-type="base"
                        name="OpenStreetMap"></l-tile-layer>
                    </l-map>
                  </div>
                </div>
              </div>
            </div>
            <div class="col-span-6  p-5">
              <div class="grid grid-cols-12 ">
                <div class="col-span-12 font-bold flex justify-evenly pb-5 flex-wrap gap-2">

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


                  <router-link :to="{ name: 'CalenderCustomer', params: { id: customer.id } }"
                    class="btn-sm btn bg-indigo-600 text-white">
                    Create Service Call
                  </router-link>



                  <router-link :to="{ name: 'customerEdit', params: { id: customer.id } }"
                    class="btn-sm btn btn-secondary">
                    Edit Customer
                  </router-link>

                  <div v-if="automatic_status === 0">
                    <button v-on:click="userAutomatic(customer.id)" class="btn-sm btn btn-secondary">
                      Become Auto
                    </button>
                  </div>
                  <div v-else>
                    <button v-on:click="userAutomatic(customer.id)" class="btn bg-green-600 text-black  btn-sm">
                      Become Will Call
                    </button>
                  </div>
                </div>
                <div class="col-span-12">
                  <div class="grid grid-cols-12">
                    <div class="col-span-6">
                      <div class="col-span-12 font-bold flex pb-5 text-lg text-red-600"
                        v-if="customer.correct_address === false">
                        Possible Incorrect Address!!
                      </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="text-green-600" v-if="automatic_status === 1">
                        <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>

                        <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 !== ''">
                          {{ 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 class="" v-else>
                        <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>

                        <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 !== ''">
                          {{ 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">
                     
                      <div class="col-span-12 py-2 px-2 text-orange-600 "
                        v-if="customer_tank.outside_or_inside == false">
                        <div v-if="customer_tank.last_tank_inspection !== null">
                        OUTSIDE TANK - {{ customer_tank.tank_size }}
                      </div>
                      </div>
                      <div class="col-span-12 py-2 px-2" v-if="customer_tank.outside_or_inside == true">
                        {{ customer_tank.tank_size }}
                      </div>

                      <div class="col-span-12  font-bold">Home Description</div>
                      <div class="col-span-12 py-2 px-2">
                        {{ customer_description.description }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div class="col-span-6">
              <div class="col-span-12">
                <hr class=" h-1 mx-auto my-4 bg-gray-800 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">
                    Stats
                  </div>
                  <div class="col-span-6">
                    <div class="col-span-12 py-2 px-2">
                      Total Calls: {{ customer_stats.total_calls }}
                    </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">

                  </div>
                  <div class="col-span-6">

                    <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-800 border-0 rounded dark:bg-gray-400">
              </div>

              <div class="col-span-6  ">
                <div class="grid grid-cols-12">
                  <div class="col-span-6 font-bold flex text-2xl">
                    Tank
                  </div>
                  <div class="col-span-6 font-bold flex text-2xl">
                    <router-link :to="{ name: 'TankEdit', params: { id: customer.id } }"
                      class="btn-sm btn btn-secondary">
                      Edit Tank
                    </router-link>
                  </div>
                  <div class="col-span-6 ">
                    <div class="col-span-12 py-2 font-bold">Last Tank Inspection </div>
                    <div class="col-span-12 py-2 px-2 text-red-600" v-if="customer_tank.last_tank_inspection == null">
                      Not inspected
                    </div>
                    <div class="col-span-12 py-2 px-2" v-else>
                      {{ customer_tank.last_tank_inspection }}
                    </div>

                    <div class="col-span-12 py-2 font-bold">Tank Status</div>
                    <div class="col-span-12 py-2 px-2 text-red-600" v-if="customer_tank.tank_status == false">
                      Needs Inspection / Bad Tank
                    </div>
                    <div class="col-span-12 py-2 px-2" v-else>
                      Inspected
                    </div>

                    <div class="col-span-12 py-2 font-bold">Inside/Outside </div>
                    <div class="col-span-12 py-2 px-2 " v-if="customer_tank.outside_or_inside == true">
                      Inside
                    </div>
                    <div class="col-span-12 py-2 px-2 text-orange-600" v-else>
                      Outside
                    </div>
                  </div>

                  <div class="col-span-6  ">
                    <div class="grid grid-cols-12">
                      <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 class="col-span-12 py-2  font-bold">Tank Size</div>
                      <div class="col-span-12 py-2 px-2">
                        {{ customer_tank.tank_size }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <div class="col-span-12 ">
                <hr class=" h-1 mx-auto my-4 bg-gray-800 border-0 rounded  dark:bg-gray-400">
                             <div class="col-span-12 ">
                <div class="grid grid-cols-12">
                    <div class="col-span-6 font-bold flex text-2xl">
                      Equipment Parts
                    </div>
                    <div class="col-span-6 font-bold flex justify-start">
                        <button @click="openPartsModal" class="btn-sm btn btn-secondary">Edit Parts</button>
                    </div>
                    
                    <div v-if="currentParts" class="col-span-12 mt-4">
                        <div v-if="hasPartsData" class="grid grid-cols-12 gap-4">
                            
                            <div v-if="currentParts.oil_filter" class="col-span-6">
                                <div class="font-bold">Oil Filter 1:</div>
                                <div>{{ currentParts.oil_filter }}</div>
                            </div>

                            <div v-if="currentParts.oil_filter_2" class="col-span-6">
                                <div class="font-bold">Oil Filter 2:</div>
                                <div>{{ currentParts.oil_filter_2 }}</div>
                            </div>
                            
                            <div v-if="currentParts.oil_nozzle" class="col-span-6">
                                <div class="font-bold">Oil Nozzle 1:</div>
                                <div :style="{ color: getNozzleColor(currentParts.oil_nozzle), fontWeight: 'bold' }">{{ currentParts.oil_nozzle }}</div>
                            </div>
                            
                            <div v-if="currentParts.oil_nozzle_2" class="col-span-6">
                                <div class="font-bold">Oil Nozzle 2:</div>
                                <div :style="{ color: getNozzleColor(currentParts.oil_nozzle_2), fontWeight: 'bold' }">{{ currentParts.oil_nozzle_2 }}</div>
                            </div>

                        </div>
                         <div v-else>
                            <p>No equipment parts information available.</p>
                        </div>
                    </div>
                </div>
                </div>
              </div>
              <div class="col-span-12 ">
                <hr class=" h-1 mx-auto my-4 bg-gray-800 border-0 rounded  dark:bg-gray-400">
              </div>
              <div class="col-span-12 ">
                <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 bg-gray-700 text-white">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" :key="card.id" class="col-span-12 ">
                    <div class="flex flex-row ">
                      <div v-if="card.main_card" class="basis-1/2 p-2 ">
                        <div class="bg-neutral 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">
                            <div v-if="card.expiration_month < 10">0{{ card.expiration_month }}</div>
                            <div v-else>{{ card.expiration_month }}</div>
                            <div class=" pl-1 pr-1">/ </div>
                            <div class=""> {{ card.expiration_year }} </div>
                          </div>
                          <div class="flex p-1 pl-4">
                            {{ card.zip_code }}
                          </div>
                          <div class="flex p-1 pl-4">
                            {{ card.security_number }}
                          </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/2 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">
                             <div v-if="card.expiration_month < 10">0{{ card.expiration_month }}</div>
                            <div v-else>{{ card.expiration_month }}</div>
                            <div class=" pl-1 pr-1">/ </div>
                            <div class=""> {{ card.expiration_year }} </div>
                          </div>
                          <div class="flex p-1 pl-4">
                            {{ card.zip_code }}
                          </div>
                          <div class="flex p-1 pl-4">
                            {{ card.security_number }}
                          </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>

            <div class="col-span-6 px-4">
              <div class="grid grid-cols-12">
                <form class="rounded-md  col-span-12" enctype="multipart/form-data" @submit.prevent="onSubmitSocial">
                  <div class="mb-4">
                    <label class="block text-white text-sm font-bold mb-2">Customer Comment</label>
                    <textarea v-model="CreateSocialForm.basicInfo.comment" rows="4"
                      class="textarea block p-2.5 w-full input-bordered " id="description" type="text"
                      placeholder="Leave a Customer Comment" />
                  </div>
                  <div class="col-span-12 md:col-span-12 flex mt-5 mb-5">
                    <button class="btn btn-sm btn-secondary">
                      Create Comment
                    </button>
                  </div>
                </form>

                <div class="col-span-12">
                  <div v-for="comment in comments" :key="comment['id']">
                    <div class="grid grid-cols-12 bg-neutral my-5">
                      <div class="col-span-2">
                        {{ comment.created }}
                      </div>
                      <div class="col-span-8">
                      </div>
                      <div class="col-span-1">
                      </div>
                      <div class="col-span-1">
                        <a href="" @click.prevent="deleteCustomerSocial(comment.id)" class="hover:text-blue-300">
                          Delete
                        </a>
                      </div>
                      <div class="col-span-12 p-5">
                        {{ comment.comment }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div class="col-span-12 ">
              <hr class=" h-1 mx-auto my-4 bg-gray-800 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-12 font-bold flex text-2xl mb-5">
                  Service Call History
                </div>
              </div>
              <div v-if="!serviceCalls || serviceCalls.length === 0" class="text-center p-10 bg-base-200 rounded-md">
                <p>No service call history found for this customer.</p>
              </div>
              <div v-else class="overflow-x-auto rounded-lg">
                <table class="min-w-full divide-y divide-gray-700">
                  <thead class="bg-base-200">
                    <tr>
                      <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-base-content uppercase tracking-wider">Date</th>
                      <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-base-content uppercase tracking-wider">Time</th>
                      <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-base-content uppercase tracking-wider">Service Type</th>
                      <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-base-content uppercase tracking-wider">Description</th>
                    </tr>
                  </thead>
                  <tbody class="bg-base-100 divide-y divide-gray-700">
                    <tr v-for="service in serviceCalls" :key="service.id" @click="openEditModal(service)" class="hover:bg-base-300 cursor-pointer">
                      <td class="px-6 py-4 whitespace-nowrap">{{ formatDate(service.scheduled_date) }}</td>
                      <td class="px-6 py-4 whitespace-nowrap">{{ formatTime(service.scheduled_date) }}</td>
                      <td class="px-6 py-4 whitespace-nowrap font-medium" :style="{ color: getServiceTypeColor(service.type_service_call) }">
                        {{ getServiceTypeName(service.type_service_call) }}
                      </td>
                      <td class="px-6 py-4 whitespace-normal text-sm">{{ service.description }}</td>
                    </tr>
                  </tbody>
                </table>
              </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 mb-5">Automatic Deliveries</div>
              </div>
              <div v-if="!autodeliveries || autodeliveries.length === 0" class="text-center p-10 bg-base-200 rounded-md">
                <p>No automatic delivery history found.</p>
              </div>
              <div v-else class="overflow-x-auto rounded-lg">
                <table class="min-w-full divide-y divide-gray-700">
                  <thead class="bg-base-200">
                    <tr>
                      <th class="px-6 py-3 text-left text-xs font-medium text-base-content uppercase tracking-wider">id</th>
                      <th class="px-6 py-3 text-left text-xs font-medium text-base-content uppercase tracking-wider">Name</th>
                      <th class="px-6 py-3 text-left text-xs font-medium text-base-content uppercase tracking-wider">Address</th>
                      <th class="px-6 py-3 text-left text-xs font-medium text-base-content uppercase tracking-wider">Town</th>
                      <th class="px-6 py-3 text-left text-xs font-medium text-base-content uppercase tracking-wider">Gallons</th>
                      <th class="px-6 py-3 text-left text-xs font-medium text-base-content uppercase tracking-wider">Date</th>
                    </tr>
                  </thead>
                  <tbody class="bg-base-100 divide-y divide-gray-700">
                    <tr v-for="auto in autodeliveries" :key="auto['id']" class="hover:bg-base-300">
                      <td class="px-6 py-4 whitespace-nowrap">{{ auto['id'] }}</td>
                      <td class="px-6 py-4 whitespace-nowrap">{{ auto['customer_full_name'] }}</td>
                      <td class="px-6 py-4 whitespace-nowrap">{{ auto['customer_address'] }}</td>
                      <td class="px-6 py-4 whitespace-nowrap">{{ auto['customer_town'] }}</td>
                      <td class="px-6 py-4 whitespace-nowrap">{{ auto['gallons_delivered'] }}</td>
                      <td class="px-6 py-4 whitespace-nowrap">{{ auto['fill_date'] }}</td>
                    </tr>
                  </tbody>
                </table>
              </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 mb-5">Orders</div>
              </div>
              <div v-if="!deliveries || deliveries.length === 0" class="text-center p-10 bg-base-200 rounded-md">
                <p>No order history found.</p>
              </div>
              <div v-else class="overflow-x-auto rounded-lg">
                <table class="min-w-full divide-y divide-gray-700">
                  <thead class="bg-base-200">
                    <tr>
                      <th class="px-6 py-3 text-left text-xs font-medium text-base-content uppercase tracking-wider">id</th>
                      <th class="px-6 py-3 text-left text-xs font-medium text-base-content uppercase tracking-wider">Status</th>
                      <th class="px-6 py-3 text-left text-xs font-medium text-base-content uppercase tracking-wider">Name</th>
                      <th class="px-6 py-3 text-left text-xs font-medium text-base-content uppercase tracking-wider">Address</th>
                      <th class="px-6 py-3 text-left text-xs font-medium text-base-content uppercase tracking-wider">Town</th>
                      <th class="px-6 py-3 text-left text-xs font-medium text-base-content uppercase tracking-wider">Gallons</th>
                      <th class="px-6 py-3 text-left text-xs font-medium text-base-content uppercase tracking-wider">Date</th>
                      <th class="px-6 py-3 text-left text-xs font-medium text-base-content uppercase tracking-wider"></th>
                    </tr>
                  </thead>
                  <tbody class="bg-base-100 divide-y divide-gray-700">
                    <tr v-for="oil in deliveries" :key="oil['id']" class="hover:bg-base-300">
                      <td class="px-6 py-4 whitespace-nowrap">{{ oil['id'] }}</td>
                      <td class="px-6 py-4 whitespace-nowrap">
                        <div v-if="oil['delivery_status'] == 0">Waiting</div>
                        <div v-else-if="oil['delivery_status'] == 1">cancelled</div>
                        <div v-else-if="oil['delivery_status'] == 2">Out for Delivery</div>
                        <div v-else-if="oil['delivery_status'] == 3">Tommorrow</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 class="px-6 py-4 whitespace-nowrap">{{ oil['customer_name'] }}</td>
                      <td class="px-6 py-4 whitespace-nowrap">{{ oil['customer_address'] }}</td>
                      <td class="px-6 py-4 whitespace-nowrap">{{ oil['customer_town'] }}</td>
                      <td class="px-6 py-4 whitespace-nowrap" v-if="oil['delivery_status'] != 10">
                        <div v-if="oil['customer_asked_for_fill'] == 1">Fill</div>
                        <div v-else> {{ oil['gallons_ordered'] }}</div>
                      </td>
                      <td class="px-6 py-4 whitespace-nowrap" v-else>
                        {{ oil['gallons_delivered'] }}
                      </td>
                      <td class="px-6 py-4 whitespace-nowrap">{{ oil['expected_delivery_date'] }}</td>
                      <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                        <div class="flex gap-2">
                          <router-link :to="{ name: 'deliveryOrder', params: { id: oil['id'] } }">
                            <button class="btn btn-secondary btn-sm">View</button>
                          </router-link>
                          <router-link :to="{ name: 'deliveryEdit', params: { id: oil['id'] } }">
                            <button class="btn btn-sm btn-secondary">Edit</button>
                          </router-link>
                          <router-link :to="{ name: 'finalizeTicket', params: { id: oil['id'] } }"
                            v-if="oil['delivery_status'] != 10">
                            <button class="btn btn-secondary btn-sm">Finalize</button>
                          </router-link>
                          <router-link :to="{ name: 'Ticket', params: { id: oil['id'] } }">
                            <button class="btn btn-success btn-sm">Print Ticket</button>
                          </router-link>
                        </div>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <Footer />

  <ServiceEditModal
      v-if="selectedServiceForEdit"
      :service="selectedServiceForEdit"
      @close-modal="closeEditModal"
      @save-changes="handleSaveChanges"
      @delete-service="handleDeleteService"
  />

  <PartsEditModal
      v-if="isPartsModalOpen && currentParts"
      :customer-id="customer.id"
      :existing-parts="currentParts"
      @close-modal="closePartsModal"
      @save-parts="handleSaveParts"
    />
</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";
import "leaflet/dist/leaflet.css";
import L from 'leaflet';
import iconUrl from 'leaflet/dist/images/marker-icon.png';
import shadowUrl from 'leaflet/dist/images/marker-shadow.png';
import { LMap, LTileLayer } from "@vue-leaflet/vue-leaflet";
import dayjs from 'dayjs';
import ServiceEditModal from '../../service/ServiceEditModal.vue';
import PartsEditModal from '../service/PartsEditModal.vue'; 

L.Icon.Default.mergeOptions({
  iconUrl: iconUrl,
  shadowUrl: shadowUrl,
});

interface ServiceCall {
  id: number;
  scheduled_date: string;
  customer_name: string;
  customer_address: string;
  customer_town: string;
  type_service_call: number;
  description: string;
}

interface ServiceParts {
  id?: number;
  customer_id: number;
  oil_filter: string;
  oil_filter_2: string;
  oil_nozzle: string;
  oil_nozzle_2: string;
}

export default defineComponent({
  name: 'CustomerProfile',
  components: {
    Header,
    SideBar,
    Footer,
    LMap,
    LTileLayer,
    ServiceEditModal,
    PartsEditModal,
  },
  data() {
    return {
      zoom: 14,
      token: null,
user: null as { user_id: number; user_name: string; confirmed: string; } | null,
      isTrue: true,
      automatic_status: 0,
      automatic_response: 0,
      customer_last_delivery: '',
      comments: [ { id: 0, created: '', customer_id: 0, poster_employee_id: 0, comment: '' } ],
      CreateSocialForm: { basicInfo: { comment: '' } },
      credit_cards: [ { id: 0, name_on_card: '', main_card: false, card_number: '', expiration_month: 0, type_of_card: '', last_four_digits: '', expiration_year: '', zip_code: '', security_number: '' } ],
      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: '', customer_latitude: 0, customer_longitude: 0, correct_address: true, account_number: '' },
      customer_description: { id: 0, customer_id: 0, account_number: '', company_id: '', fill_location: 0, description: '' },
      customer_tank: { id: 0, last_tank_inspection: null, tank_status: false, outside_or_inside: false, tank_size: 0 },
      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: [],
      autodeliveries: [],
      delivery_page: 1,
      delivery_perPage: 50,
      delivery_recordsLength: 0,
      delivery_options: { delivery_edgeNavigation: false, delivery_format: false, delivery_template: PaginationComp },
      serviceCalls: [] as ServiceCall[],
      selectedServiceForEdit: null as ServiceCall | null,
      isPartsModalOpen: false,
      currentParts: null as ServiceParts | null,
    }
  },
  computed: {
    hasPartsData() {
      if (!this.currentParts) return false;
      return !!(this.currentParts.oil_filter || this.currentParts.oil_filter_2 || this.currentParts.oil_nozzle || this.currentParts.oil_nozzle_2);
    }
  },
  created() {
    this.getCustomer(this.$route.params.id);
  },
  mounted() {
    // getPage is now called from within getCustomer, so this can be removed if it's redundant
  },
  watch: {
    '$route.params.id'(newId) {
      if (newId) {
        this.getCustomer(newId);
      }
    },
  },
  methods: {
    getPage: function (page: any) {
      if (this.customer && this.customer.id) {
        this.getCustomerDelivery(this.customer.id, page);
      }
    },
    getCustomer(userid: any) {
      if (!userid) return;
      let path = import.meta.env.VITE_BASE_URL + '/customer/' + userid;
      axios({
        method: 'get',
        url: path,
        headers: authHeader(),
      }).then((response: any) => {
        this.customer = response.data;
        
        // --- ALL DEPENDENT API CALLS ARE NOW CHAINED HERE ---
        this.userStatus();
        this.getCreditCards(this.customer.id); // Assuming this uses user_id
        this.getCreditCardsCount(this.customer.id); // Assuming this uses user_id
        this.getCustomerSocial(this.customer.id, 1);
        this.getPage(this.delivery_page);
        this.checktotalOil(this.customer.id);
        this.getCustomerTank(this.customer.id);
        this.userAutomaticStatus(this.customer.id);
        this.getCustomerDescription(this.customer.id);
        this.getCustomerStats(this.customer.id);
        this.getCustomerLastDelivery(this.customer.id);
        this.getServiceCalls(this.customer.id);
        this.fetchCustomerParts(this.customer.id);
      }).catch((error: any) => {
          console.error("CRITICAL: Failed to fetch main customer data. Aborting other calls.", error);
      });
    },
    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
        if (this.automatic_status === 1){
          this.getCustomerAutoDelivery(this.customer.id)
        }
        this.checktotalOil(this.customer.id)
      })
    },
    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' });
        } else {
          this.$notify({ title: "Automatic Status", text: 'Customer is now Manual Customer', type: 'Warning' });
        }
        this.getCustomer(this.$route.params.id);
      })
    },
    getNozzleColor(nozzleString: string): string {
      if (!nozzleString || typeof nozzleString !== 'string') return '';
      const firstChar = nozzleString.trim().toLowerCase().charAt(0);
      switch (firstChar) {
        case 'a': return '#EF4444';
        case 'b': return '#3B82F6';
        case 'w': return '#16a34a';
        default: return 'inherit';
      }
    },
    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
      })
    },
    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
      })
    },
    checktotalOil(userid: any) {
      let path = import.meta.env.VITE_BASE_URL + '/stats/gallons/check/total/' + userid;
      axios({
        method: 'get',
        url: path,
        headers: authHeader(),
      })
    },
    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
      })
    },
    getCustomerTank(userid: any) {
      let path = import.meta.env.VITE_BASE_URL + '/customer/tank/' + userid;
      axios({
        method: 'get',
        url: path,
        headers: authHeader(),
      }).then((response: any) => {
        this.customer_tank = 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
      })
    },
    getCustomerAutoDelivery(userid: any) {
      let path = import.meta.env.VITE_AUTO_URL + '/delivery/all/profile/' + userid ;
      axios({
        method: 'get',
        url: path,
        headers: authHeader(),
      }).then((response: any) => {
        this.autodeliveries = response.data
      })
    },
    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.customer.user_id)
        this.getCreditCardsCount(this.customer.user_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 delivery", type: "success" });
          this.getPage(1)
        } else {
          notify({ title: "Failure", text: "error deleting delivery", type: "success" });
        }
      })
    },
    deleteCustomerSocial(comment_id: number) {
      let path = import.meta.env.VITE_BASE_URL + '/social/delete/' + comment_id;
      axios({
        method: 'delete',
        url: path,
        headers: authHeader(),
      }).then((response: any) => {
        console.log(response)
        this.getCustomerSocial(this.customer.id, 1)
      })
    },
    getCustomerSocial(userid: any, delivery_page: any) {
      let path = import.meta.env.VITE_BASE_URL + '/social/posts/' + userid + '/' + delivery_page;
      axios({
        method: 'get',
        url: path,
        headers: authHeader(),
      }).then((response: any) => {
        this.comments = response.data
      })
    },
    CreateSocialComment(payload: { comment: string; poster_employee_id: number }) {
      let path = import.meta.env.VITE_BASE_URL + "/social/create/" + this.customer.id;
      axios({
        method: "post",
        url: path,
        data: payload,
        withCredentials: true,
        headers: authHeader(),
      })
        .then((response: any) => {
          if (response.data.ok) {
            this.getCustomerSocial(this.customer.id, 1)
          }
          if (response.data.error) {
            this.$router.push("/");
          }
        })
    },
onSubmitSocial() {
  if (!this.user) {
    console.error("Cannot submit comment: user is not logged in.");
    return; // Stop the function from proceeding
  }
  
  let payload = { comment: this.CreateSocialForm.basicInfo.comment, poster_employee_id: this.user.user_id };
  this.CreateSocialComment(payload);
},
    getServiceCalls(customerId: number) {
        let path = `${import.meta.env.VITE_BASE_URL}/service/for-customer/${customerId}`;
        axios({
            method: 'get',
            url: path,
            headers: authHeader(),
            withCredentials: true,
        }).then((response: any) => {
            this.serviceCalls = response.data;
        }).catch((error: any) => {
            console.error("Failed to get customer service calls:", error);
        });
    },
    openEditModal(service: ServiceCall) {
      this.selectedServiceForEdit = service;
    },
    closeEditModal() {
      this.selectedServiceForEdit = null;
    },
    async handleSaveChanges(updatedService: ServiceCall) {
      try {
        const path = `${import.meta.env.VITE_BASE_URL}/service/update/${updatedService.id}`;
        await axios.put(path, updatedService, { headers: authHeader(), withCredentials: true });
        this.getServiceCalls(this.customer.id);
        this.closeEditModal();
      } catch (error) {
        console.error("Failed to save service call changes:", error);
      }
    },
    async handleDeleteService(serviceId: number) {
      if (!window.confirm("Are you sure you want to delete this service call?")) return;
      try {
        const path = `${import.meta.env.VITE_BASE_URL}/service/delete/${serviceId}`;
        const response = await axios.delete(path, { headers: authHeader(), withCredentials: true });
        if(response.data.ok) {
            this.getServiceCalls(this.customer.id);
            this.closeEditModal();
             notify({ title: "Success", text: "Service call deleted!", type: "success" });
        }
      } catch (error) {
        console.error("Failed to delete service call:", error);
      }
    },
    async fetchCustomerParts(customerId: number) {
        try {
            const path = `${import.meta.env.VITE_BASE_URL}/service/parts/customer/${customerId}`;
            const response = await axios.get(path, { headers: authHeader() });
            this.currentParts = response.data;
        } catch (error) {
            console.error("Failed to fetch customer parts:", error);
            notify({ title: "Error", text: "Could not fetch equipment parts.", type: "error" });
        }
    },
    openPartsModal() {
      if (this.currentParts) {
        this.isPartsModalOpen = true;
      } else {
        notify({ title: "Info", text: "Parts data still loading, please wait.", type: "info" });
      }
    },
    closePartsModal() {
      this.isPartsModalOpen = false;
    },
    async handleSaveParts(partsToSave: ServiceParts) {
        try {
            const path = `${import.meta.env.VITE_BASE_URL}/service/parts/update/${partsToSave.customer_id}`;
            const response = await axios.post(path, partsToSave, { headers: authHeader() });
            
            if(response.data.ok) {
                this.currentParts = partsToSave;
                 notify({ title: "Success", text: "Equipment parts saved successfully!", type: "success" });
            }
            this.closePartsModal();
        } catch (error) {
            console.error("Failed to save parts:", error);
            notify({ title: "Error", text: "Failed to save equipment parts.", type: "error" });
        }
    },
    formatDate(dateString: string): string {
      if (!dateString) return 'N/A';
      return dayjs(dateString).format('MMMM D, YYYY');
    },
    formatTime(dateString: string): string {
      if (!dateString) return 'N/A';
      return dayjs(dateString).format('h:mm A');
    },
    getServiceTypeName(typeId: number): string {
      const typeMap: { [key: number]: string } = { 0: 'Tune-up', 1: 'No Heat', 2: 'Fix', 3: 'Tank Install', 4: 'Other' };
      return typeMap[typeId] || 'Unknown Service';
    },
    getServiceTypeColor(typeId: number): string {
       const colorMap: { [key: number]: string } = { 0: 'blue', 1: 'red', 2: 'green', 3: '#B58900', 4: 'black' };
      return colorMap[typeId] || 'gray';
    }
  },
})
</script>

<style scoped></style>