<template>
  <q-page
    v-if="canExportOrder"
    class="q-pa-md"
  >
    <q-card flat bordered class="q-pa-md" style="max-width: 720px">
      <q-card-section>
        <div class="text-h6">Order PDF</div>
        <div class="text-caption text-grey-7">Order ID: {{ orderId || '-' }}</div>
      </q-card-section>

      <q-card-actions align="right" class="q-gutter-sm">
        <q-btn
          v-if="canOpenPdf"
          color="primary"
          icon="picture_as_pdf"
          label="PDF Ac"
          :loading="loading"
          :disable="loading || !orderId"
          @click="openPdf"
        />

        <q-btn
          v-if="canEditOrder"
          flat
          color="secondary"
          label="Siparise Don"
          :disable="!orderId"
          @click="goToOrder"
        />
      </q-card-actions>
    </q-card>
  </q-page>

  <q-page
    v-else
    class="q-pa-md flex flex-center"
  >
    <div class="text-negative text-subtitle1">
      Bu module erisim yetkiniz yok.
    </div>
  </q-page>
</template>

<script setup>
import { computed, ref } from 'vue'
import { useQuasar } from 'quasar'
import { useRoute, useRouter } from 'vue-router'
import { usePermission } from 'src/composables/usePermission'
import { useOrderEntryStore } from 'src/stores/orderentryStore'

const { canWrite, canUpdate, canExport } = usePermission()

const canExportOrder = canExport('order')
const canWriteOrder = canWrite('order')
const canUpdateOrder = canUpdate('order')

const canEditOrder = computed(() => canWriteOrder.value || canUpdateOrder.value)
const canOpenPdf = computed(() => canExportOrder.value)

const $q = useQuasar()
const route = useRoute()
const router = useRouter()
const orderStore = useOrderEntryStore()

const loading = ref(false)
const orderId = computed(() => String(route.params.id || '').trim())

async function openPdf () {
  if (!canOpenPdf.value) {
    $q.notify({
      type: 'negative',
      message: 'Siparis PDF export yetkiniz yok'
    })
    return
  }

  if (!orderId.value) {
    $q.notify({
      type: 'warning',
      message: 'Order ID bulunamadi'
    })
    return
  }

  loading.value = true
  try {
    await orderStore.downloadOrderPdf(orderId.value)
  } catch (err) {
    $q.notify({
      type: 'negative',
      message: err?.message || 'PDF acilamadi'
    })
  } finally {
    loading.value = false
  }
}

function goToOrder () {
  if (!canEditOrder.value) {
    $q.notify({
      type: 'negative',
      message: 'Siparis duzenleme yetkiniz yok'
    })
    return
  }

  if (!orderId.value) {
    $q.notify({
      type: 'warning',
      message: 'Order ID bulunamadi'
    })
    return
  }

  const routeName = canUpdateOrder.value ? 'order-edit' : 'order-entry'
  router.push({
    name: routeName,
    params: { orderHeaderID: orderId.value }
  })
}
</script>
