<template>
  <div v-if="isOpen"
    class="text-D pt-serif-regular-italic fixed inset-0 bg-black/75 flex items-center justify-center z-[9999]">
    <div class="bg-white w-[1224px] h-[528px] rounded-md shadow-lg relative overflow-hidden">
        <div class="bg-yellow-500 h-8 w-full">
            <div class="bg-D h-6 w-full"></div>
        </div>

      <div class="p-6 text-sm flex flex-col h-full relative">
        <div class="relative flex items-center justify-between top-0 pb-2 mb-2">
          <div class="flex flex-col gap-2 -mt-5">
            <p class="flex items-center gap-2">
              <i class="fab fa-instagram text-D text-xl"></i> tokomas_Jakartacitayam
            </p>
            <p class="flex items-center gap-2">
              <i class="fab fa-tiktok text-D text-xl"></i> tokomas_Jakartacitayam
            </p>
            <p class="flex items-center gap-2">
              <i class="fab fa-whatsapp text-D text-xl"></i> 08158851178
            </p>
            <p class=" text-sm">{{ generateTransactionCode() }}</p>

          </div>


          <div class="absolute inset-x-0 top-[-48px] flex flex-col items-center">
            <img :src="logo" alt="Logo" class="h-40" />
          </div>


          <div class="grid grid-cols-[130px_1fr] gap-y-0 text-xs items-center -mt-5 relative z-10">
            <div class="text-right font-semibold pr-3">Tanggal :</div>

            <p class="mt-1 text-left pl-2">{{ getCurrentDate() }}</p>
            
            <div class="text-right font-semibold pr-3">Nama :</div>

            <inputField v-model="namaPembeli" class="h-7 text-sm rounded bg-blue-200 w-full" />

            <div class="text-right font-semibold pr-3">No.Hp :</div>

            <inputField v-model="nomorTelepon" class="h-7 px-2 text-sm rounded bg-blue-200 w-full" />

            <div class="text-right font-semibold pr-3">Alamat :</div>

            <inputField v-model="alamat" class="h-7 px-2 text-sm rounded bg-blue-200 w-full" />

          </div>
        </div>


       


        <table class="w-full border-D  text-sm table-fixed border-b">
          <thead>
            <tr class="border-b border-t border-D">
              <th class="w-[60px] border-r border-D">Jml</th>
              <th class="w-[330px] py-2 border-r border-D">Item</th>
              <th class="w-[70px] border-r border-D">Posisi</th>
              <th class="w-[60px] border-r border-D">Berat</th>
              <th class="w-[60px] border-r border-D">Kadar</th>
              <th class="w-[210px]">Harga</th>
            </tr>
          </thead>

          <tbody>
            <tr v-for="(item, index) in pesananMinimal" :key="index" class="text-center">
              <td class="border-r border-D">
                <span v-if="item.harga_deal">1</span>
              </td>
              <td class="flex items-center gap-2 p-2 border-r border-D">
                <template v-if="item.produk?.foto?.[0]?.url">
                  <img :src="item.produk.foto[0].url" class="w-12 h-12 object-cover" />
                </template>
                <template v-else>
                  <div class="w-12 h-12"></div>
                </template>
                {{ item.produk?.nama || '' }}
              </td>
              <td class="border-r border-D">{{ item.nampan?.nama || 'Brankas' }}</td>
              <td class="border-r border-D">
                <span v-if="item.produk?.berat">{{ item.produk.berat }}g</span>
              </td>
              <td class="border-r border-D">
                <span v-if="item.produk?.kadar">{{ item.produk.kadar }}k</span>
              </td>
              <td>
                <span v-if="item.harga_deal">Rp{{ item.harga_deal.toLocaleString() }}</span>
              </td>
            </tr>
          </tbody>
        </table>
        <!-- Bagian bawah -->
        <div class="flex text-sm mt-2">
          <!-- PERHATIAN -->
          <div class="w-[40%] p-2 text-left">
            <p class="font-semibold">PERHATIAN</p>
            <ol class="list-decimal ml-4 text-xs space-y-1">
              <li>Berat barang telah ditimbang dan disaksikan oleh pembeli.</li>
              <li>Barang yang dikembalikan menurut harga pasaran dan dipotong ongkos bikin, barang rusak
                lain harga.</li>
              <li>Barang yang sudah dibeli berarti sudah diperiksa dan disetujui.</li>
              <li>Surat ini harap dibawa pada saat menjual kembali.</li>
            </ol>
          </div>

          <!-- SALES -->
          <div class="w-[20%] p-2 flex flex-col items-center justify-center">
            <p><strong>Sales</strong></p>
            <inputSelect v-model="selectedSales" :options="salesOptions"
              class="mt-16 text-sm rounded bg-B cursor-pointer !w-[160px] text-center [option]:text-left" />
          </div>

          <!-- ONGKOS & TOTAL -->
          <div class="ml-auto w-[25%] p-2 flex flex-col justify-between">
            <div class="space-y-4">
              <!-- Ongkos bikin -->
              <div class="flex items-start justify-between ">
                <div class="flex flex-col ">
                  <p class="font-semibold">Ongkos bikin</p>
                  <p class="text-red-500 text-xs">diluar harga jual</p>
                </div>
                <div class="flex items-center w-40">
                  <p>Rp</p>
                  <inputField v-model.number="ongkosBikin" type="number"
                    class="h-7 px-2 text-sm rounded bg-blue-200 text-left w-full" />
                </div>
              </div>

              <!-- Total -->
              <div class="flex items-center justify-between -mt-4">
                <p class="font-semibold">Total</p>
                <div class="flex items-center w-40">
                  <p>Rp</p>
                  <p class="px-3 pl-2 py-1 text-left text-sm w-full">
                    {{ grandTotal.toLocaleString() }}
                  </p>
                </div>
              </div>
            </div>

            <!-- Tombol -->
            <div class="flex justify-end gap-2 mt-4">
              <button @click="$emit('close')" class="bg-gray-400 text-white px-6 py-2 rounded">
                Batal
              </button>
              <button @click="handleSimpan" class="bg-C text-white px-6 py-2 rounded">
                Simpan
              </button>
            </div>
          </div>
        </div>
      </div>
      <p class="absolute p-2 bottom-0 left-0 w-full text-left text-xs bg-D text-white py-1">
        Terima kasih sudah berbelanja dengan kami
      </p>

    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import logo from '@/../images/logo.png'
