<!DOCTYPE html>
<html lang="id">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Monitor Antrian Poli - e-RM</title>
	<link rel="stylesheet" href="<?= base_url('assets/adminlte/plugins/bootstrap/css/bootstrap.min.css'); ?>">
	<link rel="stylesheet" href="<?= base_url('assets/adminlte/plugins/fontawesome-free/css/all.min.css'); ?>">
	<style>
		body {
			background: #f4f6fb;
			min-height: 100vh;
			font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
		}

		.queue-wrapper {
			padding: 25px;
		}

		.queue-header {
			background: #ffffff;
			border-radius: 20px;
			padding: 25px 30px;
			margin-bottom: 25px;
			box-shadow: 0 10px 30px rgba(28, 39, 60, 0.08);
		}

		.queue-header h1 {
			font-size: 2.1rem;
			font-weight: 700;
			color: #243b53;
		}

		.queue-header p {
			color: #6c7a89;
			margin-bottom: 0;
		}

		.time-card {
			text-align: right;
		}

		.time-card .time {
			font-size: 2rem;
			font-weight: 700;
			color: #1f8ef1;
		}

		.filter-card {
			background: #ffffff;
			border-radius: 15px;
			padding: 20px;
			box-shadow: 0 4px 18px rgba(24, 39, 75, 0.08);
			margin-bottom: 25px;
		}

		.filter-card label {
			font-weight: 600;
			color: #1d3557;
		}

		.info-chip {
			display: inline-flex;
			align-items: center;
			padding: 6px 15px;
			border-radius: 999px;
			background: rgba(33, 150, 243, 0.1);
			color: #1f8ef1;
			font-weight: 600;
		}

		.queue-card {
			background: #ffffff;
			border-radius: 18px;
			padding: 25px;
			box-shadow: 0 7px 25px rgba(0, 0, 0, 0.08);
			margin-bottom: 25px;
			height: 100%;
		}

		.queue-card h5 {
			font-size: 1.2rem;
			font-weight: 600;
			color: #5c677d;
		}

		.queue-number {
			font-size: 4.2rem;
			font-weight: 800;
			color: #ff4757;
			margin-bottom: 12px;
			letter-spacing: 2px;
		}

		.queue-number.next {
			color: #20bf6b;
		}

		.queue-patient {
			font-size: 1.5rem;
			font-weight: 600;
			color: #2f3542;
		}

		.queue-meta {
			color: #8390a2;
			font-size: 0.95rem;
			margin-top: 5px;
		}

		.stats-card {
			background: #ffffff;
			border-radius: 18px;
			padding: 20px 25px;
			box-shadow: 0 5px 20px rgba(34, 60, 80, 0.1);
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin-bottom: 25px;
		}

		.stats-card .label {
			font-size: 0.9rem;
			text-transform: uppercase;
			font-weight: 700;
			color: #8898aa;
		}

		.stats-card .value {
			font-size: 2rem;
			font-weight: 800;
			color: #1a202c;
		}

		.queue-list {
			background: #ffffff;
			border-radius: 18px;
			padding: 25px;
			box-shadow: 0 10px 30px rgba(15, 23, 42, 0.1);
		}

		.queue-item {
			display: flex;
			align-items: center;
			border-bottom: 1px solid #f1f2f6;
			padding: 15px 0;
		}

		.queue-item:last-child {
			border-bottom: none;
		}

		.queue-item-number {
			width: 90px;
			font-size: 2rem;
			font-weight: 700;
			color: #1e90ff;
		}

		.queue-item-body {
			flex: 1;
		}

		.queue-item-body h6 {
			font-size: 1.1rem;
			font-weight: 600;
			color: #2f3542;
			margin-bottom: 5px;
		}

		.queue-item-body small {
			color: #a4b0be;
		}

		.status-badge {
			font-weight: 700;
			font-size: 0.9rem;
			padding: 7px 15px;
			border-radius: 999px;
		}

		.status-menunggu {
			background: rgba(255, 193, 7, 0.15);
			color: #f39c12;
		}

		.status-dipanggil {
			background: rgba(40, 167, 69, 0.15);
			color: #20bf6b;
		}

		.status-selesai {
			background: rgba(0, 123, 255, 0.15);
			color: #007bff;
		}

		.status-batal {
			background: rgba(220, 53, 69, 0.15);
			color: #dc3545;
		}

		.empty-state {
			text-align: center;
			color: #a0aec0;
			padding: 60px 0;
		}

		.empty-state i {
			font-size: 3rem;
			margin-bottom: 15px;
		}

		@media (max-width: 768px) {
			.time-card {
				text-align: left;
				margin-top: 15px;
			}

			.queue-number {
				font-size: 3rem;
			}
		}
	</style>
