<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<?php
	$draft_message = isset($draft_message) ? (string) $draft_message : '';
	$show_create_modal = !empty($show_create_modal);
	$active_tab = isset($active_tab) ? (string) $active_tab : 'pending';
?>
<style>
	.notice-toolbar {
		display: flex;
		gap: 10px;
		margin-bottom: 14px;
		flex-wrap: wrap;
	}
	.notice-tabs {
		display: flex;
		gap: 10px;
		margin-bottom: 16px;
	}
	.notice-card {
		background: var(--panel);
		border-radius: 18px;
		padding: 16px;
		box-shadow: var(--shadow);
		margin-bottom: 14px;
		display: grid;
		gap: 12px;
	}
	.notice-meta {
		color: var(--muted);
		font-size: 0.9rem;
		margin-top: 6px;
	}
	.notice-actions {
		display: flex;
		gap: 10px;
		margin-top: 4px;
		justify-content: flex-end;
	}
	.notice-form {
		display: grid;
		gap: 14px;
	}
	.notice-form textarea {
		width: 100%;
		min-height: 140px;
		border-radius: 14px;
		border: 0;
		padding: 14px 16px;
		box-shadow: inset 0 0 0 1px var(--border);
		font-family: inherit;
		background: var(--field-bg);
		color: var(--field-ink);
		resize: vertical;
	}
	.notice-modal-backdrop {
		position: fixed;
		inset: 0;
		background: rgba(15, 23, 42, 0.44);
		display: none;
		align-items: center;
		justify-content: center;
		padding: 24px;
		z-index: 999;
	}
	.notice-modal-backdrop.is-open {
		display: flex;
	}
	.notice-modal-card {
		width: min(720px, 100%);
		background: var(--panel);
		border-radius: 24px;
		box-shadow: 0 24px 60px rgba(15, 23, 42, 0.24);
		overflow: hidden;
	}
	.notice-modal-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		gap: 12px;
		padding: 18px 20px;
		border-bottom: 1px solid var(--border);
	}
	.notice-modal-header h2 {
		margin: 0;
	}
	.notice-modal-close {
		width: 42px;
		height: 42px;
		border: 0;
		border-radius: 999px;
		background: var(--card);
		color: var(--ink);
		font-size: 1.2rem;
		cursor: pointer;
		box-shadow: inset 0 0 0 1px var(--border);
	}
	.notice-modal-body {
		padding: 20px;
	}
	@media (max-width: 760px) {
		.notice-modal-backdrop {
			padding: 12px;
		}
	}
</style>

<div class="notice-toolbar">
	<button class="btn" type="button" id="open-notice-modal">Agregar notificacion</button>
	<a class="btn btn-outline" href="<?php echo site_url('notificaciones/exportar'); ?>">Exportar CSV</a>
</div>

<?php if (!empty($flash_message)) { ?>
	<div class="panel" style="background:#e9f7ef; color:#1f5c3a; margin-bottom:16px;">
		<?php echo htmlspecialchars($flash_message, ENT_QUOTES, 'UTF-8'); ?>
	</div>
<?php } ?>
<?php if (!empty($flash_error)) { ?>
	<div class="panel" style="background:#fdecea; color:#7a2d2d; margin-bottom:16px;">
		<?php echo htmlspecialchars($flash_error, ENT_QUOTES, 'UTF-8'); ?>
	</div>
<?php } ?>

<div class="notice-tabs">
	<a class="btn<?php echo $active_tab === 'pending' ? '' : ' btn-outline'; ?>" href="<?php echo site_url('notificaciones'); ?>">Pendientes</a>
	<a class="btn<?php echo $active_tab === 'reviewed' ? '' : ' btn-outline'; ?>" href="<?php echo site_url('notificaciones?tab=reviewed'); ?>">Revisadas</a>
</div>

<?php if (empty($notifications)) { ?>
	<div class="panel" id="notice-empty-state">
		<?php echo $active_tab === 'reviewed' ? 'No hay notificaciones revisadas.' : 'No hay notificaciones pendientes.'; ?>
	</div>
	<div id="notice-list" style="display:none;"></div>
<?php } else { ?>
	<div id="notice-empty-state" class="panel" style="display:none;">
		<?php echo $active_tab === 'reviewed' ? 'No hay notificaciones revisadas.' : 'No hay notificaciones pendientes.'; ?>
	</div>
	<div id="notice-list">
	<?php foreach ($notifications as $notification) { ?>
		<div class="notice-card" data-notification-id="<?php echo (int) $notification['id']; ?>">
			<div style="display:flex; justify-content:space-between; gap:12px; align-items:flex-start;">
				<div>
					<strong><?php echo htmlspecialchars((string) $notification['message'], ENT_QUOTES, 'UTF-8'); ?></strong>
					<div class="notice-meta">
						<?php echo htmlspecialchars((string) $notification['created_by_name'], ENT_QUOTES, 'UTF-8'); ?> |
						<?php echo !empty($notification['created_at']) ? date('d/m/Y h:i A', strtotime($notification['created_at'])) : '-'; ?>
					</div>
				</div>
				<span class="badge <?php echo !empty($notification['is_reviewed']) ? 'success' : 'warning'; ?>">
					<?php echo !empty($notification['is_reviewed']) ? 'Revisado' : 'Pendiente'; ?>
				</span>
			</div>
			<?php if (empty($notification['is_reviewed'])) { ?>
				<form method="post" action="<?php echo site_url('notificaciones'); ?>" class="notice-actions js-review-notification-form" data-notification-id="<?php echo (int) $notification['id']; ?>">
					<input type="hidden" name="action_type" value="review" />
					<input type="hidden" name="notification_id" value="<?php echo (int) $notification['id']; ?>" />
					<button class="btn" type="submit">Marcar como revisado</button>
				</form>
			<?php } else { ?>
				<div class="notice-meta">
					Revisado por <?php echo htmlspecialchars((string) $notification['reviewed_by_name'], ENT_QUOTES, 'UTF-8'); ?> |
					<?php echo !empty($notification['reviewed_at']) ? date('d/m/Y h:i A', strtotime($notification['reviewed_at'])) : '-'; ?>
				</div>
			<?php } ?>
		</div>
	<?php } ?>
	</div>
<?php } ?>

