<template>
	<div>

		<div class="panel panel-default">
			<div class="panel-body">

				<div class="form-group">
					<router-link class="btn btn-success" :to="{ name: 'Tambah Sesi' }">
						<i class="fa fa-plus"></i> Tambah Sesi
					</router-link>
					<button class="btn btn-default" @click="refreshPosition()">
						<i class="fa fa-refresh"></i> Kemaskini Sesi
					</button>
				</div>

				<admin-data-table :headers="positionTableHeaders" :items="data.positions" :loading="positionLoading"
					:items-per-page="10" :show-pagination="true" empty-text="Tiada jawatan" :exportable="true"
					export-file-name="jawatan">
					<template v-slot:item-actions="{ item }">
						<button type="button" class="btn btn-info" @click="edit(item)">
							<i class="fa fa-edit"></i> Edit
						</button>
						<button type="button" class="btn btn-danger"
							@click="util.showModal('#delete-position-modal'); id = item.id">
							<i class="fa fa-trash"></i> Padam
						</button>
					</template>
				</admin-data-table>
			</div>
		</div>

		<modal id="delete-position-modal">
			<modal-header>Padam Jawatan</modal-header>
			<modal-body>
				<h2>Are you sure to delete Position?</h2>
			</modal-body>
			<modal-footer>
				<button class="btn btn-danger" @click="deletePosition()">Padam</button>
				<button class="btn btn-default" @click="util.hideModal('#delete-position-modal')">Cancel</button>
			</modal-footer>
		</modal>

	</div>
</template>

<script>
export default {
	data: function () {
		return {
			id: 0,
			positionLoading: false,
			positionTableHeaders: [
				{ title: 'Nama', key: 'name', sortable: true },
				{ title: 'Tindakan', key: 'actions', sortable: false }
			]
		}
	},

	created: function () {
		if (this.$route.query.refresh) {
			this.refreshPosition();
			this.$router.replace({ name: 'Kemaskini Sesi' })
		}
	},

	methods: {
		refreshPosition: function () {
			var vm = this;
			this.positionLoading = true;
			this.util.notify('Refreshing Position', 'loading');
			axios.get(config.API + 'position')
				.then(response => {
					$.notifyClose();
					vm.data.positions = response.data;
				})
				.catch(error => {
					$.notifyClose();
					vm.util.showResult(error);
				})
				.finally(function () {
					vm.positionLoading = false;
				})
		},

		edit: function (position) {
			var vm = this;
			this.data.position = position;
			this.$router.push({ name: 'Edit Position', params: { id: vm.data.position.id } })
		},

		deletePosition: function () {
			var vm = this;
			this.util.notify('Deleting position', 'loading');
			this.util.hideModal('#delete-position-modal');
			axios.delete(config.API + 'position/' + this.id)
				.then(response => {
					$.notifyClose();
					if (vm.util.showResult(response, 'success')) vm.refreshPosition();
				})
				.catch(error => {
					$.notifyClose();
					vm.util.showResult(error);
				})
		}
	}
}
</script>