<template>
  <q-page
    v-if="canReadOrder"
    class="order-gateway flex flex-center column"
  >

    <div class="text-h5 text-primary q-mb-xl">
      🧾 Sipariş Modülü
    </div>

    <!-- 🟡 TASLAK -->
    <div
      v-if="hasDraft && canWriteOrder"
      class="draft-card q-pa-lg rounded-borders shadow-2 bg-white"
    >
      <div class="text-subtitle1 text-bold text-negative">
        📌 Devam Eden Taslak Bulundu
      </div>

      <div class="q-mt-sm">
        <div v-if="draftNumber">
          <b>No:</b> {{ draftNumber }}
        </div>
        <div v-else class="text-grey-7">
          Numara alınamadı
        </div>
      </div>

      <q-btn
        class="q-mt-md"
        color="primary"
        icon="login"
        label="TASLAĞA DEVAM ET"
        :disable="!canWriteOrder"
        @click="continueDraft"
      />
    </div>


    <!-- 🔘 BUTTONS -->
    <div class="row q-gutter-lg q-mt-xl">

      <!-- NEW ORDER -->
      <q-btn
        v-if="canWriteOrder"
        color="primary"
        icon="add_circle"
        label="YENİ SİPARİŞ OLUŞTUR"
        @click="confirmNewOrder"
      />

      <!-- ORDER LIST -->
      <q-btn
        v-if="canReadOrder"
        color="secondary"
        icon="folder_open"
        label="MEVCUT SİPARİŞİ AÇ"
        @click="goOrderList"
      />
      <q-btn
        v-if="canUpdateOrder"
        color="negative"
        icon="task_alt"
        label="TAMAMLANANLARI TOPLU KAPAT"
        @click="goBulkClose"
      />

    </div>


    <!-- YETKİ YOKSA -->
    <div
      v-if="!canReadOrder"
      class="text-negative text-subtitle1 q-mt-xl"
    >
      Bu modüle erişim yetkiniz yok.
    </div>

  </q-page>
</template>


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

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

const canReadOrder   = canRead('order')
const canWriteOrder  = canWrite('order')
const canUpdateOrder = canUpdate('order')

const router = useRouter()
const $q = useQuasar()
const store = useOrderEntryStore()
const activeNewHeaderID = computed(() => {
  try {
    return localStorage.getItem(store.getLastTxnKey)
  } catch {
    return null
  }
})

/* ===========================================================
   🔍 NEW DRAFT — TEK VE DOĞRU KAYNAK
   → SADECE store.getDraftKey
=========================================================== */
const draftRaw = computed(() => {
  try {
    return localStorage.getItem(store.getDraftKey)
  } catch {
    return null
  }
})

const hasDraft = computed(() => {
  if (!draftRaw.value) return false
  try {
    const snap = JSON.parse(draftRaw.value)
    return snap?.mode === 'new'
  } catch {
    return false
  }
})

const draftNumber = computed(() => {
  if (!hasDraft.value) return null
  try {
    return JSON.parse(draftRaw.value)?.header?.OrderNumber || null
  } catch {
    return null
  }
})

function continueDraft () {

  if (!canWriteOrder.value) {
    $q.notify({
      type: 'negative',
      message: 'Taslak güncelleme yetkiniz yok'
    })
    return
  }

  // 1) önce store meta
  let activeId = store.getActiveNewHeaderId?.()

  // 2) fallback: draft payload içinden
  if (!activeId) {
    try {
      const raw = localStorage.getItem(store.getDraftKey)
      const snap = raw ? JSON.parse(raw) : null
      activeId = snap?.header?.OrderHeaderID || null
    } catch {}
  }

  if (!activeId) {
    $q.notify({ type: 'warning', message: 'Devam edecek taslak bulunamadı' })
    return
  }

  // name resolve + path fallback
  const target = {
    name: 'order-entry',
    params: { orderHeaderID: String(activeId) },
    query: { mode: 'new', source: 'draft' }
  }

  // DEBUG: resolve sonucu
  console.log('➡️ continueDraft resolve:', router.resolve(target))

  router.push(target).catch(err => {
    console.warn('❌ continueDraft push failed, fallback to path:', err)
    router.push({
      path: `/app/order-entry/${encodeURIComponent(String(activeId))}`,
      query: { mode: 'new', source: 'draft' }
    })
  })
}



/* ===========================================================
   📂 Mevcut Sipariş Listesi
=========================================================== */
function goOrderList () {
  router.push({ name: 'order-list' })
}

function goBulkClose () {
  router.push({ name: 'order-bulk-close' })
}

/* ===========================================================
   🧹 NEW Taslağı Temizle (SADECE NEW)
=========================================================== */
function clearNewDraft () {
  try {
    localStorage.removeItem(store.getDraftKey)
    if (store.getLastTxnKey) {
      localStorage.removeItem(store.getLastTxnKey)
    }
  } catch {}
}

/* ===========================================================
   🟢 Yeni Sipariş Onayı
=========================================================== */
function confirmNewOrder () {

  if (!canWriteOrder.value) {
    $q.notify({
      type: 'negative',
      message: 'Yeni sipariş yetkiniz yok'
    })
    return
  }

  if (!hasDraft.value) {
    goNewOrder()
    return
  }



  $q.dialog({
    title: 'Yeni Sipariş',
    message: 'Önceki NEW taslak silinecek. Onaylıyor musun?',
    ok: { label: 'Evet', color: 'negative' },
    cancel: { flat: true, label: 'Hayır' },
    persistent: true
  }).onOk(() => {
    clearNewDraft()
    goNewOrder()
  })
}

/* ===========================================================
   🟦 Yeni Sipariş Başlat — TAM SIFIR
=========================================================== */
async function goNewOrder () {
  try {
    store.preventPersist = true
    store.resetForNewOrder()
    store.preventPersist = false

    const header = await store.startNewOrder({ $q })
    const newId = header?.OrderHeaderID

    if (!newId) {
      console.error('❌ startNewOrder OrderHeaderID üretmedi:', header)
      $q.notify({ type: 'negative', message: 'OrderHeaderID üretilemedi!' })
      return
    }

    const target = {
      name: 'order-entry',
      params: { orderHeaderID: String(newId) },
      query: { mode: 'new', source: 'new' }
    }

    // DEBUG: resolve sonucu (çok kritik)
    console.log('➡️ goNewOrder resolve:', router.resolve(target))

    // ✅ mutlaka await + catch
    await router.push(target).catch(async (err) => {
      console.warn('❌ router.push failed, fallback to path:', err)
      await router.push({
        path: `/app/order-entry/${encodeURIComponent(String(newId))}`,
        query: { mode: 'new', source: 'new' }
      })
    })

  } catch (err) {
    console.error('❌ goNewOrder hata:', err)
    $q.notify({ type: 'negative', message: 'Yeni sipariş oluşturulamadı!' })
  }
}

</script>