<div id="notice-modal" class="notice-modal-backdrop<?php echo $show_create_modal ? ' is-open' : ''; ?>" aria-hidden="<?php echo $show_create_modal ? 'false' : 'true'; ?>">
	<div class="notice-modal-card" role="dialog" aria-modal="true" aria-labelledby="notice-modal-title">
		<div class="notice-modal-header">
			<h2 id="notice-modal-title">Nueva notificacion</h2>
			<button class="notice-modal-close" type="button" id="close-notice-modal" aria-label="Cerrar">x</button>
		</div>
		<div class="notice-modal-body">
			<form method="post" action="<?php echo site_url('notificaciones'); ?>" class="notice-form">
				<input type="hidden" name="action_type" value="create" />
				<textarea name="message" placeholder="Escribe una notificacion para el equipo..." required><?php echo htmlspecialchars($draft_message, ENT_QUOTES, 'UTF-8'); ?></textarea>
				<div class="actions" style="justify-content:flex-end; margin-top:0;">
					<button class="btn btn-outline" type="button" id="cancel-notice-modal">Cancelar</button>
					<button class="btn" type="submit">Publicar</button>
				</div>
			</form>
		</div>
	</div>
</div>

<script>
(function () {
	const modal = document.getElementById('notice-modal');
	const openButton = document.getElementById('open-notice-modal');
	const closeButton = document.getElementById('close-notice-modal');
	const cancelButton = document.getElementById('cancel-notice-modal');
	const noticeList = document.getElementById('notice-list');
	const emptyState = document.getElementById('notice-empty-state');
	const reviewForms = document.querySelectorAll('.js-review-notification-form');

	function openModal() {
		if (!modal) {
			return;
		}
		modal.classList.add('is-open');
		modal.setAttribute('aria-hidden', 'false');
		document.body.style.overflow = 'hidden';
	}

	function closeModal() {
		if (!modal) {
			return;
		}
		modal.classList.remove('is-open');
		modal.setAttribute('aria-hidden', 'true');
		document.body.style.overflow = '';
	}

	function syncNoticeEmptyState() {
		if (!emptyState) {
			return;
		}
		const hasCards = !!(noticeList && noticeList.querySelector('.notice-card'));
		if (noticeList) {
			noticeList.style.display = hasCards ? '' : 'none';
		}
		emptyState.style.display = hasCards ? 'none' : '';
	}

	if (openButton) {
		openButton.addEventListener('click', openModal);
	}
	if (closeButton) {
		closeButton.addEventListener('click', closeModal);
	}
	if (cancelButton) {
		cancelButton.addEventListener('click', closeModal);
	}
	if (modal) {
		modal.addEventListener('click', function (event) {
			if (event.target === modal) {
				closeModal();
			}
		});
	}

	reviewForms.forEach(function (form) {
		form.addEventListener('submit', function (event) {
			event.preventDefault();
			const button = form.querySelector('button[type="submit"]');
			if (button) {
				button.disabled = true;
			}

			fetch(form.action, {
				method: 'POST',
				headers: {
					'X-Requested-With': 'XMLHttpRequest',
					'Accept': 'application/json'
				},
				body: new FormData(form)
			}).then(function (response) {
				return response.json().then(function (payload) {
					return { ok: response.ok, payload: payload };
				}).catch(function () {
					return { ok: false, payload: null };
				});
			}).then(function (result) {
				if (!result.ok || !result.payload || !result.payload.success) {
					return;
				}
				const card = form.closest('.notice-card');
				if (card) {
					card.remove();
				}
				syncNoticeEmptyState();
			}).finally(function () {
				if (button) {
					button.disabled = false;
				}
			});
		});
	});

	document.addEventListener('keydown', function (event) {
		if (event.key === 'Escape') {
			closeModal();
		}
	});

	syncNoticeEmptyState();
})();
</script>