import inputField from '@/components/inputField.vue'
import inputSelect from '@/components/inputSelect.vue'

import axios from 'axios'

const props = defineProps({
  isOpen: {
    type: Boolean,
    default: false,
  },
  pesanan: {
    type: Array,
    default: () => []
  },
  total: {
    type: Number,
    default: 0
  }
})


const emit = defineEmits(['close', 'confirm'])

const namaPembeli = ref('')
const nomorTelepon = ref('')
const alamat = ref('')
const ongkosBikin = ref(0)
const selectedSales = ref(null)
const salesOptions = ref([])

const grandTotal = computed(() => {
  return props.total + (ongkosBikin.value || 0)
})

const getCurrentDate = () => {
  const days = ['Minggu', 'Senin', 'Selasa', 'Rabu', 'Kamis', 'Jumat', 'Sabtu']
  const months = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']

  const now = new Date()
  const dayName = days[now.getDay()]
  const day = String(now.getDate()).padStart(2, '0')
  const month = months[now.getMonth()]
  const year = now.getFullYear()

  return `${dayName}/${day}-${month}-${year}`
}

const generateTransactionCode = () => {
  const now = new Date()
  const timestamp = now.getTime().toString().slice(-6)
  return `TRS-${timestamp}`
}

const fetchSales = async () => {
  try {
    const response = await axios.get('/api/sales', {
      headers: {
        Authorization: `Bearer ${localStorage.getItem("token")}`,
      },
    })

    salesOptions.value = response.data.map(sales => ({
      value: sales.id,
      label: sales.nama
    }))


    if (salesOptions.value.length > 0) {
      selectedSales.value = salesOptions.value[0].value
    }
  } catch (error) {
    console.error('Error fetching sales:', error)
  }
}

const handleSimpan = () => {

  if (!namaPembeli.value.trim()) {
    alert('Nama pembeli harus diisi!')
    return
  }

  if (!nomorTelepon.value.trim()) {
    alert('Nomor telepon harus diisi!')
    return
  }

  if (!alamat.value.trim()) {
    alert('Alamat harus diisi!')
    return
  }

  if (!selectedSales.value) {
    alert('Sales harus dipilih!')
    return
  }


  simpanTransaksi({
    id_sales: selectedSales.value,
    nama_pembeli: namaPembeli.value,
    no_hp: nomorTelepon.value,
    alamat: alamat.value,
    ongkosBikin: ongkosBikin.value || 0,
    total_harga: grandTotal.value,
    items: props.pesanan
  })
}


const simpanTransaksi = async (dataTransaksi) => {
  console.log('Data transaksi yang akan disimpan:', dataTransaksi);

  try {
    const response = await axios.post('/api/transaksi', dataTransaksi, {
      headers: {
        Authorization: `Bearer ${localStorage.getItem("token")}`,
      },
    });


    props.pesanan.value = [];
    props.isOpen = false;

    window.location.reload();

  } catch (error) {
    console.error('Error saving transaksi:', error);
    alert('Error menyimpan transaksi: ' + (error.response?.data?.message || error.message));
  }
};

onMounted(() => {
  if (props.isOpen) {
    fetchSales()
  }
})

const pesananMinimal = computed(() => {
  const arr = [...props.pesanan]
  while (arr.length < 2) {
    arr.push({ produk: {}, harga_deal: 0, posisi: '' })
  }
  return arr
})

</script>

<style scoped>
@import url('https://fonts.googleapis.com/css2?family=PT+Serif:ital,wght@0,400;0,700;1,400;1,700&display=swap');

.pt-serif-regular-italic {
  font-family: "PT Serif", serif;
  font-weight: 400;
}
</style>