</head>

<body>
	<div class="queue-wrapper container-fluid">
		<div class="queue-header">
			<div class="row align-items-center">
				<div class="col-md-8">
					<h1><i class="fas fa-clinic-medical mr-2 text-primary"></i>Monitor Antrian Poliklinik</h1>
					<p>Pantau nomor antrian poli secara real-time berdasarkan data di <strong>db_erm</strong></p>
					<div class="info-chip mt-3">
						<i class="fas fa-database mr-2"></i>tb_antrian · tb_registrasi · tb_poli
					</div>
				</div>
				<div class="col-md-4 time-card">
					<div class="text-muted">Waktu saat ini</div>
					<div class="time" id="current-time"><?= date('H:i:s') ?></div>
					<div id="current-date"><?= date('d F Y') ?></div>
				</div>
			</div>
		<div class="mt-3 text-muted">
			<i class="fas fa-sync mr-1"></i> Terakhir diperbarui:
			<span id="last-update">-</span>
		</div>
		</div>

		<div class="filter-card">
			<div class="row align-items-center">
				<div class="col-md-6 mb-3 mb-md-0">
					<label for="filter-poli">Filter Poli</label>
					<select id="filter-poli" class="form-control form-control-lg">
						<option value="all">Semua Poliklinik</option>
					</select>
				</div>
				<div class="col-md-3 mb-3 mb-md-0">
					<label class="d-block">Antrian ditampilkan</label>
					<div id="filter-info" class="font-weight-bold text-primary">Hari ini</div>
				</div>
				<div class="col-md-3 text-md-right">
					<button id="btn-refresh" class="btn btn-primary btn-lg">
						<i class="fas fa-sync-alt mr-2"></i>Muat Ulang
					</button>
				</div>
			</div>
		</div>

		<div class="row">
			<div class="col-lg-6">
				<div class="queue-card h-100">
					<h5><i class="fas fa-bullhorn mr-2 text-danger"></i>Nomor Antrian Sekarang</h5>
					<div id="queue-current-number" class="queue-number">-</div>
					<div id="queue-current-patient" class="queue-patient">Belum ada antrian dipanggil</div>
					<div id="queue-current-meta" class="queue-meta">Pilih poli untuk melihat detail</div>
				</div>
			</div>
			<div class="col-lg-6">
				<div class="queue-card h-100">
					<h5><i class="fas fa-forward mr-2 text-success"></i>Nomor Berikutnya</h5>
					<div id="queue-next-number" class="queue-number next">-</div>
					<div id="queue-next-patient" class="queue-patient">Menunggu penjadwalan</div>
					<div id="queue-next-meta" class="queue-meta">Pasien akan tampil setelah dipanggil</div>
				</div>
			</div>
		</div>

		<div class="row">
			<div class="col-md-4">
				<div class="stats-card">
					<div>
						<div class="label"><i class="fas fa-list-ol mr-1"></i>Total Antrian</div>
						<div id="stat-total" class="value">0</div>
					</div>
					<i class="fas fa-stream fa-2x text-primary"></i>
				</div>
			</div>
			<div class="col-md-4">
				<div class="stats-card">
					<div>
						<div class="label text-warning"><i class="fas fa-clock mr-1"></i>Menunggu</div>
						<div id="stat-menunggu" class="value text-warning">0</div>
					</div>
					<i class="fas fa-user-clock fa-2x text-warning"></i>
				</div>
			</div>
			<div class="col-md-4">
				<div class="stats-card">
					<div>
						<div class="label text-success"><i class="fas fa-check-circle mr-1"></i>Selesai</div>
						<div id="stat-selesai" class="value text-success">0</div>
					</div>
					<i class="fas fa-user-check fa-2x text-success"></i>
				</div>
			</div>
		</div>

		<div class="queue-list">
			<div class="d-flex justify-content-between align-items-center mb-3">
				<h4 class="mb-0 text-primary">
					<i class="fas fa-list-alt mr-2"></i>Daftar Antrian Poli
				</h4>
				<span class="badge badge-pill badge-primary p-2" id="queue-count">0 Antrian</span>
			</div>

			<div id="queue-items">
				<div class="empty-state">
					<i class="fas fa-hands-helping text-primary"></i>
					<p>Belum ada data antrian untuk kriteria yang dipilih</p>
				</div>
			</div>
		</div>
	</div>

	<script src="<?= base_url('assets/adminlte/plugins/jquery/jquery.min.js'); ?>"></script>
	<script src="<?= base_url('assets/adminlte/plugins/bootstrap/js/bootstrap.bundle.min.js'); ?>"></script>
	<script>
		const REFRESH_INTERVAL = 7000;
		let refreshTimer = null;
		let selectedPoli = 'all';
		const todayDate = '<?= date('Y-m-d') ?>';

		function formatDateTime(dateString) {
			if (!dateString) {
				return '-';
			}
			const date = new Date(dateString.replace(' ', 'T'));
			return date.toLocaleString('id-ID', {
				day: '2-digit',
				month: 'short',
				year: 'numeric',
				hour: '2-digit',
				minute: '2-digit'
			});
		}

		function updateClock() {
			const now = new Date();
			const timeString = now.toLocaleTimeString('id-ID', {
				hour: '2-digit',
				minute: '2-digit',
				second: '2-digit'
			});
			const dateString = now.toLocaleDateString('id-ID', {
				day: '2-digit',
				month: 'long',
				year: 'numeric'
			});

			$('#current-time').text(timeString);
			$('#current-date').text(dateString);
		}

		function getStatusBadge(status) {
			switch (status) {
				case 'MENUNGGU':
					return '<span class="status-badge status-menunggu">MENUNGGU</span>';
				case 'DIPANGGIL':
					return '<span class="status-badge status-dipanggil">DIPANGGIL</span>';
				case 'SELESAI':
					return '<span class="status-badge status-selesai">SELESAI</span>';
				case 'BATAL':
					return '<span class="status-badge status-batal">BATAL</span>';
				default:
					return '<span class="status-badge badge-secondary">' + (status || 'UNKNOWN') + '</span>';
			}
		}

		function updateCurrentQueue(current) {
			if (current) {
				$('#queue-current-number').text('#' + current.nomor_antrian);
				$('#queue-current-patient').text(current.nama_pasien || current.nama_lengkap || 'Pasien belum terhubung');
				$('#queue-current-meta').text((current.nama_poli || 'Poli belum ditentukan') + ' • Dipanggil ' + formatDateTime(current.waktu_panggil));
			} else {
				$('#queue-current-number').text('-');
				$('#queue-current-patient').text('Belum ada antrian dipanggil');
				$('#queue-current-meta').text('Silakan hubungi bagian pendaftaran untuk memanggil antrian');
			}
		}

		function updateNextQueue(nextQueue) {
			if (nextQueue) {
				$('#queue-next-number').text('#' + nextQueue.nomor_antrian);
				$('#queue-next-patient').text(nextQueue.nama_pasien || nextQueue.nama_lengkap || 'Pasien tanpa nama');
				$('#queue-next-meta').text((nextQueue.nama_poli || 'Poli belum ditentukan') + ' • Registrasi ' + formatDateTime(nextQueue.created_at));
			} else {
				$('#queue-next-number').text('-');
				$('#queue-next-patient').text('Menunggu penjadwalan');
				$('#queue-next-meta').text('Data antrian berikutnya akan muncul otomatis');
			}
		}

		function updateStats(items) {
			const total = items.length;
			const menunggu = items.filter(item => item.status_antrian === 'MENUNGGU').length;
			const selesai = items.filter(item => item.status_antrian === 'SELESAI').length;

			$('#stat-total').text(total);
			$('#stat-menunggu').text(menunggu);
			$('#stat-selesai').text(selesai);
			$('#queue-count').text(total + ' Antrian');
		}

		function renderQueueList(items) {
			if (!items.length) {
				$('#queue-items').html(`
					<div class="empty-state">
						<i class="fas fa-notes-medical text-primary"></i>
						<p>Tidak ada antrian poli untuk kriteria ini</p>
					</div>
				`);
				return;
			}

			const listHtml = items.map(item => `
				<div class="queue-item">
					<div class="queue-item-number">#${item.nomor_antrian}</div>
					<div class="queue-item-body">
						<h6>${item.nama_pasien || item.nama_lengkap || 'Pasien tanpa nama'}</h6>
						<small>${item.nama_poli || 'Poli tidak diketahui'} · ${item.nama_dokter || 'Dokter belum ditentukan'}</small>
						<div class="text-muted">${formatDateTime(item.created_at)}</div>
					</div>
					<div>${getStatusBadge(item.status_antrian)}</div>
				</div>
			`).join('');

			$('#queue-items').html(listHtml);
		}

		function processQueueData(data) {
			const list = Array.isArray(data) ? data.slice() : [];
			// pastikan urutan nomor antrian menanjak
			list.sort((a, b) => {
				const numA = parseInt(a.nomor_antrian, 10);
				const numB = parseInt(b.nomor_antrian, 10);
				if (isNaN(numA) || isNaN(numB)) {
					return (a.created_at > b.created_at) ? 1 : -1;
				}
				return numA - numB;
			});

			const current = list.find(item => item.status_antrian === 'DIPANGGIL');
			const nextQueue = list.find(item => item.status_antrian === 'MENUNGGU');

			updateCurrentQueue(current);
			updateNextQueue(nextQueue);
			updateStats(list);
			renderQueueList(list);

			$('#last-update').text(new Date().toLocaleTimeString('id-ID'));
		}

		function loadPoliOptions() {
			$.getJSON('<?= site_url("poli/get_poli") ?>', function(poliList) {
				if (!Array.isArray(poliList)) {
					return;
				}
				const options = poliList.map(poli => `<option value="${poli.poli_id}">${poli.nama_poli}</option>`);
				$('#filter-poli').append(options);
			});
		}

		function buildQueryParams() {
			const params = new URLSearchParams();
			params.append('poli_id', selectedPoli || 'all');
			params.append('start_date', todayDate);
			params.append('end_date', todayDate);
			params.append('status', 'all');
			return params.toString();
		}

		function loadQueueData() {
			const query = buildQueryParams();
			$.getJSON('<?= site_url("poli/get_antrian_poli") ?>?' + query, function(response) {
				processQueueData(response || []);
			}).fail(function() {
				alert('Gagal memuat data antrian poli');
			});
		}

		function startAutoRefresh() {
			if (refreshTimer) {
				clearInterval(refreshTimer);
			}
			refreshTimer = setInterval(loadQueueData, REFRESH_INTERVAL);
		}

		$(document).ready(function() {
			loadPoliOptions();
			loadQueueData();
			startAutoRefresh();

			updateClock();
			setInterval(updateClock, 1000);

			$('#filter-poli').on('change', function() {
				selectedPoli = $(this).val();
				loadQueueData();
			});

			$('#btn-refresh').on('click', function() {
				loadQueueData();
			});
		});
	</script>
</body>

</html>
