<template>
  <div>
    <admin-data-table :headers="penyataTableHeaders" :items="penyata" :loading="loading" :show-pagination="true"
      index-title="Bil." empty-text="Tiada data penyata" :exportable="true">
      <template v-slot:item-aksi="{ item }">
        <button type="button" class="btn btn-success btn-sm" @click="cetakPDF(item.no_anggota)"
          :disabled="!bolehCetak(item.status_penyata)">
          PDF
        </button>
      </template>
    </admin-data-table>

    <!-- PAGINATION -->
    <div class="text-right" v-if="meta.last_page > 1">
      <button class="btn btn-default btn-sm" :disabled="meta.current_page === 1"
        @click="changePage(meta.current_page - 1)">
        Sebelumnya
      </button>

      <button class="btn btn-default btn-sm" :disabled="meta.current_page === meta.last_page"
        @click="changePage(meta.current_page + 1)">
        Seterusnya
      </button>
    </div>

  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'ManagePenyata',

  data() {
    return {
      penyata: [],
      loading: false,
      searchNoAnggota: '',
      penyataTableHeaders: [
        { title: 'No Anggota', key: 'no_anggota', sortable: true },
        { title: 'Unit', key: 'unit', sortable: true },
        { title: 'Nama', key: 'name', sortable: true },
        { title: 'Tindakan', key: 'aksi', sortable: false }
      ],
      meta: {
        current_page: 1,
        last_page: 1
      }
    };
  },

  mounted() {
    this.getPenyata();
  },

  methods: {

    async getPenyata(page = 1) {
      this.loading = true;

      try {
        const res = await axios.get('/api/v1/voter', {
          params: {
            page: page,
            no_anggota: this.searchNoAnggota
          }
        });

        this.penyata = res.data.data;
        this.meta.current_page = res.data.current_page;
        this.meta.last_page = res.data.last_page;

      } catch (err) {
        console.error(err);
        alert('Gagal ambil senarai penyata');
      } finally {
        this.loading = false;
      }
    },

    changePage(page) {
      this.getPenyata(page);
    },

    searchPenyata() {
      this.getPenyata(1);
    },

    resetSearch() {
      this.searchNoAnggota = '';
      this.getPenyata(1);
    },

    bolehCetak(status) {
      return ['DISAHKAN', 'PERLU_SEMAK'].includes(status);
    },

    cetakPDF(noAnggota) {
      axios({
        url: `/api/v1/penyata/${noAnggota}/pdf`,
        method: 'GET',
        responseType: 'blob'
      })
        .then((response) => {
          const file = new Blob([response.data], {
            type: 'application/pdf'
          });

          const fileURL = URL.createObjectURL(file);
          window.open(fileURL);
        })
        .catch((error) => {
          console.error(error);
          alert('Gagal jana PDF.');
        });
    }

  }
};
</script>
